blob: bd292079f16d5900ba2302d00aac1b9020866e6e [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"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
63#include "SchedulingPolicyService.h"
64
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Eric Laurent972a1732013-09-04 09:42:59 -0700132// Offloaded output thread standby delay: allows track transition without going to standby
133static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// Whether to use fast mixer
136static const enum {
137 FastMixer_Never, // never initialize or use: for debugging only
138 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
139 // normal mixer multiplier is 1
140 FastMixer_Static, // initialize if needed, then use all the time if initialized,
141 // multiplier is calculated based on min & max normal mixer buffer size
142 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
143 // multiplier is calculated based on min & max normal mixer buffer size
144 // FIXME for FastMixer_Dynamic:
145 // Supporting this option will require fixing HALs that can't handle large writes.
146 // For example, one HAL implementation returns an error from a large write,
147 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
148 // We could either fix the HAL implementations, or provide a wrapper that breaks
149 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
150} kUseFastMixer = FastMixer_Static;
151
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700152// Whether to use fast capture
153static const enum {
154 FastCapture_Never, // never initialize or use: for debugging only
155 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
156 FastCapture_Static, // initialize if needed, then use all the time if initialized
157} kUseFastCapture = FastCapture_Static;
158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Priorities for requestPriority
160static const int kPriorityAudioApp = 2;
161static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
165// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800166// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
167// So for now we just assume that client is double-buffered for fast tracks.
168// FIXME It would be better for client to tell AudioFlinger the value of N,
169// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800170// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700171
172// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasten03490092014-05-27 12:30:54 -0700175// The minimum and maximum allowed values
176static const int kFastTrackMultiplierMin = 1;
177static const int kFastTrackMultiplierMax = 2;
178
179// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
180static int sFastTrackMultiplier = kFastTrackMultiplier;
181
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182// See Thread::readOnlyHeap().
183// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
184// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
185// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700186static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// ----------------------------------------------------------------------------
189
Glenn Kasten03490092014-05-27 12:30:54 -0700190static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
191
192static void sFastTrackMultiplierInit()
193{
194 char value[PROPERTY_VALUE_MAX];
195 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
196 char *endptr;
197 unsigned long ul = strtoul(value, &endptr, 0);
198 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
199 sFastTrackMultiplier = (int) ul;
200 }
201 }
202}
203
204// ----------------------------------------------------------------------------
205
Eric Laurent81784c32012-11-19 14:55:58 -0800206#ifdef ADD_BATTERY_DATA
207// To collect the amplifier usage
208static void addBatteryData(uint32_t params) {
209 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
210 if (service == NULL) {
211 // it already logged
212 return;
213 }
214
215 service->addBatteryData(params);
216}
217#endif
218
219
220// ----------------------------------------------------------------------------
221// CPU Stats
222// ----------------------------------------------------------------------------
223
224class CpuStats {
225public:
226 CpuStats();
227 void sample(const String8 &title);
228#ifdef DEBUG_CPU_USAGE
229private:
230 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
231 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
232
233 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
234
235 int mCpuNum; // thread's current CPU number
236 int mCpukHz; // frequency of thread's current CPU in kHz
237#endif
238};
239
240CpuStats::CpuStats()
241#ifdef DEBUG_CPU_USAGE
242 : mCpuNum(-1), mCpukHz(-1)
243#endif
244{
245}
246
Glenn Kasten0f11b512014-01-31 16:18:54 -0800247void CpuStats::sample(const String8 &title
248#ifndef DEBUG_CPU_USAGE
249 __unused
250#endif
251 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800252#ifdef DEBUG_CPU_USAGE
253 // get current thread's delta CPU time in wall clock ns
254 double wcNs;
255 bool valid = mCpuUsage.sampleAndEnable(wcNs);
256
257 // record sample for wall clock statistics
258 if (valid) {
259 mWcStats.sample(wcNs);
260 }
261
262 // get the current CPU number
263 int cpuNum = sched_getcpu();
264
265 // get the current CPU frequency in kHz
266 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
267
268 // check if either CPU number or frequency changed
269 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
270 mCpuNum = cpuNum;
271 mCpukHz = cpukHz;
272 // ignore sample for purposes of cycles
273 valid = false;
274 }
275
276 // if no change in CPU number or frequency, then record sample for cycle statistics
277 if (valid && mCpukHz > 0) {
278 double cycles = wcNs * cpukHz * 0.000001;
279 mHzStats.sample(cycles);
280 }
281
282 unsigned n = mWcStats.n();
283 // mCpuUsage.elapsed() is expensive, so don't call it every loop
284 if ((n & 127) == 1) {
285 long long elapsed = mCpuUsage.elapsed();
286 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
287 double perLoop = elapsed / (double) n;
288 double perLoop100 = perLoop * 0.01;
289 double perLoop1k = perLoop * 0.001;
290 double mean = mWcStats.mean();
291 double stddev = mWcStats.stddev();
292 double minimum = mWcStats.minimum();
293 double maximum = mWcStats.maximum();
294 double meanCycles = mHzStats.mean();
295 double stddevCycles = mHzStats.stddev();
296 double minCycles = mHzStats.minimum();
297 double maxCycles = mHzStats.maximum();
298 mCpuUsage.resetElapsed();
299 mWcStats.reset();
300 mHzStats.reset();
301 ALOGD("CPU usage for %s over past %.1f secs\n"
302 " (%u mixer loops at %.1f mean ms per loop):\n"
303 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
304 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
305 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
306 title.string(),
307 elapsed * .000000001, n, perLoop * .000001,
308 mean * .001,
309 stddev * .001,
310 minimum * .001,
311 maximum * .001,
312 mean / perLoop100,
313 stddev / perLoop100,
314 minimum / perLoop100,
315 maximum / perLoop100,
316 meanCycles / perLoop1k,
317 stddevCycles / perLoop1k,
318 minCycles / perLoop1k,
319 maxCycles / perLoop1k);
320
321 }
322 }
323#endif
324};
325
326// ----------------------------------------------------------------------------
327// ThreadBase
328// ----------------------------------------------------------------------------
329
Glenn Kasten97b7b752014-09-28 13:04:24 -0700330// static
331const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
332{
333 switch (type) {
334 case MIXER:
335 return "MIXER";
336 case DIRECT:
337 return "DIRECT";
338 case DUPLICATING:
339 return "DUPLICATING";
340 case RECORD:
341 return "RECORD";
342 case OFFLOAD:
343 return "OFFLOAD";
344 default:
345 return "unknown";
346 }
347}
348
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800349String8 devicesToString(audio_devices_t devices)
350{
351 static const struct mapping {
352 audio_devices_t mDevices;
353 const char * mString;
354 } mappingsOut[] = {
355 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
356 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
357 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
358 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
359 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
360 AUDIO_DEVICE_NONE, "NONE", // must be last
361 }, mappingsIn[] = {
362 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
363 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
364 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
365 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
366 AUDIO_DEVICE_NONE, "NONE", // must be last
367 };
368 String8 result;
369 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
370 const mapping *entry;
371 if (devices & AUDIO_DEVICE_BIT_IN) {
372 devices &= ~AUDIO_DEVICE_BIT_IN;
373 entry = mappingsIn;
374 } else {
375 entry = mappingsOut;
376 }
377 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
378 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
379 if (devices & entry->mDevices) {
380 if (!result.isEmpty()) {
381 result.append("|");
382 }
383 result.append(entry->mString);
384 }
385 }
386 if (devices & ~allDevices) {
387 if (!result.isEmpty()) {
388 result.append("|");
389 }
390 result.appendFormat("0x%X", devices & ~allDevices);
391 }
392 if (result.isEmpty()) {
393 result.append(entry->mString);
394 }
395 return result;
396}
397
398String8 inputFlagsToString(audio_input_flags_t flags)
399{
400 static const struct mapping {
401 audio_input_flags_t mFlag;
402 const char * mString;
403 } mappings[] = {
404 AUDIO_INPUT_FLAG_FAST, "FAST",
405 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
406 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
407 };
408 String8 result;
409 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
410 const mapping *entry;
411 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
412 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
413 if (flags & entry->mFlag) {
414 if (!result.isEmpty()) {
415 result.append("|");
416 }
417 result.append(entry->mString);
418 }
419 }
420 if (flags & ~allFlags) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.appendFormat("0x%X", flags & ~allFlags);
425 }
426 if (result.isEmpty()) {
427 result.append(entry->mString);
428 }
429 return result;
430}
431
432String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700433{
434 static const struct mapping {
435 audio_output_flags_t mFlag;
436 const char * mString;
437 } mappings[] = {
438 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
439 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
440 AUDIO_OUTPUT_FLAG_FAST, "FAST",
441 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800442 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700443 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
444 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
445 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
446 };
447 String8 result;
448 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
449 const mapping *entry;
450 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
451 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
452 if (flags & entry->mFlag) {
453 if (!result.isEmpty()) {
454 result.append("|");
455 }
456 result.append(entry->mString);
457 }
458 }
459 if (flags & ~allFlags) {
460 if (!result.isEmpty()) {
461 result.append("|");
462 }
463 result.appendFormat("0x%X", flags & ~allFlags);
464 }
465 if (result.isEmpty()) {
466 result.append(entry->mString);
467 }
468 return result;
469}
470
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471const char *sourceToString(audio_source_t source)
472{
473 switch (source) {
474 case AUDIO_SOURCE_DEFAULT: return "default";
475 case AUDIO_SOURCE_MIC: return "mic";
476 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
477 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
478 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
479 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
480 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
481 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
482 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
483 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
484 case AUDIO_SOURCE_HOTWORD: return "hotword";
485 default: return "unknown";
486 }
487}
488
Eric Laurent81784c32012-11-19 14:55:58 -0800489AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
490 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
491 : Thread(false /*canCallJava*/),
492 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700493 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700494 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800495 // are set by PlaybackThread::readOutputParameters_l() or
496 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700497 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800498 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
499 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
500 // mName will be set by concrete (non-virtual) subclass
501 mDeathRecipient(new PMDeathRecipient(this))
502{
Eric Laurent296fb132015-05-01 11:38:42 -0700503 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800504}
505
506AudioFlinger::ThreadBase::~ThreadBase()
507{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700508 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700509 mConfigEvents.clear();
510
Eric Laurent81784c32012-11-19 14:55:58 -0800511 // do not lock the mutex in destructor
512 releaseWakeLock_l();
513 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800514 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800515 binder->unlinkToDeath(mDeathRecipient);
516 }
517}
518
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700519status_t AudioFlinger::ThreadBase::readyToRun()
520{
521 status_t status = initCheck();
522 if (status == NO_ERROR) {
523 ALOGI("AudioFlinger's thread %p ready to run", this);
524 } else {
525 ALOGE("No working audio driver found.");
526 }
527 return status;
528}
529
Eric Laurent81784c32012-11-19 14:55:58 -0800530void AudioFlinger::ThreadBase::exit()
531{
532 ALOGV("ThreadBase::exit");
533 // do any cleanup required for exit to succeed
534 preExit();
535 {
536 // This lock prevents the following race in thread (uniprocessor for illustration):
537 // if (!exitPending()) {
538 // // context switch from here to exit()
539 // // exit() calls requestExit(), what exitPending() observes
540 // // exit() calls signal(), which is dropped since no waiters
541 // // context switch back from exit() to here
542 // mWaitWorkCV.wait(...);
543 // // now thread is hung
544 // }
545 AutoMutex lock(mLock);
546 requestExit();
547 mWaitWorkCV.broadcast();
548 }
549 // When Thread::requestExitAndWait is made virtual and this method is renamed to
550 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
551 requestExitAndWait();
552}
553
554status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
555{
556 status_t status;
557
558 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
559 Mutex::Autolock _l(mLock);
560
Eric Laurent10351942014-05-08 18:49:52 -0700561 return sendSetParameterConfigEvent_l(keyValuePairs);
562}
563
564// sendConfigEvent_l() must be called with ThreadBase::mLock held
565// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
566status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
567{
568 status_t status = NO_ERROR;
569
570 mConfigEvents.add(event);
571 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800572 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700573 mLock.unlock();
574 {
575 Mutex::Autolock _l(event->mLock);
576 while (event->mWaitStatus) {
577 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
578 event->mStatus = TIMED_OUT;
579 event->mWaitStatus = false;
580 }
581 }
582 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800585 return status;
586}
587
Eric Laurent73e26b62015-04-27 16:55:58 -0700588void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800589{
590 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700591 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800592}
593
594// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700595void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800596{
Eric Laurent73e26b62015-04-27 16:55:58 -0700597 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700598 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800599}
600
601// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
602void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
603{
Eric Laurent10351942014-05-08 18:49:52 -0700604 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
605 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
Eric Laurent10351942014-05-08 18:49:52 -0700608// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
609status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent10351942014-05-08 18:49:52 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
612 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700613}
614
Eric Laurent1c333e22014-05-20 10:48:17 -0700615status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
616 const struct audio_patch *patch,
617 audio_patch_handle_t *handle)
618{
619 Mutex::Autolock _l(mLock);
620 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
621 status_t status = sendConfigEvent_l(configEvent);
622 if (status == NO_ERROR) {
623 CreateAudioPatchConfigEventData *data =
624 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
625 *handle = data->mHandle;
626 }
627 return status;
628}
629
630status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
631 const audio_patch_handle_t handle)
632{
633 Mutex::Autolock _l(mLock);
634 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
635 return sendConfigEvent_l(configEvent);
636}
637
638
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700639// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700640void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700641{
Eric Laurent10351942014-05-08 18:49:52 -0700642 bool configChanged = false;
643
Eric Laurent81784c32012-11-19 14:55:58 -0800644 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700645 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
646 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800647 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700648 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700649 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700650 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
651 // FIXME Need to understand why this has to be done asynchronously
652 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700653 true /*asynchronous*/);
654 if (err != 0) {
655 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700656 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700657 }
658 } break;
659 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700660 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700661 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700662 } break;
663 case CFG_EVENT_SET_PARAMETER: {
664 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
665 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
666 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700667 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700668 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700669 case CFG_EVENT_CREATE_AUDIO_PATCH: {
670 CreateAudioPatchConfigEventData *data =
671 (CreateAudioPatchConfigEventData *)event->mData.get();
672 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
673 } break;
674 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
675 ReleaseAudioPatchConfigEventData *data =
676 (ReleaseAudioPatchConfigEventData *)event->mData.get();
677 event->mStatus = releaseAudioPatch_l(data->mHandle);
678 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700679 default:
Eric Laurent10351942014-05-08 18:49:52 -0700680 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800682 }
Eric Laurent10351942014-05-08 18:49:52 -0700683 {
684 Mutex::Autolock _l(event->mLock);
685 if (event->mWaitStatus) {
686 event->mWaitStatus = false;
687 event->mCond.signal();
688 }
689 }
690 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
691 }
692
693 if (configChanged) {
694 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800695 }
Eric Laurent81784c32012-11-19 14:55:58 -0800696}
697
Marco Nelissenb2208842014-02-07 14:00:50 -0800698String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
699 String8 s;
700 if (output) {
701 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
702 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
703 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
704 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
705 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
706 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
707 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
708 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
709 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
710 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
711 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
712 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
713 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
714 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
715 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
716 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
717 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
718 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
719 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
720 } else {
721 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
722 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
723 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
724 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
725 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
726 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
727 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
728 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
729 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
730 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
731 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
732 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
733 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
734 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
735 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
736 }
737 int len = s.length();
738 if (s.length() > 2) {
739 char *str = s.lockBuffer(len);
740 s.unlockBuffer(len - 2);
741 }
742 return s;
743}
744
Glenn Kasten0f11b512014-01-31 16:18:54 -0800745void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
747 const size_t SIZE = 256;
748 char buffer[SIZE];
749 String8 result;
750
751 bool locked = AudioFlinger::dumpTryLock(mLock);
752 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700753 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800754 }
755
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800756 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700757 dprintf(fd, " I/O handle: %d\n", mId);
758 dprintf(fd, " TID: %d\n", getTid());
759 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700760 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700761 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700762 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700763 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700764 dprintf(fd, " Channel count: %u\n", mChannelCount);
765 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800766 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700767 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
768 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700769 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800770 size_t numConfig = mConfigEvents.size();
771 if (numConfig) {
772 for (size_t i = 0; i < numConfig; i++) {
773 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700774 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800775 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700776 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800777 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700778 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800779 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800780 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
781 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
782 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800783
784 if (locked) {
785 mLock.unlock();
786 }
787}
788
789void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
790{
791 const size_t SIZE = 256;
792 char buffer[SIZE];
793 String8 result;
794
Marco Nelissenb2208842014-02-07 14:00:50 -0800795 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000796 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800797 write(fd, buffer, strlen(buffer));
798
Marco Nelissenb2208842014-02-07 14:00:50 -0800799 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800800 sp<EffectChain> chain = mEffectChains[i];
801 if (chain != 0) {
802 chain->dump(fd, args);
803 }
804 }
805}
806
Marco Nelissene14a5d62013-10-03 08:51:24 -0700807void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800808{
809 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700810 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800811}
812
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100813String16 AudioFlinger::ThreadBase::getWakeLockTag()
814{
815 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800816 case MIXER:
817 return String16("AudioMix");
818 case DIRECT:
819 return String16("AudioDirectOut");
820 case DUPLICATING:
821 return String16("AudioDup");
822 case RECORD:
823 return String16("AudioIn");
824 case OFFLOAD:
825 return String16("AudioOffload");
826 default:
827 ALOG_ASSERT(false);
828 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100829 }
830}
831
Marco Nelissene14a5d62013-10-03 08:51:24 -0700832void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800833{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800834 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800835 if (mPowerManager != 0) {
836 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700837 status_t status;
838 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700839 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700840 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100841 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700842 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700843 uid,
844 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700845 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700846 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700847 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100848 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700849 String16("media"),
850 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700851 }
Eric Laurent81784c32012-11-19 14:55:58 -0800852 if (status == NO_ERROR) {
853 mWakeLockToken = binder;
854 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800855 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800856 }
857}
858
859void AudioFlinger::ThreadBase::releaseWakeLock()
860{
861 Mutex::Autolock _l(mLock);
862 releaseWakeLock_l();
863}
864
865void AudioFlinger::ThreadBase::releaseWakeLock_l()
866{
867 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800868 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800869 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700870 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
871 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
873 mWakeLockToken.clear();
874 }
875}
876
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800877void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
878 Mutex::Autolock _l(mLock);
879 updateWakeLockUids_l(uids);
880}
881
882void AudioFlinger::ThreadBase::getPowerManager_l() {
883
884 if (mPowerManager == 0) {
885 // use checkService() to avoid blocking if power service is not up yet
886 sp<IBinder> binder =
887 defaultServiceManager()->checkService(String16("power"));
888 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800889 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800890 } else {
891 mPowerManager = interface_cast<IPowerManager>(binder);
892 binder->linkToDeath(mDeathRecipient);
893 }
894 }
895}
896
897void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
898
899 getPowerManager_l();
900 if (mWakeLockToken == NULL) {
901 ALOGE("no wake lock to update!");
902 return;
903 }
904 if (mPowerManager != 0) {
905 sp<IBinder> binder = new BBinder();
906 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700907 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
908 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800910 }
911}
912
Eric Laurent81784c32012-11-19 14:55:58 -0800913void AudioFlinger::ThreadBase::clearPowerManager()
914{
915 Mutex::Autolock _l(mLock);
916 releaseWakeLock_l();
917 mPowerManager.clear();
918}
919
Glenn Kasten0f11b512014-01-31 16:18:54 -0800920void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800921{
922 sp<ThreadBase> thread = mThread.promote();
923 if (thread != 0) {
924 thread->clearPowerManager();
925 }
926 ALOGW("power manager service died !!!");
927}
928
929void AudioFlinger::ThreadBase::setEffectSuspended(
930 const effect_uuid_t *type, bool suspend, int sessionId)
931{
932 Mutex::Autolock _l(mLock);
933 setEffectSuspended_l(type, suspend, sessionId);
934}
935
936void AudioFlinger::ThreadBase::setEffectSuspended_l(
937 const effect_uuid_t *type, bool suspend, int sessionId)
938{
939 sp<EffectChain> chain = getEffectChain_l(sessionId);
940 if (chain != 0) {
941 if (type != NULL) {
942 chain->setEffectSuspended_l(type, suspend);
943 } else {
944 chain->setEffectSuspendedAll_l(suspend);
945 }
946 }
947
948 updateSuspendedSessions_l(type, suspend, sessionId);
949}
950
951void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
952{
953 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
954 if (index < 0) {
955 return;
956 }
957
958 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
959 mSuspendedSessions.valueAt(index);
960
961 for (size_t i = 0; i < sessionEffects.size(); i++) {
962 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
963 for (int j = 0; j < desc->mRefCount; j++) {
964 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
965 chain->setEffectSuspendedAll_l(true);
966 } else {
967 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
968 desc->mType.timeLow);
969 chain->setEffectSuspended_l(&desc->mType, true);
970 }
971 }
972 }
973}
974
975void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
976 bool suspend,
977 int sessionId)
978{
979 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
980
981 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
982
983 if (suspend) {
984 if (index >= 0) {
985 sessionEffects = mSuspendedSessions.valueAt(index);
986 } else {
987 mSuspendedSessions.add(sessionId, sessionEffects);
988 }
989 } else {
990 if (index < 0) {
991 return;
992 }
993 sessionEffects = mSuspendedSessions.valueAt(index);
994 }
995
996
997 int key = EffectChain::kKeyForSuspendAll;
998 if (type != NULL) {
999 key = type->timeLow;
1000 }
1001 index = sessionEffects.indexOfKey(key);
1002
1003 sp<SuspendedSessionDesc> desc;
1004 if (suspend) {
1005 if (index >= 0) {
1006 desc = sessionEffects.valueAt(index);
1007 } else {
1008 desc = new SuspendedSessionDesc();
1009 if (type != NULL) {
1010 desc->mType = *type;
1011 }
1012 sessionEffects.add(key, desc);
1013 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1014 }
1015 desc->mRefCount++;
1016 } else {
1017 if (index < 0) {
1018 return;
1019 }
1020 desc = sessionEffects.valueAt(index);
1021 if (--desc->mRefCount == 0) {
1022 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1023 sessionEffects.removeItemsAt(index);
1024 if (sessionEffects.isEmpty()) {
1025 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1026 sessionId);
1027 mSuspendedSessions.removeItem(sessionId);
1028 }
1029 }
1030 }
1031 if (!sessionEffects.isEmpty()) {
1032 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1033 }
1034}
1035
1036void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1037 bool enabled,
1038 int sessionId)
1039{
1040 Mutex::Autolock _l(mLock);
1041 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1042}
1043
1044void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1045 bool enabled,
1046 int sessionId)
1047{
1048 if (mType != RECORD) {
1049 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1050 // another session. This gives the priority to well behaved effect control panels
1051 // and applications not using global effects.
1052 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1053 // global effects
1054 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1055 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1056 }
1057 }
1058
1059 sp<EffectChain> chain = getEffectChain_l(sessionId);
1060 if (chain != 0) {
1061 chain->checkSuspendOnEffectEnabled(effect, enabled);
1062 }
1063}
1064
1065// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1066sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1067 const sp<AudioFlinger::Client>& client,
1068 const sp<IEffectClient>& effectClient,
1069 int32_t priority,
1070 int sessionId,
1071 effect_descriptor_t *desc,
1072 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001073 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001074{
1075 sp<EffectModule> effect;
1076 sp<EffectHandle> handle;
1077 status_t lStatus;
1078 sp<EffectChain> chain;
1079 bool chainCreated = false;
1080 bool effectCreated = false;
1081 bool effectRegistered = false;
1082
1083 lStatus = initCheck();
1084 if (lStatus != NO_ERROR) {
1085 ALOGW("createEffect_l() Audio driver not initialized.");
1086 goto Exit;
1087 }
1088
Andy Hung98ef9782014-03-04 14:46:50 -08001089 // Reject any effect on Direct output threads for now, since the format of
1090 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1091 if (mType == DIRECT) {
1092 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001093 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001094 lStatus = BAD_VALUE;
1095 goto Exit;
1096 }
1097
Andy Hung389cfdb2014-08-07 17:49:53 -07001098 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001099 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001100 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1101 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1102 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001103 lStatus = BAD_VALUE;
1104 goto Exit;
1105 }
1106
Eric Laurent5baf2af2013-09-12 17:37:00 -07001107 // Allow global effects only on offloaded and mixer threads
1108 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1109 switch (mType) {
1110 case MIXER:
1111 case OFFLOAD:
1112 break;
1113 case DIRECT:
1114 case DUPLICATING:
1115 case RECORD:
1116 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001117 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1118 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001119 lStatus = BAD_VALUE;
1120 goto Exit;
1121 }
Eric Laurent81784c32012-11-19 14:55:58 -08001122 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001123
Eric Laurent81784c32012-11-19 14:55:58 -08001124 // Only Pre processor effects are allowed on input threads and only on input threads
1125 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1126 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1127 desc->name, desc->flags, mType);
1128 lStatus = BAD_VALUE;
1129 goto Exit;
1130 }
1131
1132 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1133
1134 { // scope for mLock
1135 Mutex::Autolock _l(mLock);
1136
1137 // check for existing effect chain with the requested audio session
1138 chain = getEffectChain_l(sessionId);
1139 if (chain == 0) {
1140 // create a new chain for this session
1141 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1142 chain = new EffectChain(this, sessionId);
1143 addEffectChain_l(chain);
1144 chain->setStrategy(getStrategyForSession_l(sessionId));
1145 chainCreated = true;
1146 } else {
1147 effect = chain->getEffectFromDesc_l(desc);
1148 }
1149
1150 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1151
1152 if (effect == 0) {
1153 int id = mAudioFlinger->nextUniqueId();
1154 // Check CPU and memory usage
1155 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1156 if (lStatus != NO_ERROR) {
1157 goto Exit;
1158 }
1159 effectRegistered = true;
1160 // create a new effect module if none present in the chain
1161 effect = new EffectModule(this, chain, desc, id, sessionId);
1162 lStatus = effect->status();
1163 if (lStatus != NO_ERROR) {
1164 goto Exit;
1165 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001166 effect->setOffloaded(mType == OFFLOAD, mId);
1167
Eric Laurent81784c32012-11-19 14:55:58 -08001168 lStatus = chain->addEffect_l(effect);
1169 if (lStatus != NO_ERROR) {
1170 goto Exit;
1171 }
1172 effectCreated = true;
1173
1174 effect->setDevice(mOutDevice);
1175 effect->setDevice(mInDevice);
1176 effect->setMode(mAudioFlinger->getMode());
1177 effect->setAudioSource(mAudioSource);
1178 }
1179 // create effect handle and connect it to effect module
1180 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001181 lStatus = handle->initCheck();
1182 if (lStatus == OK) {
1183 lStatus = effect->addHandle(handle.get());
1184 }
Eric Laurent81784c32012-11-19 14:55:58 -08001185 if (enabled != NULL) {
1186 *enabled = (int)effect->isEnabled();
1187 }
1188 }
1189
1190Exit:
1191 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1192 Mutex::Autolock _l(mLock);
1193 if (effectCreated) {
1194 chain->removeEffect_l(effect);
1195 }
1196 if (effectRegistered) {
1197 AudioSystem::unregisterEffect(effect->id());
1198 }
1199 if (chainCreated) {
1200 removeEffectChain_l(chain);
1201 }
1202 handle.clear();
1203 }
1204
Glenn Kasten9156ef32013-08-06 15:39:08 -07001205 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001206 return handle;
1207}
1208
1209sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1210{
1211 Mutex::Autolock _l(mLock);
1212 return getEffect_l(sessionId, effectId);
1213}
1214
1215sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1216{
1217 sp<EffectChain> chain = getEffectChain_l(sessionId);
1218 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1219}
1220
1221// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1222// PlaybackThread::mLock held
1223status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1224{
1225 // check for existing effect chain with the requested audio session
1226 int sessionId = effect->sessionId();
1227 sp<EffectChain> chain = getEffectChain_l(sessionId);
1228 bool chainCreated = false;
1229
Eric Laurent5baf2af2013-09-12 17:37:00 -07001230 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1231 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1232 this, effect->desc().name, effect->desc().flags);
1233
Eric Laurent81784c32012-11-19 14:55:58 -08001234 if (chain == 0) {
1235 // create a new chain for this session
1236 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1237 chain = new EffectChain(this, sessionId);
1238 addEffectChain_l(chain);
1239 chain->setStrategy(getStrategyForSession_l(sessionId));
1240 chainCreated = true;
1241 }
1242 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1243
1244 if (chain->getEffectFromId_l(effect->id()) != 0) {
1245 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1246 this, effect->desc().name, chain.get());
1247 return BAD_VALUE;
1248 }
1249
Eric Laurent5baf2af2013-09-12 17:37:00 -07001250 effect->setOffloaded(mType == OFFLOAD, mId);
1251
Eric Laurent81784c32012-11-19 14:55:58 -08001252 status_t status = chain->addEffect_l(effect);
1253 if (status != NO_ERROR) {
1254 if (chainCreated) {
1255 removeEffectChain_l(chain);
1256 }
1257 return status;
1258 }
1259
1260 effect->setDevice(mOutDevice);
1261 effect->setDevice(mInDevice);
1262 effect->setMode(mAudioFlinger->getMode());
1263 effect->setAudioSource(mAudioSource);
1264 return NO_ERROR;
1265}
1266
1267void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1268
1269 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1270 effect_descriptor_t desc = effect->desc();
1271 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1272 detachAuxEffect_l(effect->id());
1273 }
1274
1275 sp<EffectChain> chain = effect->chain().promote();
1276 if (chain != 0) {
1277 // remove effect chain if removing last effect
1278 if (chain->removeEffect_l(effect) == 0) {
1279 removeEffectChain_l(chain);
1280 }
1281 } else {
1282 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1283 }
1284}
1285
1286void AudioFlinger::ThreadBase::lockEffectChains_l(
1287 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1288{
1289 effectChains = mEffectChains;
1290 for (size_t i = 0; i < mEffectChains.size(); i++) {
1291 mEffectChains[i]->lock();
1292 }
1293}
1294
1295void AudioFlinger::ThreadBase::unlockEffectChains(
1296 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1297{
1298 for (size_t i = 0; i < effectChains.size(); i++) {
1299 effectChains[i]->unlock();
1300 }
1301}
1302
1303sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1304{
1305 Mutex::Autolock _l(mLock);
1306 return getEffectChain_l(sessionId);
1307}
1308
1309sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1310{
1311 size_t size = mEffectChains.size();
1312 for (size_t i = 0; i < size; i++) {
1313 if (mEffectChains[i]->sessionId() == sessionId) {
1314 return mEffectChains[i];
1315 }
1316 }
1317 return 0;
1318}
1319
1320void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1321{
1322 Mutex::Autolock _l(mLock);
1323 size_t size = mEffectChains.size();
1324 for (size_t i = 0; i < size; i++) {
1325 mEffectChains[i]->setMode_l(mode);
1326 }
1327}
1328
Eric Laurent83b88082014-06-20 18:31:16 -07001329void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1330{
1331 config->type = AUDIO_PORT_TYPE_MIX;
1332 config->ext.mix.handle = mId;
1333 config->sample_rate = mSampleRate;
1334 config->format = mFormat;
1335 config->channel_mask = mChannelMask;
1336 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1337 AUDIO_PORT_CONFIG_FORMAT;
1338}
1339
1340
Eric Laurent81784c32012-11-19 14:55:58 -08001341// ----------------------------------------------------------------------------
1342// Playback
1343// ----------------------------------------------------------------------------
1344
1345AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1346 AudioStreamOut* output,
1347 audio_io_handle_t id,
1348 audio_devices_t device,
1349 type_t type)
1350 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001351 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001352 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001353 mMixerBuffer(NULL),
1354 mMixerBufferSize(0),
1355 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1356 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001357 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001358 mEffectBuffer(NULL),
1359 mEffectBufferSize(0),
1360 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1361 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001362 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001363 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001364 // mStreamTypes[] initialized in constructor body
1365 mOutput(output),
1366 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1367 mMixerStatus(MIXER_IDLE),
1368 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1369 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001370 mBytesRemaining(0),
1371 mCurrentWriteLength(0),
1372 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001373 mWriteAckSequence(0),
1374 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001375 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001376 mScreenState(AudioFlinger::mScreenState),
1377 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001378 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001379 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001380 // mLatchD, mLatchQ,
1381 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001382{
Glenn Kastend7dca052015-03-05 16:05:54 -08001383 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1384 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001385
1386 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1387 // it would be safer to explicitly pass initial masterVolume/masterMute as
1388 // parameter.
1389 //
1390 // If the HAL we are using has support for master volume or master mute,
1391 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1392 // and the mute set to false).
1393 mMasterVolume = audioFlinger->masterVolume_l();
1394 mMasterMute = audioFlinger->masterMute_l();
1395 if (mOutput && mOutput->audioHwDev) {
1396 if (mOutput->audioHwDev->canSetMasterVolume()) {
1397 mMasterVolume = 1.0;
1398 }
1399
1400 if (mOutput->audioHwDev->canSetMasterMute()) {
1401 mMasterMute = false;
1402 }
1403 }
1404
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001405 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001406
Eric Laurent223fd5c2014-11-11 13:43:36 -08001407 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001408 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001409 stream = (audio_stream_type_t) (stream + 1)) {
1410 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1411 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1412 }
Eric Laurent81784c32012-11-19 14:55:58 -08001413}
1414
1415AudioFlinger::PlaybackThread::~PlaybackThread()
1416{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001417 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001418 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001419 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001420 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001421}
1422
1423void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1424{
1425 dumpInternals(fd, args);
1426 dumpTracks(fd, args);
1427 dumpEffectChains(fd, args);
1428}
1429
Glenn Kasten0f11b512014-01-31 16:18:54 -08001430void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001431{
1432 const size_t SIZE = 256;
1433 char buffer[SIZE];
1434 String8 result;
1435
Marco Nelissenb2208842014-02-07 14:00:50 -08001436 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001437 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1438 const stream_type_t *st = &mStreamTypes[i];
1439 if (i > 0) {
1440 result.appendFormat(", ");
1441 }
1442 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1443 if (st->mute) {
1444 result.append("M");
1445 }
1446 }
1447 result.append("\n");
1448 write(fd, result.string(), result.length());
1449 result.clear();
1450
Eric Laurent81784c32012-11-19 14:55:58 -08001451 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1452 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001453 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001454 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001455
1456 size_t numtracks = mTracks.size();
1457 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001458 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001459 size_t numactiveseen = 0;
1460 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001461 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001462 Track::appendDumpHeader(result);
1463 for (size_t i = 0; i < numtracks; ++i) {
1464 sp<Track> track = mTracks[i];
1465 if (track != 0) {
1466 bool active = mActiveTracks.indexOf(track) >= 0;
1467 if (active) {
1468 numactiveseen++;
1469 }
1470 track->dump(buffer, SIZE, active);
1471 result.append(buffer);
1472 }
1473 }
1474 } else {
1475 result.append("\n");
1476 }
1477 if (numactiveseen != numactive) {
1478 // some tracks in the active list were not in the tracks list
1479 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1480 " not in the track list\n");
1481 result.append(buffer);
1482 Track::appendDumpHeader(result);
1483 for (size_t i = 0; i < numactive; ++i) {
1484 sp<Track> track = mActiveTracks[i].promote();
1485 if (track != 0 && mTracks.indexOf(track) < 0) {
1486 track->dump(buffer, SIZE, true);
1487 result.append(buffer);
1488 }
1489 }
1490 }
1491
1492 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001493}
1494
1495void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1496{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001497 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001498
1499 dumpBase(fd, args);
1500
Elliott Hughes87cebad2014-05-22 10:14:43 -07001501 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1502 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1503 dprintf(fd, " Total writes: %d\n", mNumWrites);
1504 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1505 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1506 dprintf(fd, " Suspend count: %d\n", mSuspended);
1507 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1508 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1509 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1510 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001511 AudioStreamOut *output = mOutput;
1512 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1513 String8 flagsAsString = outputFlagsToString(flags);
1514 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001515}
1516
1517// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001518
1519void AudioFlinger::PlaybackThread::onFirstRef()
1520{
Glenn Kastend7dca052015-03-05 16:05:54 -08001521 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001522}
1523
1524// ThreadBase virtuals
1525void AudioFlinger::PlaybackThread::preExit()
1526{
1527 ALOGV(" preExit()");
1528 // FIXME this is using hard-coded strings but in the future, this functionality will be
1529 // converted to use audio HAL extensions required to support tunneling
1530 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1531}
1532
1533// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1534sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1535 const sp<AudioFlinger::Client>& client,
1536 audio_stream_type_t streamType,
1537 uint32_t sampleRate,
1538 audio_format_t format,
1539 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001540 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001541 const sp<IMemory>& sharedBuffer,
1542 int sessionId,
1543 IAudioFlinger::track_flags_t *flags,
1544 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001545 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001546 status_t *status)
1547{
Glenn Kasten74935e42013-12-19 08:56:45 -08001548 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001549 sp<Track> track;
1550 status_t lStatus;
1551
1552 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1553
1554 // client expresses a preference for FAST, but we get the final say
1555 if (*flags & IAudioFlinger::TRACK_FAST) {
1556 if (
1557 // not timed
1558 (!isTimed) &&
1559 // either of these use cases:
1560 (
1561 // use case 1: shared buffer with any frame count
1562 (
1563 (sharedBuffer != 0)
1564 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001565 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001566 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001567 // we formerly checked for a callback handler (non-0 tid),
1568 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001569 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001570 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001571 )
1572 ) &&
1573 // PCM data
1574 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001575 // TODO: extract as a data library function that checks that a computationally
1576 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001577 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001578 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1579 (channelMask == AUDIO_CHANNEL_OUT_MONO
1580 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001581 // hardware sample rate
1582 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001583 // normal mixer has an associated fast mixer
1584 hasFastMixer() &&
1585 // there are sufficient fast track slots available
1586 (mFastTrackAvailMask != 0)
1587 // FIXME test that MixerThread for this fast track has a capable output HAL
1588 // FIXME add a permission test also?
1589 ) {
1590 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1591 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001592 // read the fast track multiplier property the first time it is needed
1593 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1594 if (ok != 0) {
1595 ALOGE("%s pthread_once failed: %d", __func__, ok);
1596 }
1597 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001598 }
1599 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1600 frameCount, mFrameCount);
1601 } else {
1602 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001603 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1604 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001605 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001606 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001607 audio_is_linear_pcm(format),
1608 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1609 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001610 }
1611 }
1612 // For normal PCM streaming tracks, update minimum frame count.
1613 // For compatibility with AudioTrack calculation, buffer depth is forced
1614 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1615 // This is probably too conservative, but legacy application code may depend on it.
1616 // If you change this calculation, also review the start threshold which is related.
1617 if (!(*flags & IAudioFlinger::TRACK_FAST)
1618 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001619 // this must match AudioTrack.cpp calculateMinFrameCount().
1620 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001621 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1622 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1623 if (minBufCount < 2) {
1624 minBufCount = 2;
1625 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001626 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1627 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001628 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001629 minBufCount * sourceFramesNeededWithTimestretch(
1630 sampleRate, mNormalFrameCount,
1631 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001632 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001633 frameCount = minFrameCount;
1634 }
Eric Laurent81784c32012-11-19 14:55:58 -08001635 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001636 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001637
Glenn Kastenc3df8382014-03-13 15:05:25 -07001638 switch (mType) {
1639
1640 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001641 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001642 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001643 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1644 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001645 sampleRate, format, channelMask, mOutput, mFormat);
1646 lStatus = BAD_VALUE;
1647 goto Exit;
1648 }
1649 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001650 break;
1651
1652 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001653 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001654 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1655 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001656 sampleRate, format, channelMask, mOutput, mFormat);
1657 lStatus = BAD_VALUE;
1658 goto Exit;
1659 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001660 break;
1661
1662 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001663 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001664 ALOGE("createTrack_l() Bad parameter: format %#x \""
1665 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001666 format, mOutput, mFormat);
1667 lStatus = BAD_VALUE;
1668 goto Exit;
1669 }
Andy Hungcd044842014-08-07 11:04:34 -07001670 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001671 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1672 lStatus = BAD_VALUE;
1673 goto Exit;
1674 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001675 break;
1676
Eric Laurent81784c32012-11-19 14:55:58 -08001677 }
1678
1679 lStatus = initCheck();
1680 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001681 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001682 goto Exit;
1683 }
1684
1685 { // scope for mLock
1686 Mutex::Autolock _l(mLock);
1687
1688 // all tracks in same audio session must share the same routing strategy otherwise
1689 // conflicts will happen when tracks are moved from one output to another by audio policy
1690 // manager
1691 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1692 for (size_t i = 0; i < mTracks.size(); ++i) {
1693 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001694 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001695 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1696 if (sessionId == t->sessionId() && strategy != actual) {
1697 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1698 strategy, actual);
1699 lStatus = BAD_VALUE;
1700 goto Exit;
1701 }
1702 }
1703 }
1704
1705 if (!isTimed) {
1706 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001707 channelMask, frameCount, NULL, sharedBuffer,
1708 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001709 } else {
1710 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001711 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001712 }
Glenn Kasten03003332013-08-06 15:40:54 -07001713
1714 // new Track always returns non-NULL,
1715 // but TimedTrack::create() is a factory that could fail by returning NULL
1716 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1717 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001718 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001719 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001720 goto Exit;
1721 }
1722 mTracks.add(track);
1723
1724 sp<EffectChain> chain = getEffectChain_l(sessionId);
1725 if (chain != 0) {
1726 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1727 track->setMainBuffer(chain->inBuffer());
1728 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1729 chain->incTrackCnt();
1730 }
1731
1732 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1733 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1734 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1735 // so ask activity manager to do this on our behalf
1736 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1737 }
1738 }
1739
1740 lStatus = NO_ERROR;
1741
1742Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001743 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001744 return track;
1745}
1746
1747uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1748{
1749 return latency;
1750}
1751
1752uint32_t AudioFlinger::PlaybackThread::latency() const
1753{
1754 Mutex::Autolock _l(mLock);
1755 return latency_l();
1756}
1757uint32_t AudioFlinger::PlaybackThread::latency_l() const
1758{
1759 if (initCheck() == NO_ERROR) {
1760 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1761 } else {
1762 return 0;
1763 }
1764}
1765
1766void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1767{
1768 Mutex::Autolock _l(mLock);
1769 // Don't apply master volume in SW if our HAL can do it for us.
1770 if (mOutput && mOutput->audioHwDev &&
1771 mOutput->audioHwDev->canSetMasterVolume()) {
1772 mMasterVolume = 1.0;
1773 } else {
1774 mMasterVolume = value;
1775 }
1776}
1777
1778void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1779{
1780 Mutex::Autolock _l(mLock);
1781 // Don't apply master mute in SW if our HAL can do it for us.
1782 if (mOutput && mOutput->audioHwDev &&
1783 mOutput->audioHwDev->canSetMasterMute()) {
1784 mMasterMute = false;
1785 } else {
1786 mMasterMute = muted;
1787 }
1788}
1789
1790void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1791{
1792 Mutex::Autolock _l(mLock);
1793 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001794 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001795}
1796
1797void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1798{
1799 Mutex::Autolock _l(mLock);
1800 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001801 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001802}
1803
1804float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1805{
1806 Mutex::Autolock _l(mLock);
1807 return mStreamTypes[stream].volume;
1808}
1809
1810// addTrack_l() must be called with ThreadBase::mLock held
1811status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1812{
1813 status_t status = ALREADY_EXISTS;
1814
1815 // set retry count for buffer fill
1816 track->mRetryCount = kMaxTrackStartupRetries;
1817 if (mActiveTracks.indexOf(track) < 0) {
1818 // the track is newly added, make sure it fills up all its
1819 // buffers before playing. This is to ensure the client will
1820 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001821 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001822 TrackBase::track_state state = track->mState;
1823 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001824 status = AudioSystem::startOutput(mId, track->streamType(),
1825 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001826 mLock.lock();
1827 // abort track was stopped/paused while we released the lock
1828 if (state != track->mState) {
1829 if (status == NO_ERROR) {
1830 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001831 AudioSystem::stopOutput(mId, track->streamType(),
1832 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001833 mLock.lock();
1834 }
1835 return INVALID_OPERATION;
1836 }
1837 // abort if start is rejected by audio policy manager
1838 if (status != NO_ERROR) {
1839 return PERMISSION_DENIED;
1840 }
1841#ifdef ADD_BATTERY_DATA
1842 // to track the speaker usage
1843 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1844#endif
1845 }
1846
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001847 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001848 track->mResetDone = false;
1849 track->mPresentationCompleteFrames = 0;
1850 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001851 mWakeLockUids.add(track->uid());
1852 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001853 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001854 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1855 if (chain != 0) {
1856 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1857 track->sessionId());
1858 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001859 }
1860
1861 status = NO_ERROR;
1862 }
1863
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001864 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001865 return status;
1866}
1867
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001869{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001870 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001871 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001872 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1873 track->mState = TrackBase::STOPPED;
1874 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001875 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001876 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001877 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001878 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001879
1880 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001881}
1882
1883void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1884{
1885 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1886 mTracks.remove(track);
1887 deleteTrackName_l(track->name());
1888 // redundant as track is about to be destroyed, for dumpsys only
1889 track->mName = -1;
1890 if (track->isFastTrack()) {
1891 int index = track->mFastIndex;
1892 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1893 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1894 mFastTrackAvailMask |= 1 << index;
1895 // redundant as track is about to be destroyed, for dumpsys only
1896 track->mFastIndex = -1;
1897 }
1898 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1899 if (chain != 0) {
1900 chain->decTrackCnt();
1901 }
1902}
1903
Eric Laurentede6c3b2013-09-19 14:37:46 -07001904void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001905{
1906 // Thread could be blocked waiting for async
1907 // so signal it to handle state changes immediately
1908 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1909 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1910 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001911 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001912}
1913
Eric Laurent81784c32012-11-19 14:55:58 -08001914String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1915{
Eric Laurent81784c32012-11-19 14:55:58 -08001916 Mutex::Autolock _l(mLock);
1917 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001918 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001919 }
1920
Glenn Kastend8ea6992013-07-16 14:17:15 -07001921 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1922 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001923 free(s);
1924 return out_s8;
1925}
1926
Eric Laurent73e26b62015-04-27 16:55:58 -07001927void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
1928 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
1929 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08001930
Eric Laurent73e26b62015-04-27 16:55:58 -07001931 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08001932
1933 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07001934 case AUDIO_OUTPUT_OPENED:
1935 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07001936 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07001937 desc->mChannelMask = mChannelMask;
1938 desc->mSamplingRate = mSampleRate;
1939 desc->mFormat = mFormat;
1940 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08001941 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07001942 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001943 break;
1944
Eric Laurent73e26b62015-04-27 16:55:58 -07001945 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08001946 default:
1947 break;
1948 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001949 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001950}
1951
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952void AudioFlinger::PlaybackThread::writeCallback()
1953{
1954 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001955 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001956}
1957
1958void AudioFlinger::PlaybackThread::drainCallback()
1959{
1960 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001961 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001962}
1963
Eric Laurent3b4529e2013-09-05 18:09:19 -07001964void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965{
1966 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001967 // reject out of sequence requests
1968 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1969 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 mWaitWorkCV.signal();
1971 }
1972}
1973
Eric Laurent3b4529e2013-09-05 18:09:19 -07001974void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975{
1976 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001977 // reject out of sequence requests
1978 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1979 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 mWaitWorkCV.signal();
1981 }
1982}
1983
1984// static
1985int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001986 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001987 void *cookie)
1988{
1989 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1990 ALOGV("asyncCallback() event %d", event);
1991 switch (event) {
1992 case STREAM_CBK_EVENT_WRITE_READY:
1993 me->writeCallback();
1994 break;
1995 case STREAM_CBK_EVENT_DRAIN_READY:
1996 me->drainCallback();
1997 break;
1998 default:
1999 ALOGW("asyncCallback() unknown event %d", event);
2000 break;
2001 }
2002 return 0;
2003}
2004
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002005void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002006{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002007 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002008 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2009 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002010 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002011 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002012 }
Andy Hung9a592762014-07-21 21:56:01 -07002013 if ((mType == MIXER || mType == DUPLICATING)
2014 && !isValidPcmSinkChannelMask(mChannelMask)) {
2015 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2016 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002017 }
Andy Hunge5412692014-05-16 11:25:07 -07002018 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002019 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2020 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002021 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002022 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002023 }
Andy Hung6146c082014-03-18 11:56:15 -07002024 if ((mType == MIXER || mType == DUPLICATING)
2025 && !isValidPcmSinkFormat(mFormat)) {
2026 LOG_FATAL("HAL format %#x not supported for mixed output",
2027 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002028 }
Phil Burk062e67a2015-02-11 13:40:50 -08002029 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002030 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2031 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002032 if (mFrameCount & 15) {
2033 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2034 mFrameCount);
2035 }
2036
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2038 (mOutput->stream->set_callback != NULL)) {
2039 if (mOutput->stream->set_callback(mOutput->stream,
2040 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2041 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002042 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 }
2044 }
2045
Eric Laurentd1f69b02014-12-15 14:33:13 -08002046 mHwSupportsPause = false;
2047 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2048 if (mOutput->stream->pause != NULL) {
2049 if (mOutput->stream->resume != NULL) {
2050 mHwSupportsPause = true;
2051 } else {
2052 ALOGW("direct output implements pause but not resume");
2053 }
2054 } else if (mOutput->stream->resume != NULL) {
2055 ALOGW("direct output implements resume but not pause");
2056 }
2057 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002058 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2059 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2060 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002061
Andy Hungfbfc3952015-01-15 13:33:51 -08002062 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2063 // For best precision, we use float instead of the associated output
2064 // device format (typically PCM 16 bit).
2065
2066 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2067 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2068 mBufferSize = mFrameSize * mFrameCount;
2069
2070 // TODO: We currently use the associated output device channel mask and sample rate.
2071 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2072 // (if a valid mask) to avoid premature downmix.
2073 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2074 // instead of the output device sample rate to avoid loss of high frequency information.
2075 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2076 }
2077
Andy Hung09a50072014-02-27 14:30:47 -08002078 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002079 double multiplier = 1.0;
2080 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2081 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002082 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2083 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002084 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2085 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2086 maxNormalFrameCount = maxNormalFrameCount & ~15;
2087 if (maxNormalFrameCount < minNormalFrameCount) {
2088 maxNormalFrameCount = minNormalFrameCount;
2089 }
2090 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2091 if (multiplier <= 1.0) {
2092 multiplier = 1.0;
2093 } else if (multiplier <= 2.0) {
2094 if (2 * mFrameCount <= maxNormalFrameCount) {
2095 multiplier = 2.0;
2096 } else {
2097 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2098 }
2099 } else {
2100 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002101 // 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 -08002102 // track, but we sometimes have to do this to satisfy the maximum frame count
2103 // constraint)
2104 // FIXME this rounding up should not be done if no HAL SRC
2105 uint32_t truncMult = (uint32_t) multiplier;
2106 if ((truncMult & 1)) {
2107 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2108 ++truncMult;
2109 }
2110 }
2111 multiplier = (double) truncMult;
2112 }
2113 }
2114 mNormalFrameCount = multiplier * mFrameCount;
2115 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002116 if (mType == MIXER || mType == DUPLICATING) {
2117 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2118 }
Andy Hung09a50072014-02-27 14:30:47 -08002119 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002120 mNormalFrameCount);
2121
Andy Hung010a1a12014-03-13 13:57:33 -07002122 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2123 // Originally this was int16_t[] array, need to remove legacy implications.
2124 free(mSinkBuffer);
2125 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002126 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2127 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2128 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002129 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002130
Andy Hung69aed5f2014-02-25 17:24:40 -08002131 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2132 // drives the output.
2133 free(mMixerBuffer);
2134 mMixerBuffer = NULL;
2135 if (mMixerBufferEnabled) {
2136 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2137 mMixerBufferSize = mNormalFrameCount * mChannelCount
2138 * audio_bytes_per_sample(mMixerBufferFormat);
2139 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2140 }
Andy Hung98ef9782014-03-04 14:46:50 -08002141 free(mEffectBuffer);
2142 mEffectBuffer = NULL;
2143 if (mEffectBufferEnabled) {
2144 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2145 mEffectBufferSize = mNormalFrameCount * mChannelCount
2146 * audio_bytes_per_sample(mEffectBufferFormat);
2147 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2148 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002149
Eric Laurent81784c32012-11-19 14:55:58 -08002150 // force reconfiguration of effect chains and engines to take new buffer size and audio
2151 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002152 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002153 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2154 // matter.
2155 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2156 Vector< sp<EffectChain> > effectChains = mEffectChains;
2157 for (size_t i = 0; i < effectChains.size(); i ++) {
2158 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2159 }
2160}
2161
2162
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002163status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002164{
2165 if (halFrames == NULL || dspFrames == NULL) {
2166 return BAD_VALUE;
2167 }
2168 Mutex::Autolock _l(mLock);
2169 if (initCheck() != NO_ERROR) {
2170 return INVALID_OPERATION;
2171 }
2172 size_t framesWritten = mBytesWritten / mFrameSize;
2173 *halFrames = framesWritten;
2174
2175 if (isSuspended()) {
2176 // return an estimation of rendered frames when the output is suspended
2177 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2178 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2179 return NO_ERROR;
2180 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002181 status_t status;
2182 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002183 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002184 *dspFrames = (size_t)frames;
2185 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002186 }
2187}
2188
2189uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2190{
2191 Mutex::Autolock _l(mLock);
2192 uint32_t result = 0;
2193 if (getEffectChain_l(sessionId) != 0) {
2194 result = EFFECT_SESSION;
2195 }
2196
2197 for (size_t i = 0; i < mTracks.size(); ++i) {
2198 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002199 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002200 result |= TRACK_SESSION;
2201 break;
2202 }
2203 }
2204
2205 return result;
2206}
2207
2208uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2209{
2210 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2211 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2212 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2213 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2214 }
2215 for (size_t i = 0; i < mTracks.size(); i++) {
2216 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002217 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002218 return AudioSystem::getStrategyForStream(track->streamType());
2219 }
2220 }
2221 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2222}
2223
2224
Phil Burk062e67a2015-02-11 13:40:50 -08002225AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002226{
2227 Mutex::Autolock _l(mLock);
2228 return mOutput;
2229}
2230
Phil Burk062e67a2015-02-11 13:40:50 -08002231AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002232{
2233 Mutex::Autolock _l(mLock);
2234 AudioStreamOut *output = mOutput;
2235 mOutput = NULL;
2236 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2237 // must push a NULL and wait for ack
2238 mOutputSink.clear();
2239 mPipeSink.clear();
2240 mNormalSink.clear();
2241 return output;
2242}
2243
2244// this method must always be called either with ThreadBase mLock held or inside the thread loop
2245audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2246{
2247 if (mOutput == NULL) {
2248 return NULL;
2249 }
2250 return &mOutput->stream->common;
2251}
2252
2253uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2254{
2255 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2256}
2257
2258status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2259{
2260 if (!isValidSyncEvent(event)) {
2261 return BAD_VALUE;
2262 }
2263
2264 Mutex::Autolock _l(mLock);
2265
2266 for (size_t i = 0; i < mTracks.size(); ++i) {
2267 sp<Track> track = mTracks[i];
2268 if (event->triggerSession() == track->sessionId()) {
2269 (void) track->setSyncEvent(event);
2270 return NO_ERROR;
2271 }
2272 }
2273
2274 return NAME_NOT_FOUND;
2275}
2276
2277bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2278{
2279 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2280}
2281
2282void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2283 const Vector< sp<Track> >& tracksToRemove)
2284{
2285 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002286 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002287 for (size_t i = 0 ; i < count ; i++) {
2288 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002289 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002290 AudioSystem::stopOutput(mId, track->streamType(),
2291 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292#ifdef ADD_BATTERY_DATA
2293 // to track the speaker usage
2294 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2295#endif
2296 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002297 AudioSystem::releaseOutput(mId, track->streamType(),
2298 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299 }
Eric Laurent81784c32012-11-19 14:55:58 -08002300 }
2301 }
2302 }
Eric Laurent81784c32012-11-19 14:55:58 -08002303}
2304
2305void AudioFlinger::PlaybackThread::checkSilentMode_l()
2306{
2307 if (!mMasterMute) {
2308 char value[PROPERTY_VALUE_MAX];
2309 if (property_get("ro.audio.silent", value, "0") > 0) {
2310 char *endptr;
2311 unsigned long ul = strtoul(value, &endptr, 0);
2312 if (*endptr == '\0' && ul != 0) {
2313 ALOGD("Silence is golden");
2314 // The setprop command will not allow a property to be changed after
2315 // the first time it is set, so we don't have to worry about un-muting.
2316 setMasterMute_l(true);
2317 }
2318 }
2319 }
2320}
2321
2322// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002324{
2325 // FIXME rewrite to reduce number of system calls
2326 mLastWriteTime = systemTime();
2327 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002329 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002330
2331 // If an NBAIO sink is present, use it to write the normal mixer's submix
2332 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002333
Andy Hung010a1a12014-03-13 13:57:33 -07002334 const size_t count = mBytesRemaining / mFrameSize;
2335
Simon Wilson2d590962012-11-29 15:18:50 -08002336 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002337 // update the setpoint when AudioFlinger::mScreenState changes
2338 uint32_t screenState = AudioFlinger::mScreenState;
2339 if (screenState != mScreenState) {
2340 mScreenState = screenState;
2341 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2342 if (pipe != NULL) {
2343 pipe->setAvgFrames((mScreenState & 1) ?
2344 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2345 }
2346 }
Andy Hung010a1a12014-03-13 13:57:33 -07002347 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002348 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002349 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002350 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002351 } else {
2352 bytesWritten = framesWritten;
2353 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002354 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002355 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002356 if (status == NO_ERROR) {
2357 size_t totalFramesWritten = mNormalSink->framesWritten();
2358 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2359 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002360 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002361 mLatchDValid = true;
2362 }
2363 }
Eric Laurent81784c32012-11-19 14:55:58 -08002364 // otherwise use the HAL / AudioStreamOut directly
2365 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002367
Eric Laurentbfb1b832013-01-07 09:53:42 -08002368 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002369 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2370 mWriteAckSequence += 2;
2371 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002373 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002375 // FIXME We should have an implementation of timestamps for direct output threads.
2376 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002377 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 if (mUseAsyncWrite &&
2379 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2380 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002381 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002382 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002383 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002384 }
Eric Laurent81784c32012-11-19 14:55:58 -08002385 }
2386
Eric Laurent81784c32012-11-19 14:55:58 -08002387 mNumWrites++;
2388 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002389 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390 return bytesWritten;
2391}
2392
2393void AudioFlinger::PlaybackThread::threadLoop_drain()
2394{
2395 if (mOutput->stream->drain) {
2396 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2397 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002398 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2399 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002401 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002402 }
2403 mOutput->stream->drain(mOutput->stream,
2404 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2405 : AUDIO_DRAIN_ALL);
2406 }
2407}
2408
2409void AudioFlinger::PlaybackThread::threadLoop_exit()
2410{
Eric Laurent275e8e92014-11-30 15:14:47 -08002411 {
2412 Mutex::Autolock _l(mLock);
2413 for (size_t i = 0; i < mTracks.size(); i++) {
2414 sp<Track> track = mTracks[i];
2415 track->invalidate();
2416 }
2417 }
Eric Laurent81784c32012-11-19 14:55:58 -08002418}
2419
2420/*
2421The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002422 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002423 - activeSleepTime from activeSleepTimeUs()
2424 - idleSleepTime from idleSleepTimeUs()
2425 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2426 - maxPeriod from frame count and sample rate (MIXER only)
2427
2428The parameters that affect these derived values are:
2429 - frame count
2430 - frame size
2431 - sample rate
2432 - device type: A2DP or not
2433 - device latency
2434 - format: PCM or not
2435 - active sleep time
2436 - idle sleep time
2437*/
2438
2439void AudioFlinger::PlaybackThread::cacheParameters_l()
2440{
Andy Hung25c2dac2014-02-27 14:56:00 -08002441 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002442 activeSleepTime = activeSleepTimeUs();
2443 idleSleepTime = idleSleepTimeUs();
2444}
2445
2446void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2447{
Glenn Kasten7c027242012-12-26 14:43:16 -08002448 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002449 this, streamType, mTracks.size());
2450 Mutex::Autolock _l(mLock);
2451
2452 size_t size = mTracks.size();
2453 for (size_t i = 0; i < size; i++) {
2454 sp<Track> t = mTracks[i];
2455 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002456 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002457 }
2458 }
2459}
2460
2461status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2462{
2463 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002464 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2465 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002466 bool ownsBuffer = false;
2467
2468 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2469 if (session > 0) {
2470 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002471 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002472 if (mType != DIRECT) {
2473 size_t numSamples = mNormalFrameCount * mChannelCount;
2474 buffer = new int16_t[numSamples];
2475 memset(buffer, 0, numSamples * sizeof(int16_t));
2476 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2477 ownsBuffer = true;
2478 }
2479
2480 // Attach all tracks with same session ID to this chain.
2481 for (size_t i = 0; i < mTracks.size(); ++i) {
2482 sp<Track> track = mTracks[i];
2483 if (session == track->sessionId()) {
2484 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2485 buffer);
2486 track->setMainBuffer(buffer);
2487 chain->incTrackCnt();
2488 }
2489 }
2490
2491 // indicate all active tracks in the chain
2492 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2493 sp<Track> track = mActiveTracks[i].promote();
2494 if (track == 0) {
2495 continue;
2496 }
2497 if (session == track->sessionId()) {
2498 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2499 chain->incActiveTrackCnt();
2500 }
2501 }
2502 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002503 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002504 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002505 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2506 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002507 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2508 // chains list in order to be processed last as it contains output stage effects
2509 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2510 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2511 // after track specific effects and before output stage
2512 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2513 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2514 // Effect chain for other sessions are inserted at beginning of effect
2515 // chains list to be processed before output mix effects. Relative order between other
2516 // sessions is not important
2517 size_t size = mEffectChains.size();
2518 size_t i = 0;
2519 for (i = 0; i < size; i++) {
2520 if (mEffectChains[i]->sessionId() < session) {
2521 break;
2522 }
2523 }
2524 mEffectChains.insertAt(chain, i);
2525 checkSuspendOnAddEffectChain_l(chain);
2526
2527 return NO_ERROR;
2528}
2529
2530size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2531{
2532 int session = chain->sessionId();
2533
2534 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2535
2536 for (size_t i = 0; i < mEffectChains.size(); i++) {
2537 if (chain == mEffectChains[i]) {
2538 mEffectChains.removeAt(i);
2539 // detach all active tracks from the chain
2540 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2541 sp<Track> track = mActiveTracks[i].promote();
2542 if (track == 0) {
2543 continue;
2544 }
2545 if (session == track->sessionId()) {
2546 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2547 chain.get(), session);
2548 chain->decActiveTrackCnt();
2549 }
2550 }
2551
2552 // detach all tracks with same session ID from this chain
2553 for (size_t i = 0; i < mTracks.size(); ++i) {
2554 sp<Track> track = mTracks[i];
2555 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002556 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002557 chain->decTrackCnt();
2558 }
2559 }
2560 break;
2561 }
2562 }
2563 return mEffectChains.size();
2564}
2565
2566status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2567 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2568{
2569 Mutex::Autolock _l(mLock);
2570 return attachAuxEffect_l(track, EffectId);
2571}
2572
2573status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2574 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2575{
2576 status_t status = NO_ERROR;
2577
2578 if (EffectId == 0) {
2579 track->setAuxBuffer(0, NULL);
2580 } else {
2581 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2582 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2583 if (effect != 0) {
2584 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2585 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2586 } else {
2587 status = INVALID_OPERATION;
2588 }
2589 } else {
2590 status = BAD_VALUE;
2591 }
2592 }
2593 return status;
2594}
2595
2596void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2597{
2598 for (size_t i = 0; i < mTracks.size(); ++i) {
2599 sp<Track> track = mTracks[i];
2600 if (track->auxEffectId() == effectId) {
2601 attachAuxEffect_l(track, 0);
2602 }
2603 }
2604}
2605
2606bool AudioFlinger::PlaybackThread::threadLoop()
2607{
2608 Vector< sp<Track> > tracksToRemove;
2609
2610 standbyTime = systemTime();
2611
2612 // MIXER
2613 nsecs_t lastWarning = 0;
2614
2615 // DUPLICATING
2616 // FIXME could this be made local to while loop?
2617 writeFrames = 0;
2618
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002619 int lastGeneration = 0;
2620
Eric Laurent81784c32012-11-19 14:55:58 -08002621 cacheParameters_l();
2622 sleepTime = idleSleepTime;
2623
2624 if (mType == MIXER) {
2625 sleepTimeShift = 0;
2626 }
2627
2628 CpuStats cpuStats;
2629 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2630
2631 acquireWakeLock();
2632
Glenn Kasten9e58b552013-01-18 15:09:48 -08002633 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2634 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2635 // and then that string will be logged at the next convenient opportunity.
2636 const char *logString = NULL;
2637
Eric Laurent664539d2013-09-23 18:24:31 -07002638 checkSilentMode_l();
2639
Eric Laurent81784c32012-11-19 14:55:58 -08002640 while (!exitPending())
2641 {
2642 cpuStats.sample(myName);
2643
2644 Vector< sp<EffectChain> > effectChains;
2645
Eric Laurent81784c32012-11-19 14:55:58 -08002646 { // scope for mLock
2647
2648 Mutex::Autolock _l(mLock);
2649
Eric Laurent021cf962014-05-13 10:18:14 -07002650 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002651
Glenn Kasten9e58b552013-01-18 15:09:48 -08002652 if (logString != NULL) {
2653 mNBLogWriter->logTimestamp();
2654 mNBLogWriter->log(logString);
2655 logString = NULL;
2656 }
2657
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002658 // Gather the framesReleased counters for all active tracks,
2659 // and latch them atomically with the timestamp.
2660 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2661 mLatchD.mFramesReleased.clear();
2662 size_t size = mActiveTracks.size();
2663 for (size_t i = 0; i < size; i++) {
2664 sp<Track> t = mActiveTracks[i].promote();
2665 if (t != 0) {
2666 mLatchD.mFramesReleased.add(t.get(),
2667 t->mAudioTrackServerProxy->framesReleased());
2668 }
2669 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002670 if (mLatchDValid) {
2671 mLatchQ = mLatchD;
2672 mLatchDValid = false;
2673 mLatchQValid = true;
2674 }
2675
Eric Laurent81784c32012-11-19 14:55:58 -08002676 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 if (mSignalPending) {
2678 // A signal was raised while we were unlocked
2679 mSignalPending = false;
2680 } else if (waitingAsyncCallback_l()) {
2681 if (exitPending()) {
2682 break;
2683 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002684 bool released = false;
2685 // The following works around a bug in the offload driver. Ideally we would release
2686 // the wake lock every time, but that causes the last offload buffer(s) to be
2687 // dropped while the device is on battery, so we need to hold a wake lock during
2688 // the drain phase.
2689 if (mBytesRemaining && !(mDrainSequence & 1)) {
2690 releaseWakeLock_l();
2691 released = true;
2692 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002693 mWakeLockUids.clear();
2694 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002695 ALOGV("wait async completion");
2696 mWaitWorkCV.wait(mLock);
2697 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002698 if (released) {
2699 acquireWakeLock_l();
2700 }
Eric Laurent972a1732013-09-04 09:42:59 -07002701 standbyTime = systemTime() + standbyDelay;
2702 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002703
2704 continue;
2705 }
2706 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707 isSuspended()) {
2708 // put audio hardware into standby after short delay
2709 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002710
2711 threadLoop_standby();
2712
2713 mStandby = true;
2714 }
2715
2716 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2717 // we're about to wait, flush the binder command buffer
2718 IPCThreadState::self()->flushCommands();
2719
2720 clearOutputTracks();
2721
2722 if (exitPending()) {
2723 break;
2724 }
2725
2726 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002727 mWakeLockUids.clear();
2728 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002729 // wait until we have something to do...
2730 ALOGV("%s going to sleep", myName.string());
2731 mWaitWorkCV.wait(mLock);
2732 ALOGV("%s waking up", myName.string());
2733 acquireWakeLock_l();
2734
2735 mMixerStatus = MIXER_IDLE;
2736 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2737 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002739 checkSilentMode_l();
2740
2741 standbyTime = systemTime() + standbyDelay;
2742 sleepTime = idleSleepTime;
2743 if (mType == MIXER) {
2744 sleepTimeShift = 0;
2745 }
2746
2747 continue;
2748 }
2749 }
Eric Laurent81784c32012-11-19 14:55:58 -08002750 // mMixerStatusIgnoringFastTracks is also updated internally
2751 mMixerStatus = prepareTracks_l(&tracksToRemove);
2752
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002753 // compare with previously applied list
2754 if (lastGeneration != mActiveTracksGeneration) {
2755 // update wakelock
2756 updateWakeLockUids_l(mWakeLockUids);
2757 lastGeneration = mActiveTracksGeneration;
2758 }
2759
Eric Laurent81784c32012-11-19 14:55:58 -08002760 // prevent any changes in effect chain list and in each effect chain
2761 // during mixing and effect process as the audio buffers could be deleted
2762 // or modified if an effect is created or deleted
2763 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002764 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002765
Eric Laurentbfb1b832013-01-07 09:53:42 -08002766 if (mBytesRemaining == 0) {
2767 mCurrentWriteLength = 0;
2768 if (mMixerStatus == MIXER_TRACKS_READY) {
2769 // threadLoop_mix() sets mCurrentWriteLength
2770 threadLoop_mix();
2771 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2772 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2773 // threadLoop_sleepTime sets sleepTime to 0 if data
2774 // must be written to HAL
2775 threadLoop_sleepTime();
2776 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002777 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778 }
2779 }
Andy Hung98ef9782014-03-04 14:46:50 -08002780 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2781 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2782 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2783 // or mSinkBuffer (if there are no effects).
2784 //
2785 // This is done pre-effects computation; if effects change to
2786 // support higher precision, this needs to move.
2787 //
2788 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2789 // TODO use sleepTime == 0 as an additional condition.
2790 if (mMixerBufferValid) {
2791 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2792 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2793
2794 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2795 mNormalFrameCount * mChannelCount);
2796 }
2797
Eric Laurentbfb1b832013-01-07 09:53:42 -08002798 mBytesRemaining = mCurrentWriteLength;
2799 if (isSuspended()) {
2800 sleepTime = suspendSleepTimeUs();
2801 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002802 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002803 mBytesRemaining = 0;
2804 }
Eric Laurent81784c32012-11-19 14:55:58 -08002805
Eric Laurentbfb1b832013-01-07 09:53:42 -08002806 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002807 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002808 for (size_t i = 0; i < effectChains.size(); i ++) {
2809 effectChains[i]->process_l();
2810 }
Eric Laurent81784c32012-11-19 14:55:58 -08002811 }
2812 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002813 // Process effect chains for offloaded thread even if no audio
2814 // was read from audio track: process only updates effect state
2815 // and thus does have to be synchronized with audio writes but may have
2816 // to be called while waiting for async write callback
2817 if (mType == OFFLOAD) {
2818 for (size_t i = 0; i < effectChains.size(); i ++) {
2819 effectChains[i]->process_l();
2820 }
2821 }
Eric Laurent81784c32012-11-19 14:55:58 -08002822
Andy Hung98ef9782014-03-04 14:46:50 -08002823 // Only if the Effects buffer is enabled and there is data in the
2824 // Effects buffer (buffer valid), we need to
2825 // copy into the sink buffer.
2826 // TODO use sleepTime == 0 as an additional condition.
2827 if (mEffectBufferValid) {
2828 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2829 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2830 mNormalFrameCount * mChannelCount);
2831 }
2832
Eric Laurent81784c32012-11-19 14:55:58 -08002833 // enable changes in effect chain
2834 unlockEffectChains(effectChains);
2835
Eric Laurentbfb1b832013-01-07 09:53:42 -08002836 if (!waitingAsyncCallback()) {
2837 // sleepTime == 0 means we must write to audio hardware
2838 if (sleepTime == 0) {
2839 if (mBytesRemaining) {
2840 ssize_t ret = threadLoop_write();
2841 if (ret < 0) {
2842 mBytesRemaining = 0;
2843 } else {
2844 mBytesWritten += ret;
2845 mBytesRemaining -= ret;
2846 }
2847 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2848 (mMixerStatus == MIXER_DRAIN_ALL)) {
2849 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002850 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002851 if (mType == MIXER) {
2852 // write blocked detection
2853 nsecs_t now = systemTime();
2854 nsecs_t delta = now - mLastWriteTime;
2855 if (!mStandby && delta > maxPeriod) {
2856 mNumDelayedWrites++;
2857 if ((now - lastWarning) > kWarningThrottleNs) {
2858 ATRACE_NAME("underrun");
2859 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2860 ns2ms(delta), mNumDelayedWrites, this);
2861 lastWarning = now;
2862 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 }
2864 }
Eric Laurent81784c32012-11-19 14:55:58 -08002865
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002867 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002869 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 }
Eric Laurent81784c32012-11-19 14:55:58 -08002871 }
2872
2873 // Finally let go of removed track(s), without the lock held
2874 // since we can't guarantee the destructors won't acquire that
2875 // same lock. This will also mutate and push a new fast mixer state.
2876 threadLoop_removeTracks(tracksToRemove);
2877 tracksToRemove.clear();
2878
2879 // FIXME I don't understand the need for this here;
2880 // it was in the original code but maybe the
2881 // assignment in saveOutputTracks() makes this unnecessary?
2882 clearOutputTracks();
2883
2884 // Effect chains will be actually deleted here if they were removed from
2885 // mEffectChains list during mixing or effects processing
2886 effectChains.clear();
2887
2888 // FIXME Note that the above .clear() is no longer necessary since effectChains
2889 // is now local to this block, but will keep it for now (at least until merge done).
2890 }
2891
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 threadLoop_exit();
2893
Eric Laurentcf817a22014-08-04 20:36:31 -07002894 if (!mStandby) {
2895 threadLoop_standby();
2896 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002897 }
2898
2899 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002900 mWakeLockUids.clear();
2901 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002902
2903 ALOGV("Thread %p type %d exiting", this, mType);
2904 return false;
2905}
2906
Eric Laurentbfb1b832013-01-07 09:53:42 -08002907// removeTracks_l() must be called with ThreadBase::mLock held
2908void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2909{
2910 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002911 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002912 for (size_t i=0 ; i<count ; i++) {
2913 const sp<Track>& track = tracksToRemove.itemAt(i);
2914 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002915 mWakeLockUids.remove(track->uid());
2916 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2918 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2919 if (chain != 0) {
2920 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2921 track->sessionId());
2922 chain->decActiveTrackCnt();
2923 }
2924 if (track->isTerminated()) {
2925 removeTrack_l(track);
2926 }
2927 }
2928 }
2929
2930}
Eric Laurent81784c32012-11-19 14:55:58 -08002931
Eric Laurentaccc1472013-09-20 09:36:34 -07002932status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2933{
2934 if (mNormalSink != 0) {
2935 return mNormalSink->getTimestamp(timestamp);
2936 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002937 if ((mType == OFFLOAD || mType == DIRECT)
2938 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002939 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002940 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002941 if (ret == 0) {
2942 timestamp.mPosition = (uint32_t)position64;
2943 return NO_ERROR;
2944 }
2945 }
2946 return INVALID_OPERATION;
2947}
Eric Laurent1c333e22014-05-20 10:48:17 -07002948
Eric Laurent054d9d32015-04-24 08:48:48 -07002949status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
2950 audio_patch_handle_t *handle)
2951{
2952 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2953 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2954 if (mFastMixer != 0) {
2955 FastMixerStateQueue *sq = mFastMixer->sq();
2956 FastMixerState *state = sq->begin();
2957 if (!(state->mCommand & FastMixerState::IDLE)) {
2958 previousCommand = state->mCommand;
2959 state->mCommand = FastMixerState::HOT_IDLE;
2960 sq->end();
2961 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2962 } else {
2963 sq->end(false /*didModify*/);
2964 }
2965 }
2966 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
2967
2968 if (!(previousCommand & FastMixerState::IDLE)) {
2969 ALOG_ASSERT(mFastMixer != 0);
2970 FastMixerStateQueue *sq = mFastMixer->sq();
2971 FastMixerState *state = sq->begin();
2972 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
2973 state->mCommand = previousCommand;
2974 sq->end();
2975 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2976 }
2977
2978 return status;
2979}
2980
Eric Laurent1c333e22014-05-20 10:48:17 -07002981status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2982 audio_patch_handle_t *handle)
2983{
2984 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07002985
2986 // store new device and send to effects
2987 audio_devices_t type = AUDIO_DEVICE_NONE;
2988 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2989 type |= patch->sinks[i].ext.device.type;
2990 }
2991
2992#ifdef ADD_BATTERY_DATA
2993 // when changing the audio output device, call addBatteryData to notify
2994 // the change
2995 if (mOutDevice != type) {
2996 uint32_t params = 0;
2997 // check whether speaker is on
2998 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
2999 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003000 }
3001
Eric Laurent054d9d32015-04-24 08:48:48 -07003002 audio_devices_t deviceWithoutSpeaker
3003 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3004 // check if any other device (except speaker) is on
3005 if (type & deviceWithoutSpeaker) {
3006 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3007 }
3008
3009 if (params != 0) {
3010 addBatteryData(params);
3011 }
3012 }
3013#endif
3014
3015 for (size_t i = 0; i < mEffectChains.size(); i++) {
3016 mEffectChains[i]->setDevice_l(type);
3017 }
3018 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003019 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003020
3021 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003022 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3023 status = hwDevice->create_audio_patch(hwDevice,
3024 patch->num_sources,
3025 patch->sources,
3026 patch->num_sinks,
3027 patch->sinks,
3028 handle);
3029 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003030 char *address;
3031 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3032 //FIXME: we only support address on first sink with HAL version < 3.0
3033 address = audio_device_address_to_parameter(
3034 patch->sinks[0].ext.device.type,
3035 patch->sinks[0].ext.device.address);
3036 } else {
3037 address = (char *)calloc(1, 1);
3038 }
3039 AudioParameter param = AudioParameter(String8(address));
3040 free(address);
3041 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3042 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3043 param.toString().string());
3044 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003045 }
Eric Laurent296fb132015-05-01 11:38:42 -07003046 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003047 return status;
3048}
3049
Eric Laurent054d9d32015-04-24 08:48:48 -07003050status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3051{
3052 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3053 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3054 if (mFastMixer != 0) {
3055 FastMixerStateQueue *sq = mFastMixer->sq();
3056 FastMixerState *state = sq->begin();
3057 if (!(state->mCommand & FastMixerState::IDLE)) {
3058 previousCommand = state->mCommand;
3059 state->mCommand = FastMixerState::HOT_IDLE;
3060 sq->end();
3061 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3062 } else {
3063 sq->end(false /*didModify*/);
3064 }
3065 }
3066
3067 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3068
3069 if (!(previousCommand & FastMixerState::IDLE)) {
3070 ALOG_ASSERT(mFastMixer != 0);
3071 FastMixerStateQueue *sq = mFastMixer->sq();
3072 FastMixerState *state = sq->begin();
3073 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3074 state->mCommand = previousCommand;
3075 sq->end();
3076 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3077 }
3078
3079 return status;
3080}
3081
Eric Laurent1c333e22014-05-20 10:48:17 -07003082status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3083{
3084 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003085
3086 mOutDevice = AUDIO_DEVICE_NONE;
3087
Eric Laurent1c333e22014-05-20 10:48:17 -07003088 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3089 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3090 status = hwDevice->release_audio_patch(hwDevice, handle);
3091 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003092 AudioParameter param;
3093 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3094 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3095 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003096 }
3097 return status;
3098}
3099
Eric Laurent83b88082014-06-20 18:31:16 -07003100void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3101{
3102 Mutex::Autolock _l(mLock);
3103 mTracks.add(track);
3104}
3105
3106void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3107{
3108 Mutex::Autolock _l(mLock);
3109 destroyTrack_l(track);
3110}
3111
3112void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3113{
3114 ThreadBase::getAudioPortConfig(config);
3115 config->role = AUDIO_PORT_ROLE_SOURCE;
3116 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3117 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3118}
3119
Eric Laurent81784c32012-11-19 14:55:58 -08003120// ----------------------------------------------------------------------------
3121
3122AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
3123 audio_io_handle_t id, audio_devices_t device, type_t type)
3124 : PlaybackThread(audioFlinger, output, id, device, type),
3125 // mAudioMixer below
3126 // mFastMixer below
3127 mFastMixerFutex(0)
3128 // mOutputSink below
3129 // mPipeSink below
3130 // mNormalSink below
3131{
3132 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003133 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003134 "mFrameCount=%d, mNormalFrameCount=%d",
3135 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3136 mNormalFrameCount);
3137 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3138
Andy Hungfbfc3952015-01-15 13:33:51 -08003139 if (type == DUPLICATING) {
3140 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3141 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3142 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3143 return;
3144 }
Eric Laurent81784c32012-11-19 14:55:58 -08003145 // create an NBAIO sink for the HAL output stream, and negotiate
3146 mOutputSink = new AudioStreamOutSink(output->stream);
3147 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003148 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003149 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3150 ALOG_ASSERT(index == 0);
3151
3152 // initialize fast mixer depending on configuration
3153 bool initFastMixer;
3154 switch (kUseFastMixer) {
3155 case FastMixer_Never:
3156 initFastMixer = false;
3157 break;
3158 case FastMixer_Always:
3159 initFastMixer = true;
3160 break;
3161 case FastMixer_Static:
3162 case FastMixer_Dynamic:
3163 initFastMixer = mFrameCount < mNormalFrameCount;
3164 break;
3165 }
3166 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003167 audio_format_t fastMixerFormat;
3168 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3169 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3170 } else {
3171 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3172 }
3173 if (mFormat != fastMixerFormat) {
3174 // change our Sink format to accept our intermediate precision
3175 mFormat = fastMixerFormat;
3176 free(mSinkBuffer);
3177 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3178 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3179 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3180 }
Eric Laurent81784c32012-11-19 14:55:58 -08003181
3182 // create a MonoPipe to connect our submix to FastMixer
3183 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003184 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003185 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003186 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003187 format.mFormat = fastMixerFormat;
3188 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3189
Eric Laurent81784c32012-11-19 14:55:58 -08003190 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3191 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3192 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3193 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3194 const NBAIO_Format offers[1] = {format};
3195 size_t numCounterOffers = 0;
3196 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3197 ALOG_ASSERT(index == 0);
3198 monoPipe->setAvgFrames((mScreenState & 1) ?
3199 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3200 mPipeSink = monoPipe;
3201
Glenn Kasten46909e72013-02-26 09:20:22 -08003202#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003203 if (mTeeSinkOutputEnabled) {
3204 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003205 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3206 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003207 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003208 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003209 ALOG_ASSERT(index == 0);
3210 mTeeSink = teeSink;
3211 PipeReader *teeSource = new PipeReader(*teeSink);
3212 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003213 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003214 ALOG_ASSERT(index == 0);
3215 mTeeSource = teeSource;
3216 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003217#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003218
3219 // create fast mixer and configure it initially with just one fast track for our submix
3220 mFastMixer = new FastMixer();
3221 FastMixerStateQueue *sq = mFastMixer->sq();
3222#ifdef STATE_QUEUE_DUMP
3223 sq->setObserverDump(&mStateQueueObserverDump);
3224 sq->setMutatorDump(&mStateQueueMutatorDump);
3225#endif
3226 FastMixerState *state = sq->begin();
3227 FastTrack *fastTrack = &state->mFastTracks[0];
3228 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3229 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3230 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003231 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3232 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003233 fastTrack->mGeneration++;
3234 state->mFastTracksGen++;
3235 state->mTrackMask = 1;
3236 // fast mixer will use the HAL output sink
3237 state->mOutputSink = mOutputSink.get();
3238 state->mOutputSinkGen++;
3239 state->mFrameCount = mFrameCount;
3240 state->mCommand = FastMixerState::COLD_IDLE;
3241 // already done in constructor initialization list
3242 //mFastMixerFutex = 0;
3243 state->mColdFutexAddr = &mFastMixerFutex;
3244 state->mColdGen++;
3245 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003246#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003247 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003248#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003249 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3250 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003251 sq->end();
3252 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3253
3254 // start the fast mixer
3255 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3256 pid_t tid = mFastMixer->getTid();
3257 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3258 if (err != 0) {
3259 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3260 kPriorityFastMixer, getpid_cached, tid, err);
3261 }
3262
3263#ifdef AUDIO_WATCHDOG
3264 // create and start the watchdog
3265 mAudioWatchdog = new AudioWatchdog();
3266 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3267 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3268 tid = mAudioWatchdog->getTid();
3269 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3270 if (err != 0) {
3271 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3272 kPriorityFastMixer, getpid_cached, tid, err);
3273 }
3274#endif
3275
Eric Laurent81784c32012-11-19 14:55:58 -08003276 }
3277
3278 switch (kUseFastMixer) {
3279 case FastMixer_Never:
3280 case FastMixer_Dynamic:
3281 mNormalSink = mOutputSink;
3282 break;
3283 case FastMixer_Always:
3284 mNormalSink = mPipeSink;
3285 break;
3286 case FastMixer_Static:
3287 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3288 break;
3289 }
3290}
3291
3292AudioFlinger::MixerThread::~MixerThread()
3293{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003294 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003295 FastMixerStateQueue *sq = mFastMixer->sq();
3296 FastMixerState *state = sq->begin();
3297 if (state->mCommand == FastMixerState::COLD_IDLE) {
3298 int32_t old = android_atomic_inc(&mFastMixerFutex);
3299 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003300 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003301 }
3302 }
3303 state->mCommand = FastMixerState::EXIT;
3304 sq->end();
3305 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3306 mFastMixer->join();
3307 // Though the fast mixer thread has exited, it's state queue is still valid.
3308 // We'll use that extract the final state which contains one remaining fast track
3309 // corresponding to our sub-mix.
3310 state = sq->begin();
3311 ALOG_ASSERT(state->mTrackMask == 1);
3312 FastTrack *fastTrack = &state->mFastTracks[0];
3313 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3314 delete fastTrack->mBufferProvider;
3315 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003316 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003317#ifdef AUDIO_WATCHDOG
3318 if (mAudioWatchdog != 0) {
3319 mAudioWatchdog->requestExit();
3320 mAudioWatchdog->requestExitAndWait();
3321 mAudioWatchdog.clear();
3322 }
3323#endif
3324 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003325 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003326 delete mAudioMixer;
3327}
3328
3329
3330uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3331{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003332 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003333 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3334 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3335 }
3336 return latency;
3337}
3338
3339
3340void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3341{
3342 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3343}
3344
Eric Laurentbfb1b832013-01-07 09:53:42 -08003345ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003346{
3347 // FIXME we should only do one push per cycle; confirm this is true
3348 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003349 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003350 FastMixerStateQueue *sq = mFastMixer->sq();
3351 FastMixerState *state = sq->begin();
3352 if (state->mCommand != FastMixerState::MIX_WRITE &&
3353 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3354 if (state->mCommand == FastMixerState::COLD_IDLE) {
3355 int32_t old = android_atomic_inc(&mFastMixerFutex);
3356 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003357 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003358 }
3359#ifdef AUDIO_WATCHDOG
3360 if (mAudioWatchdog != 0) {
3361 mAudioWatchdog->resume();
3362 }
3363#endif
3364 }
3365 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003366#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003367 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003368 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003369#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003370 sq->end();
3371 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3372 if (kUseFastMixer == FastMixer_Dynamic) {
3373 mNormalSink = mPipeSink;
3374 }
3375 } else {
3376 sq->end(false /*didModify*/);
3377 }
3378 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003379 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003380}
3381
3382void AudioFlinger::MixerThread::threadLoop_standby()
3383{
3384 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003385 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003386 FastMixerStateQueue *sq = mFastMixer->sq();
3387 FastMixerState *state = sq->begin();
3388 if (!(state->mCommand & FastMixerState::IDLE)) {
3389 state->mCommand = FastMixerState::COLD_IDLE;
3390 state->mColdFutexAddr = &mFastMixerFutex;
3391 state->mColdGen++;
3392 mFastMixerFutex = 0;
3393 sq->end();
3394 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3395 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3396 if (kUseFastMixer == FastMixer_Dynamic) {
3397 mNormalSink = mOutputSink;
3398 }
3399#ifdef AUDIO_WATCHDOG
3400 if (mAudioWatchdog != 0) {
3401 mAudioWatchdog->pause();
3402 }
3403#endif
3404 } else {
3405 sq->end(false /*didModify*/);
3406 }
3407 }
3408 PlaybackThread::threadLoop_standby();
3409}
3410
Eric Laurentbfb1b832013-01-07 09:53:42 -08003411bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3412{
3413 return false;
3414}
3415
3416bool AudioFlinger::PlaybackThread::shouldStandby_l()
3417{
3418 return !mStandby;
3419}
3420
3421bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3422{
3423 Mutex::Autolock _l(mLock);
3424 return waitingAsyncCallback_l();
3425}
3426
Eric Laurent81784c32012-11-19 14:55:58 -08003427// shared by MIXER and DIRECT, overridden by DUPLICATING
3428void AudioFlinger::PlaybackThread::threadLoop_standby()
3429{
3430 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003431 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003432 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003433 // discard any pending drain or write ack by incrementing sequence
3434 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3435 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003436 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003437 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3438 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003439 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003440 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003441}
3442
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003443void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3444{
3445 ALOGV("signal playback thread");
3446 broadcast_l();
3447}
3448
Eric Laurent81784c32012-11-19 14:55:58 -08003449void AudioFlinger::MixerThread::threadLoop_mix()
3450{
3451 // obtain the presentation timestamp of the next output buffer
3452 int64_t pts;
3453 status_t status = INVALID_OPERATION;
3454
3455 if (mNormalSink != 0) {
3456 status = mNormalSink->getNextWriteTimestamp(&pts);
3457 } else {
3458 status = mOutputSink->getNextWriteTimestamp(&pts);
3459 }
3460
3461 if (status != NO_ERROR) {
3462 pts = AudioBufferProvider::kInvalidPTS;
3463 }
3464
3465 // mix buffers...
3466 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003467 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003468 // increase sleep time progressively when application underrun condition clears.
3469 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3470 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3471 // such that we would underrun the audio HAL.
3472 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3473 sleepTimeShift--;
3474 }
3475 sleepTime = 0;
3476 standbyTime = systemTime() + standbyDelay;
3477 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003478
Eric Laurent81784c32012-11-19 14:55:58 -08003479}
3480
3481void AudioFlinger::MixerThread::threadLoop_sleepTime()
3482{
3483 // If no tracks are ready, sleep once for the duration of an output
3484 // buffer size, then write 0s to the output
3485 if (sleepTime == 0) {
3486 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3487 sleepTime = activeSleepTime >> sleepTimeShift;
3488 if (sleepTime < kMinThreadSleepTimeUs) {
3489 sleepTime = kMinThreadSleepTimeUs;
3490 }
3491 // reduce sleep time in case of consecutive application underruns to avoid
3492 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3493 // duration we would end up writing less data than needed by the audio HAL if
3494 // the condition persists.
3495 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3496 sleepTimeShift++;
3497 }
3498 } else {
3499 sleepTime = idleSleepTime;
3500 }
3501 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003502 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3503 // before effects processing or output.
3504 if (mMixerBufferValid) {
3505 memset(mMixerBuffer, 0, mMixerBufferSize);
3506 } else {
3507 memset(mSinkBuffer, 0, mSinkBufferSize);
3508 }
Eric Laurent81784c32012-11-19 14:55:58 -08003509 sleepTime = 0;
3510 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3511 "anticipated start");
3512 }
3513 // TODO add standby time extension fct of effect tail
3514}
3515
3516// prepareTracks_l() must be called with ThreadBase::mLock held
3517AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3518 Vector< sp<Track> > *tracksToRemove)
3519{
3520
3521 mixer_state mixerStatus = MIXER_IDLE;
3522 // find out which tracks need to be processed
3523 size_t count = mActiveTracks.size();
3524 size_t mixedTracks = 0;
3525 size_t tracksWithEffect = 0;
3526 // counts only _active_ fast tracks
3527 size_t fastTracks = 0;
3528 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3529
3530 float masterVolume = mMasterVolume;
3531 bool masterMute = mMasterMute;
3532
3533 if (masterMute) {
3534 masterVolume = 0;
3535 }
3536 // Delegate master volume control to effect in output mix effect chain if needed
3537 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3538 if (chain != 0) {
3539 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3540 chain->setVolume_l(&v, &v);
3541 masterVolume = (float)((v + (1 << 23)) >> 24);
3542 chain.clear();
3543 }
3544
3545 // prepare a new state to push
3546 FastMixerStateQueue *sq = NULL;
3547 FastMixerState *state = NULL;
3548 bool didModify = false;
3549 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003550 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003551 sq = mFastMixer->sq();
3552 state = sq->begin();
3553 }
3554
Andy Hung69aed5f2014-02-25 17:24:40 -08003555 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003556 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003557
Eric Laurent81784c32012-11-19 14:55:58 -08003558 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003559 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003560 if (t == 0) {
3561 continue;
3562 }
3563
3564 // this const just means the local variable doesn't change
3565 Track* const track = t.get();
3566
3567 // process fast tracks
3568 if (track->isFastTrack()) {
3569
3570 // It's theoretically possible (though unlikely) for a fast track to be created
3571 // and then removed within the same normal mix cycle. This is not a problem, as
3572 // the track never becomes active so it's fast mixer slot is never touched.
3573 // The converse, of removing an (active) track and then creating a new track
3574 // at the identical fast mixer slot within the same normal mix cycle,
3575 // is impossible because the slot isn't marked available until the end of each cycle.
3576 int j = track->mFastIndex;
3577 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3578 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3579 FastTrack *fastTrack = &state->mFastTracks[j];
3580
3581 // Determine whether the track is currently in underrun condition,
3582 // and whether it had a recent underrun.
3583 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3584 FastTrackUnderruns underruns = ftDump->mUnderruns;
3585 uint32_t recentFull = (underruns.mBitFields.mFull -
3586 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3587 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3588 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3589 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3590 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3591 uint32_t recentUnderruns = recentPartial + recentEmpty;
3592 track->mObservedUnderruns = underruns;
3593 // don't count underruns that occur while stopping or pausing
3594 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003595 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3596 recentUnderruns > 0) {
3597 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3598 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003599 }
3600
3601 // This is similar to the state machine for normal tracks,
3602 // with a few modifications for fast tracks.
3603 bool isActive = true;
3604 switch (track->mState) {
3605 case TrackBase::STOPPING_1:
3606 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003607 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003608 track->mState = TrackBase::STOPPING_2;
3609 }
3610 break;
3611 case TrackBase::PAUSING:
3612 // ramp down is not yet implemented
3613 track->setPaused();
3614 break;
3615 case TrackBase::RESUMING:
3616 // ramp up is not yet implemented
3617 track->mState = TrackBase::ACTIVE;
3618 break;
3619 case TrackBase::ACTIVE:
3620 if (recentFull > 0 || recentPartial > 0) {
3621 // track has provided at least some frames recently: reset retry count
3622 track->mRetryCount = kMaxTrackRetries;
3623 }
3624 if (recentUnderruns == 0) {
3625 // no recent underruns: stay active
3626 break;
3627 }
3628 // there has recently been an underrun of some kind
3629 if (track->sharedBuffer() == 0) {
3630 // were any of the recent underruns "empty" (no frames available)?
3631 if (recentEmpty == 0) {
3632 // no, then ignore the partial underruns as they are allowed indefinitely
3633 break;
3634 }
3635 // there has recently been an "empty" underrun: decrement the retry counter
3636 if (--(track->mRetryCount) > 0) {
3637 break;
3638 }
3639 // indicate to client process that the track was disabled because of underrun;
3640 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003641 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003642 // remove from active list, but state remains ACTIVE [confusing but true]
3643 isActive = false;
3644 break;
3645 }
3646 // fall through
3647 case TrackBase::STOPPING_2:
3648 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003649 case TrackBase::STOPPED:
3650 case TrackBase::FLUSHED: // flush() while active
3651 // Check for presentation complete if track is inactive
3652 // We have consumed all the buffers of this track.
3653 // This would be incomplete if we auto-paused on underrun
3654 {
3655 size_t audioHALFrames =
3656 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3657 size_t framesWritten = mBytesWritten / mFrameSize;
3658 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3659 // track stays in active list until presentation is complete
3660 break;
3661 }
3662 }
3663 if (track->isStopping_2()) {
3664 track->mState = TrackBase::STOPPED;
3665 }
3666 if (track->isStopped()) {
3667 // Can't reset directly, as fast mixer is still polling this track
3668 // track->reset();
3669 // So instead mark this track as needing to be reset after push with ack
3670 resetMask |= 1 << i;
3671 }
3672 isActive = false;
3673 break;
3674 case TrackBase::IDLE:
3675 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003676 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003677 }
3678
3679 if (isActive) {
3680 // was it previously inactive?
3681 if (!(state->mTrackMask & (1 << j))) {
3682 ExtendedAudioBufferProvider *eabp = track;
3683 VolumeProvider *vp = track;
3684 fastTrack->mBufferProvider = eabp;
3685 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003686 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003687 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003688 fastTrack->mGeneration++;
3689 state->mTrackMask |= 1 << j;
3690 didModify = true;
3691 // no acknowledgement required for newly active tracks
3692 }
3693 // cache the combined master volume and stream type volume for fast mixer; this
3694 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003695 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003696 ++fastTracks;
3697 } else {
3698 // was it previously active?
3699 if (state->mTrackMask & (1 << j)) {
3700 fastTrack->mBufferProvider = NULL;
3701 fastTrack->mGeneration++;
3702 state->mTrackMask &= ~(1 << j);
3703 didModify = true;
3704 // If any fast tracks were removed, we must wait for acknowledgement
3705 // because we're about to decrement the last sp<> on those tracks.
3706 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3707 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003708 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003709 }
3710 tracksToRemove->add(track);
3711 // Avoids a misleading display in dumpsys
3712 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3713 }
3714 continue;
3715 }
3716
3717 { // local variable scope to avoid goto warning
3718
3719 audio_track_cblk_t* cblk = track->cblk();
3720
3721 // The first time a track is added we wait
3722 // for all its buffers to be filled before processing it
3723 int name = track->name();
3724 // make sure that we have enough frames to mix one full buffer.
3725 // enforce this condition only once to enable draining the buffer in case the client
3726 // app does not call stop() and relies on underrun to stop:
3727 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3728 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003729 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003730 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003731 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003732
3733 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003734 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003735 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3736 // add frames already consumed but not yet released by the resampler
3737 // because mAudioTrackServerProxy->framesReady() will include these frames
3738 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3739
Eric Laurent81784c32012-11-19 14:55:58 -08003740 uint32_t minFrames = 1;
3741 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3742 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003743 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003744 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003745
3746 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003747 if (ATRACE_ENABLED()) {
3748 // I wish we had formatted trace names
3749 char traceName[16];
3750 strcpy(traceName, "nRdy");
3751 int name = track->name();
3752 if (AudioMixer::TRACK0 <= name &&
3753 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3754 name -= AudioMixer::TRACK0;
3755 traceName[4] = (name / 10) + '0';
3756 traceName[5] = (name % 10) + '0';
3757 } else {
3758 traceName[4] = '?';
3759 traceName[5] = '?';
3760 }
3761 traceName[6] = '\0';
3762 ATRACE_INT(traceName, framesReady);
3763 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003764 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003765 !track->isPaused() && !track->isTerminated())
3766 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003767 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003768
3769 mixedTracks++;
3770
Andy Hung69aed5f2014-02-25 17:24:40 -08003771 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3772 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003773 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003774 if (track->mainBuffer() != mSinkBuffer &&
3775 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003776 if (mEffectBufferEnabled) {
3777 mEffectBufferValid = true; // Later can set directly.
3778 }
Eric Laurent81784c32012-11-19 14:55:58 -08003779 chain = getEffectChain_l(track->sessionId());
3780 // Delegate volume control to effect in track effect chain if needed
3781 if (chain != 0) {
3782 tracksWithEffect++;
3783 } else {
3784 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3785 "session %d",
3786 name, track->sessionId());
3787 }
3788 }
3789
3790
3791 int param = AudioMixer::VOLUME;
3792 if (track->mFillingUpStatus == Track::FS_FILLED) {
3793 // no ramp for the first volume setting
3794 track->mFillingUpStatus = Track::FS_ACTIVE;
3795 if (track->mState == TrackBase::RESUMING) {
3796 track->mState = TrackBase::ACTIVE;
3797 param = AudioMixer::RAMP_VOLUME;
3798 }
3799 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003800 // FIXME should not make a decision based on mServer
3801 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003802 // If the track is stopped before the first frame was mixed,
3803 // do not apply ramp
3804 param = AudioMixer::RAMP_VOLUME;
3805 }
3806
3807 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003808 uint32_t vl, vr; // in U8.24 integer format
3809 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003810 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003811 vl = vr = 0;
3812 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003813 if (track->isPausing()) {
3814 track->setPaused();
3815 }
3816 } else {
3817
3818 // read original volumes with volume control
3819 float typeVolume = mStreamTypes[track->streamType()].volume;
3820 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003821 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003822 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003823 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3824 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003825 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003826 if (vlf > GAIN_FLOAT_UNITY) {
3827 ALOGV("Track left volume out of range: %.3g", vlf);
3828 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003829 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003830 if (vrf > GAIN_FLOAT_UNITY) {
3831 ALOGV("Track right volume out of range: %.3g", vrf);
3832 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003833 }
3834 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003835 vlf *= v;
3836 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003837 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003838 // then derive vl and vr as U8.24 versions for the effect chain
3839 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3840 vl = (uint32_t) (scaleto8_24 * vlf);
3841 vr = (uint32_t) (scaleto8_24 * vrf);
3842 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003843 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003844 // send level comes from shared memory and so may be corrupt
3845 if (sendLevel > MAX_GAIN_INT) {
3846 ALOGV("Track send level out of range: %04X", sendLevel);
3847 sendLevel = MAX_GAIN_INT;
3848 }
Andy Hung6be49402014-05-30 10:42:03 -07003849 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3850 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003851 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003852
Eric Laurent81784c32012-11-19 14:55:58 -08003853 // Delegate volume control to effect in track effect chain if needed
3854 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3855 // Do not ramp volume if volume is controlled by effect
3856 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003857 // Update remaining floating point volume levels
3858 vlf = (float)vl / (1 << 24);
3859 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003860 track->mHasVolumeController = true;
3861 } else {
3862 // force no volume ramp when volume controller was just disabled or removed
3863 // from effect chain to avoid volume spike
3864 if (track->mHasVolumeController) {
3865 param = AudioMixer::VOLUME;
3866 }
3867 track->mHasVolumeController = false;
3868 }
3869
Eric Laurent81784c32012-11-19 14:55:58 -08003870 // XXX: these things DON'T need to be done each time
3871 mAudioMixer->setBufferProvider(name, track);
3872 mAudioMixer->enable(name);
3873
Andy Hung6be49402014-05-30 10:42:03 -07003874 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3875 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3876 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003877 mAudioMixer->setParameter(
3878 name,
3879 AudioMixer::TRACK,
3880 AudioMixer::FORMAT, (void *)track->format());
3881 mAudioMixer->setParameter(
3882 name,
3883 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003884 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003885 mAudioMixer->setParameter(
3886 name,
3887 AudioMixer::TRACK,
3888 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003889 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003890 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003891 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003892 if (reqSampleRate == 0) {
3893 reqSampleRate = mSampleRate;
3894 } else if (reqSampleRate > maxSampleRate) {
3895 reqSampleRate = maxSampleRate;
3896 }
Eric Laurent81784c32012-11-19 14:55:58 -08003897 mAudioMixer->setParameter(
3898 name,
3899 AudioMixer::RESAMPLE,
3900 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003901 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003902
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003903 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003904 mAudioMixer->setParameter(
3905 name,
3906 AudioMixer::TIMESTRETCH,
3907 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003908 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003909
Andy Hung69aed5f2014-02-25 17:24:40 -08003910 /*
3911 * Select the appropriate output buffer for the track.
3912 *
Andy Hung98ef9782014-03-04 14:46:50 -08003913 * Tracks with effects go into their own effects chain buffer
3914 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003915 *
3916 * Other tracks can use mMixerBuffer for higher precision
3917 * channel accumulation. If this buffer is enabled
3918 * (mMixerBufferEnabled true), then selected tracks will accumulate
3919 * into it.
3920 *
3921 */
3922 if (mMixerBufferEnabled
3923 && (track->mainBuffer() == mSinkBuffer
3924 || track->mainBuffer() == mMixerBuffer)) {
3925 mAudioMixer->setParameter(
3926 name,
3927 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003928 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003929 mAudioMixer->setParameter(
3930 name,
3931 AudioMixer::TRACK,
3932 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3933 // TODO: override track->mainBuffer()?
3934 mMixerBufferValid = true;
3935 } else {
3936 mAudioMixer->setParameter(
3937 name,
3938 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003939 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003940 mAudioMixer->setParameter(
3941 name,
3942 AudioMixer::TRACK,
3943 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3944 }
Eric Laurent81784c32012-11-19 14:55:58 -08003945 mAudioMixer->setParameter(
3946 name,
3947 AudioMixer::TRACK,
3948 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3949
3950 // reset retry count
3951 track->mRetryCount = kMaxTrackRetries;
3952
3953 // If one track is ready, set the mixer ready if:
3954 // - the mixer was not ready during previous round OR
3955 // - no other track is not ready
3956 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3957 mixerStatus != MIXER_TRACKS_ENABLED) {
3958 mixerStatus = MIXER_TRACKS_READY;
3959 }
3960 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003961 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003962 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003963 }
Eric Laurent81784c32012-11-19 14:55:58 -08003964 // clear effect chain input buffer if an active track underruns to avoid sending
3965 // previous audio buffer again to effects
3966 chain = getEffectChain_l(track->sessionId());
3967 if (chain != 0) {
3968 chain->clearInputBuffer();
3969 }
3970
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003971 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003972 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3973 track->isStopped() || track->isPaused()) {
3974 // We have consumed all the buffers of this track.
3975 // Remove it from the list of active tracks.
3976 // TODO: use actual buffer filling status instead of latency when available from
3977 // audio HAL
3978 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3979 size_t framesWritten = mBytesWritten / mFrameSize;
3980 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3981 if (track->isStopped()) {
3982 track->reset();
3983 }
3984 tracksToRemove->add(track);
3985 }
3986 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003987 // No buffers for this track. Give it a few chances to
3988 // fill a buffer, then remove it from active list.
3989 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003990 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003991 tracksToRemove->add(track);
3992 // indicate to client process that the track was disabled because of underrun;
3993 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003994 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003995 // If one track is not ready, mark the mixer also not ready if:
3996 // - the mixer was ready during previous round OR
3997 // - no other track is ready
3998 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3999 mixerStatus != MIXER_TRACKS_READY) {
4000 mixerStatus = MIXER_TRACKS_ENABLED;
4001 }
4002 }
4003 mAudioMixer->disable(name);
4004 }
4005
4006 } // local variable scope to avoid goto warning
4007track_is_ready: ;
4008
4009 }
4010
4011 // Push the new FastMixer state if necessary
4012 bool pauseAudioWatchdog = false;
4013 if (didModify) {
4014 state->mFastTracksGen++;
4015 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4016 if (kUseFastMixer == FastMixer_Dynamic &&
4017 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4018 state->mCommand = FastMixerState::COLD_IDLE;
4019 state->mColdFutexAddr = &mFastMixerFutex;
4020 state->mColdGen++;
4021 mFastMixerFutex = 0;
4022 if (kUseFastMixer == FastMixer_Dynamic) {
4023 mNormalSink = mOutputSink;
4024 }
4025 // If we go into cold idle, need to wait for acknowledgement
4026 // so that fast mixer stops doing I/O.
4027 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4028 pauseAudioWatchdog = true;
4029 }
Eric Laurent81784c32012-11-19 14:55:58 -08004030 }
4031 if (sq != NULL) {
4032 sq->end(didModify);
4033 sq->push(block);
4034 }
4035#ifdef AUDIO_WATCHDOG
4036 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4037 mAudioWatchdog->pause();
4038 }
4039#endif
4040
4041 // Now perform the deferred reset on fast tracks that have stopped
4042 while (resetMask != 0) {
4043 size_t i = __builtin_ctz(resetMask);
4044 ALOG_ASSERT(i < count);
4045 resetMask &= ~(1 << i);
4046 sp<Track> t = mActiveTracks[i].promote();
4047 if (t == 0) {
4048 continue;
4049 }
4050 Track* track = t.get();
4051 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4052 track->reset();
4053 }
4054
4055 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004056 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004057
Eric Laurent97d547d2014-09-02 14:45:53 -07004058 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4059 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004060 }
4061
4062 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004063 // as long as there are effects we should clear the effects buffer, to avoid
4064 // passing a non-clean buffer to the effect chain
4065 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004066 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004067 // sink or mix buffer must be cleared if all tracks are connected to an
4068 // effect chain as in this case the mixer will not write to the sink or mix buffer
4069 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4071 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004072 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004073 if (mMixerBufferValid) {
4074 memset(mMixerBuffer, 0, mMixerBufferSize);
4075 // TODO: In testing, mSinkBuffer below need not be cleared because
4076 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4077 // after mixing.
4078 //
4079 // To enforce this guarantee:
4080 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4081 // (mixedTracks == 0 && fastTracks > 0))
4082 // must imply MIXER_TRACKS_READY.
4083 // Later, we may clear buffers regardless, and skip much of this logic.
4084 }
Andy Hung98ef9782014-03-04 14:46:50 -08004085 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004086 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004087 }
4088
4089 // if any fast tracks, then status is ready
4090 mMixerStatusIgnoringFastTracks = mixerStatus;
4091 if (fastTracks > 0) {
4092 mixerStatus = MIXER_TRACKS_READY;
4093 }
4094 return mixerStatus;
4095}
4096
4097// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004098int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4099 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004100{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004101 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004102}
4103
4104// deleteTrackName_l() must be called with ThreadBase::mLock held
4105void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4106{
4107 ALOGV("remove track (%d) and delete from mixer", name);
4108 mAudioMixer->deleteTrackName(name);
4109}
4110
Eric Laurent10351942014-05-08 18:49:52 -07004111// checkForNewParameter_l() must be called with ThreadBase::mLock held
4112bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4113 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004114{
Eric Laurent81784c32012-11-19 14:55:58 -08004115 bool reconfig = false;
4116
Eric Laurent10351942014-05-08 18:49:52 -07004117 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004118
Eric Laurent10351942014-05-08 18:49:52 -07004119 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4120 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004121 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004122 FastMixerStateQueue *sq = mFastMixer->sq();
4123 FastMixerState *state = sq->begin();
4124 if (!(state->mCommand & FastMixerState::IDLE)) {
4125 previousCommand = state->mCommand;
4126 state->mCommand = FastMixerState::HOT_IDLE;
4127 sq->end();
4128 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4129 } else {
4130 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004131 }
Eric Laurent10351942014-05-08 18:49:52 -07004132 }
Eric Laurent81784c32012-11-19 14:55:58 -08004133
Eric Laurent10351942014-05-08 18:49:52 -07004134 AudioParameter param = AudioParameter(keyValuePair);
4135 int value;
4136 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4137 reconfig = true;
4138 }
4139 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004140 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004141 status = BAD_VALUE;
4142 } else {
4143 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004144 reconfig = true;
4145 }
Eric Laurent10351942014-05-08 18:49:52 -07004146 }
4147 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004148 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004149 status = BAD_VALUE;
4150 } else {
4151 // no need to save value, since it's constant
4152 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004153 }
Eric Laurent10351942014-05-08 18:49:52 -07004154 }
4155 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4156 // do not accept frame count changes if tracks are open as the track buffer
4157 // size depends on frame count and correct behavior would not be guaranteed
4158 // if frame count is changed after track creation
4159 if (!mTracks.isEmpty()) {
4160 status = INVALID_OPERATION;
4161 } else {
4162 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004163 }
Eric Laurent10351942014-05-08 18:49:52 -07004164 }
4165 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004166#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004167 // when changing the audio output device, call addBatteryData to notify
4168 // the change
4169 if (mOutDevice != value) {
4170 uint32_t params = 0;
4171 // check whether speaker is on
4172 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4173 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004174 }
Eric Laurent10351942014-05-08 18:49:52 -07004175
4176 audio_devices_t deviceWithoutSpeaker
4177 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4178 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004179 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004180 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4181 }
4182
4183 if (params != 0) {
4184 addBatteryData(params);
4185 }
4186 }
Eric Laurent81784c32012-11-19 14:55:58 -08004187#endif
4188
Eric Laurent10351942014-05-08 18:49:52 -07004189 // forward device change to effects that have requested to be
4190 // aware of attached audio device.
4191 if (value != AUDIO_DEVICE_NONE) {
4192 mOutDevice = value;
4193 for (size_t i = 0; i < mEffectChains.size(); i++) {
4194 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004195 }
4196 }
Eric Laurent10351942014-05-08 18:49:52 -07004197 }
Eric Laurent81784c32012-11-19 14:55:58 -08004198
Eric Laurent10351942014-05-08 18:49:52 -07004199 if (status == NO_ERROR) {
4200 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4201 keyValuePair.string());
4202 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004203 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004204 mStandby = true;
4205 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004206 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004207 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004208 }
Eric Laurent10351942014-05-08 18:49:52 -07004209 if (status == NO_ERROR && reconfig) {
4210 readOutputParameters_l();
4211 delete mAudioMixer;
4212 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4213 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004214 int name = getTrackName_l(mTracks[i]->mChannelMask,
4215 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004216 if (name < 0) {
4217 break;
4218 }
4219 mTracks[i]->mName = name;
4220 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004221 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004222 }
Eric Laurent81784c32012-11-19 14:55:58 -08004223 }
4224
4225 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004226 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004227 FastMixerStateQueue *sq = mFastMixer->sq();
4228 FastMixerState *state = sq->begin();
4229 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4230 state->mCommand = previousCommand;
4231 sq->end();
4232 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4233 }
4234
4235 return reconfig;
4236}
4237
4238
4239void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4240{
4241 const size_t SIZE = 256;
4242 char buffer[SIZE];
4243 String8 result;
4244
4245 PlaybackThread::dumpInternals(fd, args);
4246
Elliott Hughes87cebad2014-05-22 10:14:43 -07004247 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004248
4249 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004250 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004251 copy.dump(fd);
4252
4253#ifdef STATE_QUEUE_DUMP
4254 // Similar for state queue
4255 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4256 observerCopy.dump(fd);
4257 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4258 mutatorCopy.dump(fd);
4259#endif
4260
Glenn Kasten46909e72013-02-26 09:20:22 -08004261#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004262 // Write the tee output to a .wav file
4263 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004264#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004265
4266#ifdef AUDIO_WATCHDOG
4267 if (mAudioWatchdog != 0) {
4268 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4269 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4270 wdCopy.dump(fd);
4271 }
4272#endif
4273}
4274
4275uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4276{
4277 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4278}
4279
4280uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4281{
4282 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4283}
4284
4285void AudioFlinger::MixerThread::cacheParameters_l()
4286{
4287 PlaybackThread::cacheParameters_l();
4288
4289 // FIXME: Relaxed timing because of a certain device that can't meet latency
4290 // Should be reduced to 2x after the vendor fixes the driver issue
4291 // increase threshold again due to low power audio mode. The way this warning
4292 // threshold is calculated and its usefulness should be reconsidered anyway.
4293 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4294}
4295
4296// ----------------------------------------------------------------------------
4297
4298AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4299 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4300 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4301 // mLeftVolFloat, mRightVolFloat
4302{
4303}
4304
Eric Laurentbfb1b832013-01-07 09:53:42 -08004305AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4306 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4307 ThreadBase::type_t type)
4308 : PlaybackThread(audioFlinger, output, id, device, type)
4309 // mLeftVolFloat, mRightVolFloat
4310{
4311}
4312
Eric Laurent81784c32012-11-19 14:55:58 -08004313AudioFlinger::DirectOutputThread::~DirectOutputThread()
4314{
4315}
4316
Eric Laurentbfb1b832013-01-07 09:53:42 -08004317void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4318{
4319 audio_track_cblk_t* cblk = track->cblk();
4320 float left, right;
4321
4322 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4323 left = right = 0;
4324 } else {
4325 float typeVolume = mStreamTypes[track->streamType()].volume;
4326 float v = mMasterVolume * typeVolume;
4327 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004328 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4329 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4330 if (left > GAIN_FLOAT_UNITY) {
4331 left = GAIN_FLOAT_UNITY;
4332 }
4333 left *= v;
4334 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4335 if (right > GAIN_FLOAT_UNITY) {
4336 right = GAIN_FLOAT_UNITY;
4337 }
4338 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004339 }
4340
4341 if (lastTrack) {
4342 if (left != mLeftVolFloat || right != mRightVolFloat) {
4343 mLeftVolFloat = left;
4344 mRightVolFloat = right;
4345
4346 // Convert volumes from float to 8.24
4347 uint32_t vl = (uint32_t)(left * (1 << 24));
4348 uint32_t vr = (uint32_t)(right * (1 << 24));
4349
4350 // Delegate volume control to effect in track effect chain if needed
4351 // only one effect chain can be present on DirectOutputThread, so if
4352 // there is one, the track is connected to it
4353 if (!mEffectChains.isEmpty()) {
4354 mEffectChains[0]->setVolume_l(&vl, &vr);
4355 left = (float)vl / (1 << 24);
4356 right = (float)vr / (1 << 24);
4357 }
4358 if (mOutput->stream->set_volume) {
4359 mOutput->stream->set_volume(mOutput->stream, left, right);
4360 }
4361 }
4362 }
4363}
4364
4365
Eric Laurent81784c32012-11-19 14:55:58 -08004366AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4367 Vector< sp<Track> > *tracksToRemove
4368)
4369{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004370 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004371 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004372 bool doHwPause = false;
4373 bool doHwResume = false;
4374 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004375
4376 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004377 for (size_t i = 0; i < count; i++) {
4378 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004379 // The track died recently
4380 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004381 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004382 }
4383
4384 Track* const track = t.get();
4385 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004386 // Only consider last track started for volume and mixer state control.
4387 // In theory an older track could underrun and restart after the new one starts
4388 // but as we only care about the transition phase between two tracks on a
4389 // direct output, it is not a problem to ignore the underrun case.
4390 sp<Track> l = mLatestActiveTrack.promote();
4391 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004392
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004393 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004394 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004395 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004396 doHwPause = true;
4397 mHwPaused = true;
4398 }
4399 tracksToRemove->add(track);
4400 } else if (track->isFlushPending()) {
4401 track->flushAck();
4402 if (last) {
4403 flushPending = true;
4404 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004405 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004406 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004407 if (last && mHwPaused) {
4408 doHwResume = true;
4409 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004410 }
4411 }
4412
Eric Laurent81784c32012-11-19 14:55:58 -08004413 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004414 // for all its buffers to be filled before processing it.
4415 // Allow draining the buffer in case the client
4416 // app does not call stop() and relies on underrun to stop:
4417 // hence the test on (track->mRetryCount > 1).
4418 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004419 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004420 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4421 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004422 minFrames = mNormalFrameCount;
4423 } else {
4424 minFrames = 1;
4425 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426
Eric Laurentab5cdba2014-06-09 17:22:27 -07004427 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4428 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004429 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004430 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004431
4432 if (track->mFillingUpStatus == Track::FS_FILLED) {
4433 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004434 // make sure processVolume_l() will apply new volume even if 0
4435 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004436 if (!mHwSupportsPause) {
4437 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004438 }
4439 }
4440
4441 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004442 processVolume_l(track, last);
4443 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004444 // reset retry count
4445 track->mRetryCount = kMaxTrackRetriesDirect;
4446 mActiveTrack = t;
4447 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004448 if (usesHwAvSync() && mHwPaused) {
4449 doHwResume = true;
4450 mHwPaused = false;
4451 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004452 }
Eric Laurent81784c32012-11-19 14:55:58 -08004453 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004454 // clear effect chain input buffer if the last active track started underruns
4455 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004456 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004457 mEffectChains[0]->clearInputBuffer();
4458 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004459 if (track->isStopping_1()) {
4460 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004461 if (last && mHwPaused) {
4462 doHwResume = true;
4463 mHwPaused = false;
4464 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004465 }
4466 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4467 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004468 // We have consumed all the buffers of this track.
4469 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004470 size_t audioHALFrames;
4471 if (audio_is_linear_pcm(mFormat)) {
4472 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4473 } else {
4474 audioHALFrames = 0;
4475 }
4476
Eric Laurent81784c32012-11-19 14:55:58 -08004477 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004478 if (mStandby || !last ||
4479 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004480 if (track->isStopping_2()) {
4481 track->mState = TrackBase::STOPPED;
4482 }
Eric Laurent81784c32012-11-19 14:55:58 -08004483 if (track->isStopped()) {
4484 track->reset();
4485 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004486 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004487 }
4488 } else {
4489 // No buffers for this track. Give it a few chances to
4490 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004491 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004492 if (--(track->mRetryCount) <= 0) {
4493 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004494 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004495 // indicate to client process that the track was disabled because of underrun;
4496 // it will then automatically call start() when data is available
4497 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004498 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004499 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004500 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4501 doHwPause = true;
4502 mHwPaused = true;
4503 }
Eric Laurent81784c32012-11-19 14:55:58 -08004504 }
4505 }
4506 }
4507 }
4508
Eric Laurentd1f69b02014-12-15 14:33:13 -08004509 // if an active track did not command a flush, check for pending flush on stopped tracks
4510 if (!flushPending) {
4511 for (size_t i = 0; i < mTracks.size(); i++) {
4512 if (mTracks[i]->isFlushPending()) {
4513 mTracks[i]->flushAck();
4514 flushPending = true;
4515 }
4516 }
4517 }
4518
4519 // make sure the pause/flush/resume sequence is executed in the right order.
4520 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4521 // before flush and then resume HW. This can happen in case of pause/flush/resume
4522 // if resume is received before pause is executed.
4523 if (mHwSupportsPause && !mStandby &&
4524 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4525 mOutput->stream->pause(mOutput->stream);
4526 }
4527 if (flushPending) {
4528 flushHw_l();
4529 }
4530 if (mHwSupportsPause && !mStandby && doHwResume) {
4531 mOutput->stream->resume(mOutput->stream);
4532 }
Eric Laurent81784c32012-11-19 14:55:58 -08004533 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004534 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004535
4536 return mixerStatus;
4537}
4538
4539void AudioFlinger::DirectOutputThread::threadLoop_mix()
4540{
Eric Laurent81784c32012-11-19 14:55:58 -08004541 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004542 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004543 // output audio to hardware
4544 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004545 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004546 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004547 status_t status = mActiveTrack->getNextBuffer(&buffer);
4548 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004549 memset(curBuf, 0, frameCount * mFrameSize);
4550 break;
4551 }
4552 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4553 frameCount -= buffer.frameCount;
4554 curBuf += buffer.frameCount * mFrameSize;
4555 mActiveTrack->releaseBuffer(&buffer);
4556 }
Andy Hung2098f272014-02-27 14:00:06 -08004557 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004558 sleepTime = 0;
4559 standbyTime = systemTime() + standbyDelay;
4560 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004561}
4562
4563void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4564{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004565 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004566 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004567 sleepTime = idleSleepTime;
4568 return;
4569 }
Eric Laurent81784c32012-11-19 14:55:58 -08004570 if (sleepTime == 0) {
4571 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4572 sleepTime = activeSleepTime;
4573 } else {
4574 sleepTime = idleSleepTime;
4575 }
4576 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004577 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004578 sleepTime = 0;
4579 }
4580}
4581
Eric Laurentd1f69b02014-12-15 14:33:13 -08004582void AudioFlinger::DirectOutputThread::threadLoop_exit()
4583{
4584 {
4585 Mutex::Autolock _l(mLock);
4586 bool flushPending = false;
4587 for (size_t i = 0; i < mTracks.size(); i++) {
4588 if (mTracks[i]->isFlushPending()) {
4589 mTracks[i]->flushAck();
4590 flushPending = true;
4591 }
4592 }
4593 if (flushPending) {
4594 flushHw_l();
4595 }
4596 }
4597 PlaybackThread::threadLoop_exit();
4598}
4599
4600// must be called with thread mutex locked
4601bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4602{
4603 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004604 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004605
4606 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4607 // after a timeout and we will enter standby then.
4608 if (mTracks.size() > 0) {
4609 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004610 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4611 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004612 }
4613
Eric Laurentb369caf2015-03-30 20:51:47 -07004614 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004615}
4616
Eric Laurent81784c32012-11-19 14:55:58 -08004617// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004618int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004619 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004620{
4621 return 0;
4622}
4623
4624// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004625void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004626{
4627}
4628
Eric Laurent10351942014-05-08 18:49:52 -07004629// checkForNewParameter_l() must be called with ThreadBase::mLock held
4630bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4631 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004632{
4633 bool reconfig = false;
4634
Eric Laurent10351942014-05-08 18:49:52 -07004635 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004636
Eric Laurent10351942014-05-08 18:49:52 -07004637 AudioParameter param = AudioParameter(keyValuePair);
4638 int value;
4639 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4640 // forward device change to effects that have requested to be
4641 // aware of attached audio device.
4642 if (value != AUDIO_DEVICE_NONE) {
4643 mOutDevice = value;
4644 for (size_t i = 0; i < mEffectChains.size(); i++) {
4645 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004646 }
4647 }
Eric Laurent81784c32012-11-19 14:55:58 -08004648 }
Eric Laurent10351942014-05-08 18:49:52 -07004649 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4650 // do not accept frame count changes if tracks are open as the track buffer
4651 // size depends on frame count and correct behavior would not be garantied
4652 // if frame count is changed after track creation
4653 if (!mTracks.isEmpty()) {
4654 status = INVALID_OPERATION;
4655 } else {
4656 reconfig = true;
4657 }
4658 }
4659 if (status == NO_ERROR) {
4660 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4661 keyValuePair.string());
4662 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004663 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004664 mStandby = true;
4665 mBytesWritten = 0;
4666 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4667 keyValuePair.string());
4668 }
4669 if (status == NO_ERROR && reconfig) {
4670 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004671 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004672 }
4673 }
4674
Eric Laurent81784c32012-11-19 14:55:58 -08004675 return reconfig;
4676}
4677
4678uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4679{
4680 uint32_t time;
4681 if (audio_is_linear_pcm(mFormat)) {
4682 time = PlaybackThread::activeSleepTimeUs();
4683 } else {
4684 time = 10000;
4685 }
4686 return time;
4687}
4688
4689uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4690{
4691 uint32_t time;
4692 if (audio_is_linear_pcm(mFormat)) {
4693 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4694 } else {
4695 time = 10000;
4696 }
4697 return time;
4698}
4699
4700uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4701{
4702 uint32_t time;
4703 if (audio_is_linear_pcm(mFormat)) {
4704 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4705 } else {
4706 time = 10000;
4707 }
4708 return time;
4709}
4710
4711void AudioFlinger::DirectOutputThread::cacheParameters_l()
4712{
4713 PlaybackThread::cacheParameters_l();
4714
4715 // use shorter standby delay as on normal output to release
4716 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004717 // no delay on outputs with HW A/V sync
4718 if (usesHwAvSync()) {
4719 standbyDelay = 0;
4720 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004721 standbyDelay = microseconds(activeSleepTime*2);
4722 } else {
4723 standbyDelay = kOffloadStandbyDelayNs;
4724 }
Eric Laurent81784c32012-11-19 14:55:58 -08004725}
4726
Eric Laurente659ef42014-09-29 13:06:46 -07004727void AudioFlinger::DirectOutputThread::flushHw_l()
4728{
Phil Burk062e67a2015-02-11 13:40:50 -08004729 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004730 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004731}
4732
Eric Laurent81784c32012-11-19 14:55:58 -08004733// ----------------------------------------------------------------------------
4734
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004736 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004737 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004738 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004739 mWriteAckSequence(0),
4740 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004741{
4742}
4743
4744AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4745{
4746}
4747
4748void AudioFlinger::AsyncCallbackThread::onFirstRef()
4749{
4750 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4751}
4752
4753bool AudioFlinger::AsyncCallbackThread::threadLoop()
4754{
4755 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004756 uint32_t writeAckSequence;
4757 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758
4759 {
4760 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004761 while (!((mWriteAckSequence & 1) ||
4762 (mDrainSequence & 1) ||
4763 exitPending())) {
4764 mWaitWorkCV.wait(mLock);
4765 }
4766
Eric Laurentbfb1b832013-01-07 09:53:42 -08004767 if (exitPending()) {
4768 break;
4769 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004770 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4771 mWriteAckSequence, mDrainSequence);
4772 writeAckSequence = mWriteAckSequence;
4773 mWriteAckSequence &= ~1;
4774 drainSequence = mDrainSequence;
4775 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004776 }
4777 {
Eric Laurent4de95592013-09-26 15:28:21 -07004778 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4779 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004780 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004781 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004782 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004783 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004784 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004785 }
4786 }
4787 }
4788 }
4789 return false;
4790}
4791
4792void AudioFlinger::AsyncCallbackThread::exit()
4793{
4794 ALOGV("AsyncCallbackThread::exit");
4795 Mutex::Autolock _l(mLock);
4796 requestExit();
4797 mWaitWorkCV.broadcast();
4798}
4799
Eric Laurent3b4529e2013-09-05 18:09:19 -07004800void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801{
4802 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004803 // bit 0 is cleared
4804 mWriteAckSequence = sequence << 1;
4805}
4806
4807void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4808{
4809 Mutex::Autolock _l(mLock);
4810 // ignore unexpected callbacks
4811 if (mWriteAckSequence & 2) {
4812 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004813 mWaitWorkCV.signal();
4814 }
4815}
4816
Eric Laurent3b4529e2013-09-05 18:09:19 -07004817void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004818{
4819 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004820 // bit 0 is cleared
4821 mDrainSequence = sequence << 1;
4822}
4823
4824void AudioFlinger::AsyncCallbackThread::resetDraining()
4825{
4826 Mutex::Autolock _l(mLock);
4827 // ignore unexpected callbacks
4828 if (mDrainSequence & 2) {
4829 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004830 mWaitWorkCV.signal();
4831 }
4832}
4833
4834
4835// ----------------------------------------------------------------------------
4836AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4837 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4838 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004839 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004840{
Eric Laurentfd477972013-10-25 18:10:40 -07004841 //FIXME: mStandby should be set to true by ThreadBase constructor
4842 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004843}
4844
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845void AudioFlinger::OffloadThread::threadLoop_exit()
4846{
4847 if (mFlushPending || mHwPaused) {
4848 // If a flush is pending or track was paused, just discard buffered data
4849 flushHw_l();
4850 } else {
4851 mMixerStatus = MIXER_DRAIN_ALL;
4852 threadLoop_drain();
4853 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004854 if (mUseAsyncWrite) {
4855 ALOG_ASSERT(mCallbackThread != 0);
4856 mCallbackThread->exit();
4857 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004858 PlaybackThread::threadLoop_exit();
4859}
4860
4861AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4862 Vector< sp<Track> > *tracksToRemove
4863)
4864{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004865 size_t count = mActiveTracks.size();
4866
4867 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004868 bool doHwPause = false;
4869 bool doHwResume = false;
4870
Eric Laurentede6c3b2013-09-19 14:37:46 -07004871 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4872
Eric Laurentbfb1b832013-01-07 09:53:42 -08004873 // find out which tracks need to be processed
4874 for (size_t i = 0; i < count; i++) {
4875 sp<Track> t = mActiveTracks[i].promote();
4876 // The track died recently
4877 if (t == 0) {
4878 continue;
4879 }
4880 Track* const track = t.get();
4881 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004882 // Only consider last track started for volume and mixer state control.
4883 // In theory an older track could underrun and restart after the new one starts
4884 // but as we only care about the transition phase between two tracks on a
4885 // direct output, it is not a problem to ignore the underrun case.
4886 sp<Track> l = mLatestActiveTrack.promote();
4887 bool last = l.get() == track;
4888
Haynes Mathew George7844f672014-01-15 12:32:55 -08004889 if (track->isInvalid()) {
4890 ALOGW("An invalidated track shouldn't be in active list");
4891 tracksToRemove->add(track);
4892 continue;
4893 }
4894
4895 if (track->mState == TrackBase::IDLE) {
4896 ALOGW("An idle track shouldn't be in active list");
4897 continue;
4898 }
4899
Eric Laurentbfb1b832013-01-07 09:53:42 -08004900 if (track->isPausing()) {
4901 track->setPaused();
4902 if (last) {
4903 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004904 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004905 mHwPaused = true;
4906 }
4907 // If we were part way through writing the mixbuffer to
4908 // the HAL we must save this until we resume
4909 // BUG - this will be wrong if a different track is made active,
4910 // in that case we want to discard the pending data in the
4911 // mixbuffer and tell the client to present it again when the
4912 // track is resumed
4913 mPausedWriteLength = mCurrentWriteLength;
4914 mPausedBytesRemaining = mBytesRemaining;
4915 mBytesRemaining = 0; // stop writing
4916 }
4917 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004918 } else if (track->isFlushPending()) {
4919 track->flushAck();
4920 if (last) {
4921 mFlushPending = true;
4922 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004923 } else if (track->isResumePending()){
4924 track->resumeAck();
4925 if (last) {
4926 if (mPausedBytesRemaining) {
4927 // Need to continue write that was interrupted
4928 mCurrentWriteLength = mPausedWriteLength;
4929 mBytesRemaining = mPausedBytesRemaining;
4930 mPausedBytesRemaining = 0;
4931 }
4932 if (mHwPaused) {
4933 doHwResume = true;
4934 mHwPaused = false;
4935 // threadLoop_mix() will handle the case that we need to
4936 // resume an interrupted write
4937 }
4938 // enable write to audio HAL
4939 sleepTime = 0;
4940
4941 // Do not handle new data in this iteration even if track->framesReady()
4942 mixerStatus = MIXER_TRACKS_ENABLED;
4943 }
4944 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004945 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004946 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004947 if (track->mFillingUpStatus == Track::FS_FILLED) {
4948 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004949 // make sure processVolume_l() will apply new volume even if 0
4950 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004951 }
4952
4953 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004954 sp<Track> previousTrack = mPreviousTrack.promote();
4955 if (previousTrack != 0) {
4956 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004957 // Flush any data still being written from last track
4958 mBytesRemaining = 0;
4959 if (mPausedBytesRemaining) {
4960 // Last track was paused so we also need to flush saved
4961 // mixbuffer state and invalidate track so that it will
4962 // re-submit that unwritten data when it is next resumed
4963 mPausedBytesRemaining = 0;
4964 // Invalidate is a bit drastic - would be more efficient
4965 // to have a flag to tell client that some of the
4966 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004967 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004968 }
4969 // flush data already sent to the DSP if changing audio session as audio
4970 // comes from a different source. Also invalidate previous track to force a
4971 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004972 if (previousTrack->sessionId() != track->sessionId()) {
4973 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004974 }
4975 }
4976 }
4977 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004978 // reset retry count
4979 track->mRetryCount = kMaxTrackRetriesOffload;
4980 mActiveTrack = t;
4981 mixerStatus = MIXER_TRACKS_READY;
4982 }
4983 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004984 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004985 if (track->isStopping_1()) {
4986 // Hardware buffer can hold a large amount of audio so we must
4987 // wait for all current track's data to drain before we say
4988 // that the track is stopped.
4989 if (mBytesRemaining == 0) {
4990 // Only start draining when all data in mixbuffer
4991 // has been written
4992 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4993 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004994 // do not drain if no data was ever sent to HAL (mStandby == true)
4995 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004996 // do not modify drain sequence if we are already draining. This happens
4997 // when resuming from pause after drain.
4998 if ((mDrainSequence & 1) == 0) {
4999 sleepTime = 0;
5000 standbyTime = systemTime() + standbyDelay;
5001 mixerStatus = MIXER_DRAIN_TRACK;
5002 mDrainSequence += 2;
5003 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005004 if (mHwPaused) {
5005 // It is possible to move from PAUSED to STOPPING_1 without
5006 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005007 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005008 mHwPaused = false;
5009 }
5010 }
5011 }
5012 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005013 // Drain has completed or we are in standby, signal presentation complete
5014 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005015 track->mState = TrackBase::STOPPED;
5016 size_t audioHALFrames =
5017 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5018 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005019 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005020 track->presentationComplete(framesWritten, audioHALFrames);
5021 track->reset();
5022 tracksToRemove->add(track);
5023 }
5024 } else {
5025 // No buffers for this track. Give it a few chances to
5026 // fill a buffer, then remove it from active list.
5027 if (--(track->mRetryCount) <= 0) {
5028 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5029 track->name());
5030 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005031 // indicate to client process that the track was disabled because of underrun;
5032 // it will then automatically call start() when data is available
5033 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005034 } else if (last){
5035 mixerStatus = MIXER_TRACKS_ENABLED;
5036 }
5037 }
5038 }
5039 // compute volume for this track
5040 processVolume_l(track, last);
5041 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005042
Eric Laurentea0fade2013-10-04 16:23:48 -07005043 // make sure the pause/flush/resume sequence is executed in the right order.
5044 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5045 // before flush and then resume HW. This can happen in case of pause/flush/resume
5046 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005047 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005048 mOutput->stream->pause(mOutput->stream);
5049 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005050 if (mFlushPending) {
5051 flushHw_l();
5052 mFlushPending = false;
5053 }
Eric Laurentfd477972013-10-25 18:10:40 -07005054 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005055 mOutput->stream->resume(mOutput->stream);
5056 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005057
Eric Laurentbfb1b832013-01-07 09:53:42 -08005058 // remove all the tracks that need to be...
5059 removeTracks_l(*tracksToRemove);
5060
5061 return mixerStatus;
5062}
5063
Eric Laurentbfb1b832013-01-07 09:53:42 -08005064// must be called with thread mutex locked
5065bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5066{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005067 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5068 mWriteAckSequence, mDrainSequence);
5069 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005070 return true;
5071 }
5072 return false;
5073}
5074
Eric Laurentbfb1b832013-01-07 09:53:42 -08005075bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5076{
5077 Mutex::Autolock _l(mLock);
5078 return waitingAsyncCallback_l();
5079}
5080
5081void AudioFlinger::OffloadThread::flushHw_l()
5082{
Eric Laurente659ef42014-09-29 13:06:46 -07005083 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005084 // Flush anything still waiting in the mixbuffer
5085 mCurrentWriteLength = 0;
5086 mBytesRemaining = 0;
5087 mPausedWriteLength = 0;
5088 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005089
Eric Laurentbfb1b832013-01-07 09:53:42 -08005090 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005091 // discard any pending drain or write ack by incrementing sequence
5092 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5093 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005094 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005095 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5096 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005097 }
5098}
5099
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005100void AudioFlinger::OffloadThread::onAddNewTrack_l()
5101{
5102 sp<Track> previousTrack = mPreviousTrack.promote();
5103 sp<Track> latestTrack = mLatestActiveTrack.promote();
5104
5105 if (previousTrack != 0 && latestTrack != 0 &&
5106 (previousTrack->sessionId() != latestTrack->sessionId())) {
5107 mFlushPending = true;
5108 }
5109 PlaybackThread::onAddNewTrack_l();
5110}
5111
Eric Laurentbfb1b832013-01-07 09:53:42 -08005112// ----------------------------------------------------------------------------
5113
Eric Laurent81784c32012-11-19 14:55:58 -08005114AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5115 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
5116 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5117 DUPLICATING),
5118 mWaitTimeMs(UINT_MAX)
5119{
5120 addOutputTrack(mainThread);
5121}
5122
5123AudioFlinger::DuplicatingThread::~DuplicatingThread()
5124{
5125 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5126 mOutputTracks[i]->destroy();
5127 }
5128}
5129
5130void AudioFlinger::DuplicatingThread::threadLoop_mix()
5131{
5132 // mix buffers...
5133 if (outputsReady(outputTracks)) {
5134 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5135 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005136 if (mMixerBufferValid) {
5137 memset(mMixerBuffer, 0, mMixerBufferSize);
5138 } else {
5139 memset(mSinkBuffer, 0, mSinkBufferSize);
5140 }
Eric Laurent81784c32012-11-19 14:55:58 -08005141 }
5142 sleepTime = 0;
5143 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005144 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005145 standbyTime = systemTime() + standbyDelay;
5146}
5147
5148void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5149{
5150 if (sleepTime == 0) {
5151 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5152 sleepTime = activeSleepTime;
5153 } else {
5154 sleepTime = idleSleepTime;
5155 }
5156 } else if (mBytesWritten != 0) {
5157 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5158 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005159 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005160 } else {
5161 // flush remaining overflow buffers in output tracks
5162 writeFrames = 0;
5163 }
5164 sleepTime = 0;
5165 }
5166}
5167
Eric Laurentbfb1b832013-01-07 09:53:42 -08005168ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005169{
5170 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005171 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005172 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005173 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005174 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005175}
5176
5177void AudioFlinger::DuplicatingThread::threadLoop_standby()
5178{
5179 // DuplicatingThread implements standby by stopping all tracks
5180 for (size_t i = 0; i < outputTracks.size(); i++) {
5181 outputTracks[i]->stop();
5182 }
5183}
5184
5185void AudioFlinger::DuplicatingThread::saveOutputTracks()
5186{
5187 outputTracks = mOutputTracks;
5188}
5189
5190void AudioFlinger::DuplicatingThread::clearOutputTracks()
5191{
5192 outputTracks.clear();
5193}
5194
5195void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5196{
5197 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005198 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5199 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5200 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5201 const size_t frameCount =
5202 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5203 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5204 // from different OutputTracks and their associated MixerThreads (e.g. one may
5205 // nearly empty and the other may be dropping data).
5206
5207 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005208 this,
5209 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005210 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005211 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005212 frameCount,
5213 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005214 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005215 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005216 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005217 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005218 updateWaitTime_l();
5219 }
5220}
5221
5222void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5223{
5224 Mutex::Autolock _l(mLock);
5225 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5226 if (mOutputTracks[i]->thread() == thread) {
5227 mOutputTracks[i]->destroy();
5228 mOutputTracks.removeAt(i);
5229 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005230 if (thread->getOutput() == mOutput) {
5231 mOutput = NULL;
5232 }
Eric Laurent81784c32012-11-19 14:55:58 -08005233 return;
5234 }
5235 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005236 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005237}
5238
5239// caller must hold mLock
5240void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5241{
5242 mWaitTimeMs = UINT_MAX;
5243 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5244 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5245 if (strong != 0) {
5246 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5247 if (waitTimeMs < mWaitTimeMs) {
5248 mWaitTimeMs = waitTimeMs;
5249 }
5250 }
5251 }
5252}
5253
5254
5255bool AudioFlinger::DuplicatingThread::outputsReady(
5256 const SortedVector< sp<OutputTrack> > &outputTracks)
5257{
5258 for (size_t i = 0; i < outputTracks.size(); i++) {
5259 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5260 if (thread == 0) {
5261 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5262 outputTracks[i].get());
5263 return false;
5264 }
5265 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5266 // see note at standby() declaration
5267 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5268 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5269 thread.get());
5270 return false;
5271 }
5272 }
5273 return true;
5274}
5275
5276uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5277{
5278 return (mWaitTimeMs * 1000) / 2;
5279}
5280
5281void AudioFlinger::DuplicatingThread::cacheParameters_l()
5282{
5283 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5284 updateWaitTime_l();
5285
5286 MixerThread::cacheParameters_l();
5287}
5288
5289// ----------------------------------------------------------------------------
5290// Record
5291// ----------------------------------------------------------------------------
5292
5293AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5294 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005295 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005296 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005297 audio_devices_t inDevice
5298#ifdef TEE_SINK
5299 , const sp<NBAIO_Sink>& teeSink
5300#endif
5301 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005302 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005303 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005304 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005305 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005306#ifdef TEE_SINK
5307 , mTeeSink(teeSink)
5308#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005309 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5310 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005311 // mFastCapture below
5312 , mFastCaptureFutex(0)
5313 // mInputSource
5314 // mPipeSink
5315 // mPipeSource
5316 , mPipeFramesP2(0)
5317 // mPipeMemory
5318 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005319 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005320{
Glenn Kastend7dca052015-03-05 16:05:54 -08005321 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5322 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005323
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005324 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005325
5326 // create an NBAIO source for the HAL input stream, and negotiate
5327 mInputSource = new AudioStreamInSource(input->stream);
5328 size_t numCounterOffers = 0;
5329 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5330 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5331 ALOG_ASSERT(index == 0);
5332
5333 // initialize fast capture depending on configuration
5334 bool initFastCapture;
5335 switch (kUseFastCapture) {
5336 case FastCapture_Never:
5337 initFastCapture = false;
5338 break;
5339 case FastCapture_Always:
5340 initFastCapture = true;
5341 break;
5342 case FastCapture_Static:
5343 uint32_t primaryOutputSampleRate;
5344 {
5345 AutoMutex _l(audioFlinger->mHardwareLock);
5346 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5347 }
5348 initFastCapture =
5349 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005350 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005351 (mSampleRate == primaryOutputSampleRate)) ||
5352 // or primary output sample rate is unknown, and capture sample rate is reasonable
5353 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005354 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005355 // and the buffer size is < 12 ms
5356 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005357 break;
5358 // case FastCapture_Dynamic:
5359 }
5360
5361 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005362 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005363 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005364 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005365 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5366 void *pipeBuffer;
5367 const sp<MemoryDealer> roHeap(readOnlyHeap());
5368 sp<IMemory> pipeMemory;
5369 if ((roHeap == 0) ||
5370 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5371 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5372 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5373 goto failed;
5374 }
5375 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5376 memset(pipeBuffer, 0, pipeSize);
5377 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5378 const NBAIO_Format offers[1] = {format};
5379 size_t numCounterOffers = 0;
5380 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5381 ALOG_ASSERT(index == 0);
5382 mPipeSink = pipe;
5383 PipeReader *pipeReader = new PipeReader(*pipe);
5384 numCounterOffers = 0;
5385 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5386 ALOG_ASSERT(index == 0);
5387 mPipeSource = pipeReader;
5388 mPipeFramesP2 = pipeFramesP2;
5389 mPipeMemory = pipeMemory;
5390
5391 // create fast capture
5392 mFastCapture = new FastCapture();
5393 FastCaptureStateQueue *sq = mFastCapture->sq();
5394#ifdef STATE_QUEUE_DUMP
5395 // FIXME
5396#endif
5397 FastCaptureState *state = sq->begin();
5398 state->mCblk = NULL;
5399 state->mInputSource = mInputSource.get();
5400 state->mInputSourceGen++;
5401 state->mPipeSink = pipe;
5402 state->mPipeSinkGen++;
5403 state->mFrameCount = mFrameCount;
5404 state->mCommand = FastCaptureState::COLD_IDLE;
5405 // already done in constructor initialization list
5406 //mFastCaptureFutex = 0;
5407 state->mColdFutexAddr = &mFastCaptureFutex;
5408 state->mColdGen++;
5409 state->mDumpState = &mFastCaptureDumpState;
5410#ifdef TEE_SINK
5411 // FIXME
5412#endif
5413 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5414 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5415 sq->end();
5416 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5417
5418 // start the fast capture
5419 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5420 pid_t tid = mFastCapture->getTid();
5421 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5422 if (err != 0) {
5423 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5424 kPriorityFastCapture, getpid_cached, tid, err);
5425 }
5426
5427#ifdef AUDIO_WATCHDOG
5428 // FIXME
5429#endif
5430
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005431 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005432 }
5433failed: ;
5434
5435 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005436}
5437
Eric Laurent81784c32012-11-19 14:55:58 -08005438AudioFlinger::RecordThread::~RecordThread()
5439{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005440 if (mFastCapture != 0) {
5441 FastCaptureStateQueue *sq = mFastCapture->sq();
5442 FastCaptureState *state = sq->begin();
5443 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5444 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5445 if (old == -1) {
5446 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5447 }
5448 }
5449 state->mCommand = FastCaptureState::EXIT;
5450 sq->end();
5451 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5452 mFastCapture->join();
5453 mFastCapture.clear();
5454 }
5455 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005456 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005457 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005458}
5459
5460void AudioFlinger::RecordThread::onFirstRef()
5461{
Glenn Kastend7dca052015-03-05 16:05:54 -08005462 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005463}
5464
Eric Laurent81784c32012-11-19 14:55:58 -08005465bool AudioFlinger::RecordThread::threadLoop()
5466{
Eric Laurent81784c32012-11-19 14:55:58 -08005467 nsecs_t lastWarning = 0;
5468
5469 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005470
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005471reacquire_wakelock:
5472 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005473 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005474 {
5475 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005476 size_t size = mActiveTracks.size();
5477 activeTracksGen = mActiveTracksGen;
5478 if (size > 0) {
5479 // FIXME an arbitrary choice
5480 activeTrack = mActiveTracks[0];
5481 acquireWakeLock_l(activeTrack->uid());
5482 if (size > 1) {
5483 SortedVector<int> tmp;
5484 for (size_t i = 0; i < size; i++) {
5485 tmp.add(mActiveTracks[i]->uid());
5486 }
5487 updateWakeLockUids_l(tmp);
5488 }
5489 } else {
5490 acquireWakeLock_l(-1);
5491 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005492 }
5493
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005494 // used to request a deferred sleep, to be executed later while mutex is unlocked
5495 uint32_t sleepUs = 0;
5496
5497 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005498 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005499 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005500
Glenn Kasten5edadd42013-08-14 16:30:49 -07005501 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005502 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005503 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005504 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005505 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005506 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005507 }
5508
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005509 // activeTracks accumulates a copy of a subset of mActiveTracks
5510 Vector< sp<RecordTrack> > activeTracks;
5511
Glenn Kasten735f45f2014-08-18 15:51:59 -07005512 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005513 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005514
Glenn Kasten735f45f2014-08-18 15:51:59 -07005515 // reference to a fast track which is about to be removed
5516 sp<RecordTrack> fastTrackToRemove;
5517
Eric Laurent81784c32012-11-19 14:55:58 -08005518 { // scope for mLock
5519 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005520
Eric Laurent021cf962014-05-13 10:18:14 -07005521 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005522
Eric Laurent000a4192014-01-29 15:17:32 -08005523 // check exitPending here because checkForNewParameters_l() and
5524 // checkForNewParameters_l() can temporarily release mLock
5525 if (exitPending()) {
5526 break;
5527 }
5528
Glenn Kasten2b806402013-11-20 16:37:38 -08005529 // if no active track(s), then standby and release wakelock
5530 size_t size = mActiveTracks.size();
5531 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005532 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005533 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005534 releaseWakeLock_l();
5535 ALOGV("RecordThread: loop stopping");
5536 // go to sleep
5537 mWaitWorkCV.wait(mLock);
5538 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005539 goto reacquire_wakelock;
5540 }
5541
Glenn Kasten2b806402013-11-20 16:37:38 -08005542 if (mActiveTracksGen != activeTracksGen) {
5543 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005544 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005545 for (size_t i = 0; i < size; i++) {
5546 tmp.add(mActiveTracks[i]->uid());
5547 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005548 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005549 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005550
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005551 bool doBroadcast = false;
5552 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005553
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005554 activeTrack = mActiveTracks[i];
5555 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005556 if (activeTrack->isFastTrack()) {
5557 ALOG_ASSERT(fastTrackToRemove == 0);
5558 fastTrackToRemove = activeTrack;
5559 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005560 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005561 mActiveTracks.remove(activeTrack);
5562 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005563 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005564 continue;
5565 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005566
5567 TrackBase::track_state activeTrackState = activeTrack->mState;
5568 switch (activeTrackState) {
5569
5570 case TrackBase::PAUSING:
5571 mActiveTracks.remove(activeTrack);
5572 mActiveTracksGen++;
5573 doBroadcast = true;
5574 size--;
5575 continue;
5576
5577 case TrackBase::STARTING_1:
5578 sleepUs = 10000;
5579 i++;
5580 continue;
5581
5582 case TrackBase::STARTING_2:
5583 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005584 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005585 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005586 break;
5587
5588 case TrackBase::ACTIVE:
5589 break;
5590
5591 case TrackBase::IDLE:
5592 i++;
5593 continue;
5594
5595 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005596 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005597 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005598
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005599 activeTracks.add(activeTrack);
5600 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005601
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005602 if (activeTrack->isFastTrack()) {
5603 ALOG_ASSERT(!mFastTrackAvail);
5604 ALOG_ASSERT(fastTrack == 0);
5605 fastTrack = activeTrack;
5606 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005607 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005608 if (doBroadcast) {
5609 mStartStopCond.broadcast();
5610 }
5611
5612 // sleep if there are no active tracks to process
5613 if (activeTracks.size() == 0) {
5614 if (sleepUs == 0) {
5615 sleepUs = kRecordThreadSleepUs;
5616 }
5617 continue;
5618 }
5619 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005620
Eric Laurent81784c32012-11-19 14:55:58 -08005621 lockEffectChains_l(effectChains);
5622 }
5623
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005624 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005625
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005626 size_t size = effectChains.size();
5627 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005628 // thread mutex is not locked, but effect chain is locked
5629 effectChains[i]->process_l();
5630 }
5631
Glenn Kasten735f45f2014-08-18 15:51:59 -07005632 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005633 if (mFastCapture != 0) {
5634 FastCaptureStateQueue *sq = mFastCapture->sq();
5635 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005636 bool didModify = false;
5637 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005638 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5639 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5640 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5641 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5642 if (old == -1) {
5643 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5644 }
5645 }
5646 state->mCommand = FastCaptureState::READ_WRITE;
5647#if 0 // FIXME
5648 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005649 FastThreadDumpState::kSamplingNforLowRamDevice :
5650 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005651#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005652 didModify = true;
5653 }
5654 audio_track_cblk_t *cblkOld = state->mCblk;
5655 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5656 if (cblkNew != cblkOld) {
5657 state->mCblk = cblkNew;
5658 // block until acked if removing a fast track
5659 if (cblkOld != NULL) {
5660 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5661 }
5662 didModify = true;
5663 }
5664 sq->end(didModify);
5665 if (didModify) {
5666 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005667#if 0
5668 if (kUseFastCapture == FastCapture_Dynamic) {
5669 mNormalSource = mPipeSource;
5670 }
5671#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005672 }
5673 }
5674
Glenn Kasten735f45f2014-08-18 15:51:59 -07005675 // now run the fast track destructor with thread mutex unlocked
5676 fastTrackToRemove.clear();
5677
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005678 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5679 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5680 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5681 // If destination is non-contiguous, first read past the nominal end of buffer, then
5682 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005683
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005684 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005685 ssize_t framesRead;
5686
5687 // If an NBAIO source is present, use it to read the normal capture's data
5688 if (mPipeSource != 0) {
5689 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005690 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005691 framesToRead, AudioBufferProvider::kInvalidPTS);
5692 if (framesRead == 0) {
5693 // since pipe is non-blocking, simulate blocking input
5694 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5695 }
5696 // otherwise use the HAL / AudioStreamIn directly
5697 } else {
5698 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005699 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005700 if (bytesRead < 0) {
5701 framesRead = bytesRead;
5702 } else {
5703 framesRead = bytesRead / mFrameSize;
5704 }
5705 }
5706
5707 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5708 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005709 // Force input into standby so that it tries to recover at next read attempt
5710 inputStandBy();
5711 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005712 }
5713 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005714 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005715 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005716 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005717
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005718 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005719 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005720 }
5721 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005722 {
5723 size_t part1 = mRsmpInFramesP2 - rear;
5724 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005725 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005726 (framesRead - part1) * mFrameSize);
5727 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005728 }
5729 rear = mRsmpInRear += framesRead;
5730
5731 size = activeTracks.size();
5732 // loop over each active track
5733 for (size_t i = 0; i < size; i++) {
5734 activeTrack = activeTracks[i];
5735
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005736 // skip fast tracks, as those are handled directly by FastCapture
5737 if (activeTrack->isFastTrack()) {
5738 continue;
5739 }
5740
Andy Hung73c02e42015-03-29 01:13:58 -07005741 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005742 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5743
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005744 enum {
5745 OVERRUN_UNKNOWN,
5746 OVERRUN_TRUE,
5747 OVERRUN_FALSE
5748 } overrun = OVERRUN_UNKNOWN;
5749
5750 // loop over getNextBuffer to handle circular sink
5751 for (;;) {
5752
5753 activeTrack->mSink.frameCount = ~0;
5754 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5755 size_t framesOut = activeTrack->mSink.frameCount;
5756 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5757
Andy Hung73c02e42015-03-29 01:13:58 -07005758 // check available frames and handle overrun conditions
5759 // if the record track isn't draining fast enough.
5760 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005761 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005762 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5763 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005764 overrun = OVERRUN_TRUE;
5765 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005766 if (framesOut == 0 || framesIn == 0) {
5767 break;
5768 }
5769
Andy Hung6770c6f2015-04-07 13:43:36 -07005770 // Don't allow framesOut to be larger than what is possible with resampling
5771 // from framesIn.
5772 // This isn't strictly necessary but helps limit buffer resizing in
5773 // RecordBufferConverter. TODO: remove when no longer needed.
5774 framesOut = min(framesOut,
5775 destinationFramesPossible(
5776 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005777 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5778 framesOut = activeTrack->mRecordBufferConverter->convert(
5779 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005780
5781 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5782 overrun = OVERRUN_FALSE;
5783 }
5784
5785 if (activeTrack->mFramesToDrop == 0) {
5786 if (framesOut > 0) {
5787 activeTrack->mSink.frameCount = framesOut;
5788 activeTrack->releaseBuffer(&activeTrack->mSink);
5789 }
5790 } else {
5791 // FIXME could do a partial drop of framesOut
5792 if (activeTrack->mFramesToDrop > 0) {
5793 activeTrack->mFramesToDrop -= framesOut;
5794 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005795 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005796 }
5797 } else {
5798 activeTrack->mFramesToDrop += framesOut;
5799 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5800 activeTrack->mSyncStartEvent->isCancelled()) {
5801 ALOGW("Synced record %s, session %d, trigger session %d",
5802 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5803 activeTrack->sessionId(),
5804 (activeTrack->mSyncStartEvent != 0) ?
5805 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005806 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 }
5808 }
5809 }
5810
5811 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005812 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005813 }
5814 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005815
5816 switch (overrun) {
5817 case OVERRUN_TRUE:
5818 // client isn't retrieving buffers fast enough
5819 if (!activeTrack->setOverflow()) {
5820 nsecs_t now = systemTime();
5821 // FIXME should lastWarning per track?
5822 if ((now - lastWarning) > kWarningThrottleNs) {
5823 ALOGW("RecordThread: buffer overflow");
5824 lastWarning = now;
5825 }
5826 }
5827 break;
5828 case OVERRUN_FALSE:
5829 activeTrack->clearOverflow();
5830 break;
5831 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005832 break;
5833 }
5834
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005835 }
5836
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005837unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005838 // enable changes in effect chain
5839 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005840 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005841 }
5842
Glenn Kasten93e471f2013-08-19 08:40:07 -07005843 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005844
5845 {
5846 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005847 for (size_t i = 0; i < mTracks.size(); i++) {
5848 sp<RecordTrack> track = mTracks[i];
5849 track->invalidate();
5850 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005851 mActiveTracks.clear();
5852 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005853 mStartStopCond.broadcast();
5854 }
5855
5856 releaseWakeLock();
5857
5858 ALOGV("RecordThread %p exiting", this);
5859 return false;
5860}
5861
Glenn Kasten93e471f2013-08-19 08:40:07 -07005862void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005863{
5864 if (!mStandby) {
5865 inputStandBy();
5866 mStandby = true;
5867 }
5868}
5869
5870void AudioFlinger::RecordThread::inputStandBy()
5871{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005872 // Idle the fast capture if it's currently running
5873 if (mFastCapture != 0) {
5874 FastCaptureStateQueue *sq = mFastCapture->sq();
5875 FastCaptureState *state = sq->begin();
5876 if (!(state->mCommand & FastCaptureState::IDLE)) {
5877 state->mCommand = FastCaptureState::COLD_IDLE;
5878 state->mColdFutexAddr = &mFastCaptureFutex;
5879 state->mColdGen++;
5880 mFastCaptureFutex = 0;
5881 sq->end();
5882 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5883 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5884#if 0
5885 if (kUseFastCapture == FastCapture_Dynamic) {
5886 // FIXME
5887 }
5888#endif
5889#ifdef AUDIO_WATCHDOG
5890 // FIXME
5891#endif
5892 } else {
5893 sq->end(false /*didModify*/);
5894 }
5895 }
Eric Laurent81784c32012-11-19 14:55:58 -08005896 mInput->stream->common.standby(&mInput->stream->common);
5897}
5898
Glenn Kasten05997e22014-03-13 15:08:33 -07005899// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005900sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005901 const sp<AudioFlinger::Client>& client,
5902 uint32_t sampleRate,
5903 audio_format_t format,
5904 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005905 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005906 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005907 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005908 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005909 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005910 pid_t tid,
5911 status_t *status)
5912{
Glenn Kasten74935e42013-12-19 08:56:45 -08005913 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005914 sp<RecordTrack> track;
5915 status_t lStatus;
5916
Glenn Kasten90e58b12013-07-31 16:16:02 -07005917 // client expresses a preference for FAST, but we get the final say
5918 if (*flags & IAudioFlinger::TRACK_FAST) {
5919 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005920 // we formerly checked for a callback handler (non-0 tid),
5921 // but that is no longer required for TRANSFER_OBTAIN mode
5922 //
Glenn Kasten74105912014-07-03 12:28:53 -07005923 // frame count is not specified, or is exactly the pipe depth
5924 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005925 // PCM data
5926 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005927 // native format
5928 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 // native channel mask
5930 (channelMask == mChannelMask) &&
5931 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005932 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005933 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005934 hasFastCapture() &&
5935 // there are sufficient fast track slots available
5936 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005937 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005938 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005939 frameCount, mFrameCount);
5940 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005941 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5942 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005943 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005944 frameCount, mFrameCount, mPipeFramesP2,
5945 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5946 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005947 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005948 }
5949 }
5950
5951 // compute track buffer size in frames, and suggest the notification frame count
5952 if (*flags & IAudioFlinger::TRACK_FAST) {
5953 // fast track: frame count is exactly the pipe depth
5954 frameCount = mPipeFramesP2;
5955 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5956 *notificationFrames = mFrameCount;
5957 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005958 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5959 // or 20 ms if there is a fast capture
5960 // TODO This could be a roundupRatio inline, and const
5961 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5962 * sampleRate + mSampleRate - 1) / mSampleRate;
5963 // minimum number of notification periods is at least kMinNotifications,
5964 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5965 static const size_t kMinNotifications = 3;
5966 static const uint32_t kMinMs = 30;
5967 // TODO This could be a roundupRatio inline
5968 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5969 // TODO This could be a roundupRatio inline
5970 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5971 maxNotificationFrames;
5972 const size_t minFrameCount = maxNotificationFrames *
5973 max(kMinNotifications, minNotificationsByMs);
5974 frameCount = max(frameCount, minFrameCount);
5975 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5976 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005977 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005978 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005979 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005980
Glenn Kasten15e57982013-09-24 11:52:37 -07005981 lStatus = initCheck();
5982 if (lStatus != NO_ERROR) {
5983 ALOGE("createRecordTrack_l() audio driver not initialized");
5984 goto Exit;
5985 }
Eric Laurent81784c32012-11-19 14:55:58 -08005986
5987 { // scope for mLock
5988 Mutex::Autolock _l(mLock);
5989
5990 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005991 format, channelMask, frameCount, NULL, sessionId, uid,
5992 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005993
Glenn Kasten03003332013-08-06 15:40:54 -07005994 lStatus = track->initCheck();
5995 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005996 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005997 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005998 goto Exit;
5999 }
6000 mTracks.add(track);
6001
6002 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6003 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6004 mAudioFlinger->btNrecIsOff();
6005 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6006 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006007
6008 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6009 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6010 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6011 // so ask activity manager to do this on our behalf
6012 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6013 }
Eric Laurent81784c32012-11-19 14:55:58 -08006014 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006015
Eric Laurent81784c32012-11-19 14:55:58 -08006016 lStatus = NO_ERROR;
6017
6018Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006019 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006020 return track;
6021}
6022
6023status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6024 AudioSystem::sync_event_t event,
6025 int triggerSession)
6026{
6027 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6028 sp<ThreadBase> strongMe = this;
6029 status_t status = NO_ERROR;
6030
6031 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006032 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006033 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006035 triggerSession,
6036 recordTrack->sessionId(),
6037 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006039 // Sync event can be cancelled by the trigger session if the track is not in a
6040 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006041 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006042 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006043 } else {
6044 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006046 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006047 }
6048 }
6049
6050 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006051 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006052 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006053 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6054 if (recordTrack->mState == TrackBase::PAUSING) {
6055 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006056 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006057 } else {
6058 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006059 }
6060 return status;
6061 }
6062
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006063 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6064 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6065 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006066 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006067 mActiveTracks.add(recordTrack);
6068 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006069 status_t status = NO_ERROR;
6070 if (recordTrack->isExternalTrack()) {
6071 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006072 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006073 mLock.lock();
6074 // FIXME should verify that recordTrack is still in mActiveTracks
6075 if (status != NO_ERROR) {
6076 mActiveTracks.remove(recordTrack);
6077 mActiveTracksGen++;
6078 recordTrack->clearSyncStartEvent();
6079 ALOGV("RecordThread::start error %d", status);
6080 return status;
6081 }
Eric Laurent81784c32012-11-19 14:55:58 -08006082 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006083 // Catch up with current buffer indices if thread is already running.
6084 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6085 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6086 // see previously buffered data before it called start(), but with greater risk of overrun.
6087
Andy Hung73c02e42015-03-29 01:13:58 -07006088 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006089 // clear any converter state as new data will be discontinuous
6090 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006091 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006092 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006093 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006094 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006095 ALOGV("Record failed to start");
6096 status = BAD_VALUE;
6097 goto startError;
6098 }
Eric Laurent81784c32012-11-19 14:55:58 -08006099 return status;
6100 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006101
Eric Laurent81784c32012-11-19 14:55:58 -08006102startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006103 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006104 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006105 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006106 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006107 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006108 return status;
6109}
6110
Eric Laurent81784c32012-11-19 14:55:58 -08006111void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6112{
6113 sp<SyncEvent> strongEvent = event.promote();
6114
6115 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006116 sp<RefBase> ptr = strongEvent->cookie().promote();
6117 if (ptr != 0) {
6118 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6119 recordTrack->handleSyncStartEvent(strongEvent);
6120 }
Eric Laurent81784c32012-11-19 14:55:58 -08006121 }
6122}
6123
Glenn Kastena8356f62013-07-25 14:37:52 -07006124bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006125 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006126 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006127 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006128 return false;
6129 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006130 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006131 recordTrack->mState = TrackBase::PAUSING;
6132 // do not wait for mStartStopCond if exiting
6133 if (exitPending()) {
6134 return true;
6135 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006136 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006137 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006138 // if we have been restarted, recordTrack is in mActiveTracks here
6139 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006140 ALOGV("Record stopped OK");
6141 return true;
6142 }
6143 return false;
6144}
6145
Glenn Kasten0f11b512014-01-31 16:18:54 -08006146bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006147{
6148 return false;
6149}
6150
Glenn Kasten0f11b512014-01-31 16:18:54 -08006151status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006152{
6153#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6154 if (!isValidSyncEvent(event)) {
6155 return BAD_VALUE;
6156 }
6157
6158 int eventSession = event->triggerSession();
6159 status_t ret = NAME_NOT_FOUND;
6160
6161 Mutex::Autolock _l(mLock);
6162
6163 for (size_t i = 0; i < mTracks.size(); i++) {
6164 sp<RecordTrack> track = mTracks[i];
6165 if (eventSession == track->sessionId()) {
6166 (void) track->setSyncEvent(event);
6167 ret = NO_ERROR;
6168 }
6169 }
6170 return ret;
6171#else
6172 return BAD_VALUE;
6173#endif
6174}
6175
6176// destroyTrack_l() must be called with ThreadBase::mLock held
6177void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6178{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006179 track->terminate();
6180 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006181 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006182 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006183 removeTrack_l(track);
6184 }
6185}
6186
6187void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6188{
6189 mTracks.remove(track);
6190 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006191 if (track->isFastTrack()) {
6192 ALOG_ASSERT(!mFastTrackAvail);
6193 mFastTrackAvail = true;
6194 }
Eric Laurent81784c32012-11-19 14:55:58 -08006195}
6196
6197void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6198{
6199 dumpInternals(fd, args);
6200 dumpTracks(fd, args);
6201 dumpEffectChains(fd, args);
6202}
6203
6204void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6205{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006206 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006207
Glenn Kasten44182c22015-03-05 17:12:23 -08006208 dumpBase(fd, args);
6209
6210 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006211 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006212 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006213 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006214 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006215
6216 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6217 const FastCaptureDumpState copy(mFastCaptureDumpState);
6218 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006219}
6220
Glenn Kasten0f11b512014-01-31 16:18:54 -08006221void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006222{
6223 const size_t SIZE = 256;
6224 char buffer[SIZE];
6225 String8 result;
6226
Marco Nelissenb2208842014-02-07 14:00:50 -08006227 size_t numtracks = mTracks.size();
6228 size_t numactive = mActiveTracks.size();
6229 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006230 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006231 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006232 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006233 RecordTrack::appendDumpHeader(result);
6234 for (size_t i = 0; i < numtracks ; ++i) {
6235 sp<RecordTrack> track = mTracks[i];
6236 if (track != 0) {
6237 bool active = mActiveTracks.indexOf(track) >= 0;
6238 if (active) {
6239 numactiveseen++;
6240 }
6241 track->dump(buffer, SIZE, active);
6242 result.append(buffer);
6243 }
Eric Laurent81784c32012-11-19 14:55:58 -08006244 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006245 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006246 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006247 }
6248
Marco Nelissenb2208842014-02-07 14:00:50 -08006249 if (numactiveseen != numactive) {
6250 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6251 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006252 result.append(buffer);
6253 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006254 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006255 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006256 if (mTracks.indexOf(track) < 0) {
6257 track->dump(buffer, SIZE, true);
6258 result.append(buffer);
6259 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006260 }
Eric Laurent81784c32012-11-19 14:55:58 -08006261
6262 }
6263 write(fd, result.string(), result.size());
6264}
6265
Andy Hung73c02e42015-03-29 01:13:58 -07006266
6267void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6268{
6269 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6270 RecordThread *recordThread = (RecordThread *) threadBase.get();
6271 mRsmpInFront = recordThread->mRsmpInRear;
6272 mRsmpInUnrel = 0;
6273}
6274
6275void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6276 size_t *framesAvailable, bool *hasOverrun)
6277{
6278 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6279 RecordThread *recordThread = (RecordThread *) threadBase.get();
6280 const int32_t rear = recordThread->mRsmpInRear;
6281 const int32_t front = mRsmpInFront;
6282 const ssize_t filled = rear - front;
6283
6284 size_t framesIn;
6285 bool overrun = false;
6286 if (filled < 0) {
6287 // should not happen, but treat like a massive overrun and re-sync
6288 framesIn = 0;
6289 mRsmpInFront = rear;
6290 overrun = true;
6291 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6292 framesIn = (size_t) filled;
6293 } else {
6294 // client is not keeping up with server, but give it latest data
6295 framesIn = recordThread->mRsmpInFrames;
6296 mRsmpInFront = /* front = */ rear - framesIn;
6297 overrun = true;
6298 }
6299 if (framesAvailable != NULL) {
6300 *framesAvailable = framesIn;
6301 }
6302 if (hasOverrun != NULL) {
6303 *hasOverrun = overrun;
6304 }
6305}
6306
Eric Laurent81784c32012-11-19 14:55:58 -08006307// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006308status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6309 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006310{
Andy Hung73c02e42015-03-29 01:13:58 -07006311 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006312 if (threadBase == 0) {
6313 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006314 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006315 return NOT_ENOUGH_DATA;
6316 }
6317 RecordThread *recordThread = (RecordThread *) threadBase.get();
6318 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006319 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006320 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006321 // FIXME should not be P2 (don't want to increase latency)
6322 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006323 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006324 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006325 front &= recordThread->mRsmpInFramesP2 - 1;
6326 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006327 if (part1 > (size_t) filled) {
6328 part1 = filled;
6329 }
6330 size_t ask = buffer->frameCount;
6331 ALOG_ASSERT(ask > 0);
6332 if (part1 > ask) {
6333 part1 = ask;
6334 }
6335 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006336 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006337 buffer->raw = NULL;
6338 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006339 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006340 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006341 }
6342
Andy Hung57446612015-04-19 23:56:46 -07006343 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006344 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006345 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006346 return NO_ERROR;
6347}
6348
6349// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006350void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6351 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006352{
Glenn Kasten85948432013-08-19 12:09:05 -07006353 size_t stepCount = buffer->frameCount;
6354 if (stepCount == 0) {
6355 return;
6356 }
Andy Hung73c02e42015-03-29 01:13:58 -07006357 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6358 mRsmpInUnrel -= stepCount;
6359 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006360 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006361 buffer->frameCount = 0;
6362}
6363
Andy Hung97a893e2015-03-29 01:03:07 -07006364AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6365 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6366 uint32_t srcSampleRate,
6367 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6368 uint32_t dstSampleRate) :
6369 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6370 // mSrcFormat
6371 // mSrcSampleRate
6372 // mDstChannelMask
6373 // mDstFormat
6374 // mDstSampleRate
6375 // mSrcChannelCount
6376 // mDstChannelCount
6377 // mDstFrameSize
6378 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006379 mResampler(NULL),
6380 mIsLegacyDownmix(false),
6381 mIsLegacyUpmix(false),
6382 mRequiresFloat(false),
6383 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006384{
6385 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6386 dstChannelMask, dstFormat, dstSampleRate);
6387}
6388
6389AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6390 free(mBuf);
6391 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006392 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006393}
6394
6395size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6396 AudioBufferProvider *provider, size_t frames)
6397{
Andy Hungd330ee42015-04-20 13:23:41 -07006398 if (mInputConverterProvider != NULL) {
6399 mInputConverterProvider->setBufferProvider(provider);
6400 provider = mInputConverterProvider;
6401 }
6402
6403 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006404 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6405 mSrcSampleRate, mSrcFormat, mDstFormat);
6406
6407 AudioBufferProvider::Buffer buffer;
6408 for (size_t i = frames; i > 0; ) {
6409 buffer.frameCount = i;
6410 status_t status = provider->getNextBuffer(&buffer, 0);
6411 if (status != OK || buffer.frameCount == 0) {
6412 frames -= i; // cannot fill request.
6413 break;
6414 }
Andy Hungd330ee42015-04-20 13:23:41 -07006415 // format convert to destination buffer
6416 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006417
6418 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6419 i -= buffer.frameCount;
6420 provider->releaseBuffer(&buffer);
6421 }
6422 } else {
6423 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6424 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6425
Andy Hungd330ee42015-04-20 13:23:41 -07006426 // reallocate buffer if needed
6427 if (mBufFrameSize != 0 && mBufFrames < frames) {
6428 free(mBuf);
6429 mBufFrames = frames;
6430 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6431 }
Andy Hung97a893e2015-03-29 01:03:07 -07006432 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006433 memset(mBuf, 0, frames * mBufFrameSize);
6434 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6435 // format convert to destination buffer
6436 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006437 }
6438 return frames;
6439}
6440
6441status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6442 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6443 uint32_t srcSampleRate,
6444 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6445 uint32_t dstSampleRate)
6446{
6447 // quick evaluation if there is any change.
6448 if (mSrcFormat == srcFormat
6449 && mSrcChannelMask == srcChannelMask
6450 && mSrcSampleRate == srcSampleRate
6451 && mDstFormat == dstFormat
6452 && mDstChannelMask == dstChannelMask
6453 && mDstSampleRate == dstSampleRate) {
6454 return NO_ERROR;
6455 }
6456
Andy Hungdb4c0312015-05-06 08:46:52 -07006457 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6458 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6459 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006460 const bool valid =
6461 audio_is_input_channel(srcChannelMask)
6462 && audio_is_input_channel(dstChannelMask)
6463 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6464 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6465 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6466 ; // no upsampling checks for now
6467 if (!valid) {
6468 return BAD_VALUE;
6469 }
6470
6471 mSrcFormat = srcFormat;
6472 mSrcChannelMask = srcChannelMask;
6473 mSrcSampleRate = srcSampleRate;
6474 mDstFormat = dstFormat;
6475 mDstChannelMask = dstChannelMask;
6476 mDstSampleRate = dstSampleRate;
6477
6478 // compute derived parameters
6479 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6480 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6481 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6482
Andy Hungd330ee42015-04-20 13:23:41 -07006483 // do we need to resample?
6484 delete mResampler;
6485 mResampler = NULL;
6486 if (mSrcSampleRate != mDstSampleRate) {
6487 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6488 mSrcChannelCount, mDstSampleRate);
6489 mResampler->setSampleRate(mSrcSampleRate);
6490 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6491 }
6492
6493 // are we running legacy channel conversion modes?
6494 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6495 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6496 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6497 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6498 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6499 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6500
6501 // do we need to process in float?
6502 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6503
6504 // do we need a staging buffer to convert for destination (we can still optimize this)?
6505 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6506 if (mResampler != NULL) {
6507 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6508 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6509 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6510 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6511 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006512 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6513 } else {
6514 mBufFrameSize = 0;
6515 }
6516 mBufFrames = 0; // force the buffer to be resized.
6517
Andy Hungd330ee42015-04-20 13:23:41 -07006518 // do we need an input converter buffer provider to give us float?
6519 delete mInputConverterProvider;
6520 mInputConverterProvider = NULL;
6521 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6522 mInputConverterProvider = new ReformatBufferProvider(
6523 audio_channel_count_from_in_mask(mSrcChannelMask),
6524 mSrcFormat,
6525 AUDIO_FORMAT_PCM_FLOAT,
6526 256 /* provider buffer frame count */);
6527 }
6528
6529 // do we need a remixer to do channel mask conversion
6530 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6531 (void) memcpy_by_index_array_initialization_from_channel_mask(
6532 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006533 }
6534 return NO_ERROR;
6535}
6536
Andy Hungd330ee42015-04-20 13:23:41 -07006537void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6538 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006539{
Andy Hungd330ee42015-04-20 13:23:41 -07006540 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006541 if (mBufFrameSize != 0 && mBufFrames < frames) {
6542 free(mBuf);
6543 mBufFrames = frames;
6544 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6545 }
Andy Hungd330ee42015-04-20 13:23:41 -07006546 // do we need to do legacy upmix and downmix?
6547 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006548 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006549 if (mIsLegacyUpmix) {
6550 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6551 (const float *)src, frames);
6552 } else /*mIsLegacyDownmix */ {
6553 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6554 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006555 }
Andy Hungd330ee42015-04-20 13:23:41 -07006556 if (mBuf != NULL) {
6557 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6558 frames * mDstChannelCount);
6559 }
6560 return;
6561 }
6562 // do we need to do channel mask conversion?
6563 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006564 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006565 memcpy_by_index_array(dstBuf, mDstChannelCount,
6566 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6567 if (dstBuf == dst) {
6568 return; // format is the same
6569 }
6570 }
6571 // convert to destination buffer
6572 const void *convertBuf = mBuf != NULL ? mBuf : src;
6573 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6574 frames * mDstChannelCount);
6575}
6576
6577void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6578 void *dst, /*not-a-const*/ void *src, size_t frames)
6579{
6580 // src buffer format is ALWAYS float when entering this routine
6581 if (mIsLegacyUpmix) {
6582 ; // mono to stereo already handled by resampler
6583 } else if (mIsLegacyDownmix
6584 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6585 // the resampler outputs stereo for mono input channel (a feature?)
6586 // must convert to mono
6587 downmix_to_mono_float_from_stereo_float((float *)src,
6588 (const float *)src, frames);
6589 } else if (mSrcChannelMask != mDstChannelMask) {
6590 // convert to mono channel again for channel mask conversion (could be skipped
6591 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006592 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006593 downmix_to_mono_float_from_stereo_float((float *)src,
6594 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006595 }
Andy Hungd330ee42015-04-20 13:23:41 -07006596 // convert to destination format (in place, OK as float is larger than other types)
6597 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6598 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6599 frames * mSrcChannelCount);
6600 }
6601 // channel convert and save to dst
6602 memcpy_by_index_array(dst, mDstChannelCount,
6603 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6604 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006605 }
Andy Hungd330ee42015-04-20 13:23:41 -07006606 // convert to destination format and save to dst
6607 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6608 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006609}
6610
Eric Laurent10351942014-05-08 18:49:52 -07006611bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6612 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006613{
6614 bool reconfig = false;
6615
Eric Laurent10351942014-05-08 18:49:52 -07006616 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006617
Eric Laurent10351942014-05-08 18:49:52 -07006618 audio_format_t reqFormat = mFormat;
6619 uint32_t samplingRate = mSampleRate;
6620 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006621 // possible that we are > 2 channels, use channel index mask
6622 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6623 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6624 }
Eric Laurent10351942014-05-08 18:49:52 -07006625
6626 AudioParameter param = AudioParameter(keyValuePair);
6627 int value;
6628 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6629 // channel count change can be requested. Do we mandate the first client defines the
6630 // HAL sampling rate and channel count or do we allow changes on the fly?
6631 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6632 samplingRate = value;
6633 reconfig = true;
6634 }
6635 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006636 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006637 status = BAD_VALUE;
6638 } else {
6639 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006640 reconfig = true;
6641 }
Eric Laurent10351942014-05-08 18:49:52 -07006642 }
6643 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6644 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006645 if (!audio_is_input_channel(mask) ||
6646 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006647 status = BAD_VALUE;
6648 } else {
6649 channelMask = mask;
6650 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006651 }
Eric Laurent10351942014-05-08 18:49:52 -07006652 }
6653 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6654 // do not accept frame count changes if tracks are open as the track buffer
6655 // size depends on frame count and correct behavior would not be guaranteed
6656 // if frame count is changed after track creation
6657 if (mActiveTracks.size() > 0) {
6658 status = INVALID_OPERATION;
6659 } else {
6660 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006661 }
Eric Laurent10351942014-05-08 18:49:52 -07006662 }
6663 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6664 // forward device change to effects that have requested to be
6665 // aware of attached audio device.
6666 for (size_t i = 0; i < mEffectChains.size(); i++) {
6667 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006668 }
Eric Laurent81784c32012-11-19 14:55:58 -08006669
Eric Laurent10351942014-05-08 18:49:52 -07006670 // store input device and output device but do not forward output device to audio HAL.
6671 // Note that status is ignored by the caller for output device
6672 // (see AudioFlinger::setParameters()
6673 if (audio_is_output_devices(value)) {
6674 mOutDevice = value;
6675 status = BAD_VALUE;
6676 } else {
6677 mInDevice = value;
6678 // disable AEC and NS if the device is a BT SCO headset supporting those
6679 // pre processings
6680 if (mTracks.size() > 0) {
6681 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6682 mAudioFlinger->btNrecIsOff();
6683 for (size_t i = 0; i < mTracks.size(); i++) {
6684 sp<RecordTrack> track = mTracks[i];
6685 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6686 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006687 }
6688 }
6689 }
Eric Laurent10351942014-05-08 18:49:52 -07006690 }
6691 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6692 mAudioSource != (audio_source_t)value) {
6693 // forward device change to effects that have requested to be
6694 // aware of attached audio device.
6695 for (size_t i = 0; i < mEffectChains.size(); i++) {
6696 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006697 }
Eric Laurent10351942014-05-08 18:49:52 -07006698 mAudioSource = (audio_source_t)value;
6699 }
Glenn Kastene198c362013-08-13 09:13:36 -07006700
Eric Laurent10351942014-05-08 18:49:52 -07006701 if (status == NO_ERROR) {
6702 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6703 keyValuePair.string());
6704 if (status == INVALID_OPERATION) {
6705 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006706 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6707 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006708 }
6709 if (reconfig) {
6710 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006711 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6712 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006713 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006714 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006715 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006716 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006717 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006718 }
Eric Laurent10351942014-05-08 18:49:52 -07006719 if (status == NO_ERROR) {
6720 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006721 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006722 }
6723 }
Eric Laurent81784c32012-11-19 14:55:58 -08006724 }
Eric Laurent10351942014-05-08 18:49:52 -07006725
Eric Laurent81784c32012-11-19 14:55:58 -08006726 return reconfig;
6727}
6728
6729String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6730{
Eric Laurent81784c32012-11-19 14:55:58 -08006731 Mutex::Autolock _l(mLock);
6732 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006733 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006734 }
6735
Glenn Kastend8ea6992013-07-16 14:17:15 -07006736 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6737 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006738 free(s);
6739 return out_s8;
6740}
6741
Eric Laurent73e26b62015-04-27 16:55:58 -07006742void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6743 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6744
6745 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006746
6747 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006748 case AUDIO_INPUT_OPENED:
6749 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006750 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006751 desc->mChannelMask = mChannelMask;
6752 desc->mSamplingRate = mSampleRate;
6753 desc->mFormat = mFormat;
6754 desc->mFrameCount = mFrameCount;
6755 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006756 break;
6757
Eric Laurent73e26b62015-04-27 16:55:58 -07006758 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006759 default:
6760 break;
6761 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006762 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006763}
6764
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006765void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006766{
Eric Laurent81784c32012-11-19 14:55:58 -08006767 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6768 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006769 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006770 if (mChannelCount > FCC_8) {
6771 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6772 }
Andy Hung463be252014-07-10 16:56:07 -07006773 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6774 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006775 if (!audio_is_linear_pcm(mFormat)) {
6776 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006777 }
Eric Laurent665470b2014-07-03 16:37:08 -07006778 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006779 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6780 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006781 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006782 // 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 -07006783 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006784 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006785 // A larger value should allow more old data to be read after a track calls start(),
6786 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006787 //
6788 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006789 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006790 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006791 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006792
6793 // TODO optimize audio capture buffer sizes ...
6794 // Here we calculate the size of the sliding buffer used as a source
6795 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6796 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6797 // be better to have it derived from the pipe depth in the long term.
6798 // The current value is higher than necessary. However it should not add to latency.
6799
Glenn Kasten85948432013-08-19 12:09:05 -07006800 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006801 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006802
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006803 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6804 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006805}
6806
Glenn Kasten5f972c02014-01-13 09:59:31 -08006807uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006808{
6809 Mutex::Autolock _l(mLock);
6810 if (initCheck() != NO_ERROR) {
6811 return 0;
6812 }
6813
6814 return mInput->stream->get_input_frames_lost(mInput->stream);
6815}
6816
6817uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6818{
6819 Mutex::Autolock _l(mLock);
6820 uint32_t result = 0;
6821 if (getEffectChain_l(sessionId) != 0) {
6822 result = EFFECT_SESSION;
6823 }
6824
6825 for (size_t i = 0; i < mTracks.size(); ++i) {
6826 if (sessionId == mTracks[i]->sessionId()) {
6827 result |= TRACK_SESSION;
6828 break;
6829 }
6830 }
6831
6832 return result;
6833}
6834
6835KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6836{
6837 KeyedVector<int, bool> ids;
6838 Mutex::Autolock _l(mLock);
6839 for (size_t j = 0; j < mTracks.size(); ++j) {
6840 sp<RecordThread::RecordTrack> track = mTracks[j];
6841 int sessionId = track->sessionId();
6842 if (ids.indexOfKey(sessionId) < 0) {
6843 ids.add(sessionId, true);
6844 }
6845 }
6846 return ids;
6847}
6848
6849AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6850{
6851 Mutex::Autolock _l(mLock);
6852 AudioStreamIn *input = mInput;
6853 mInput = NULL;
6854 return input;
6855}
6856
6857// this method must always be called either with ThreadBase mLock held or inside the thread loop
6858audio_stream_t* AudioFlinger::RecordThread::stream() const
6859{
6860 if (mInput == NULL) {
6861 return NULL;
6862 }
6863 return &mInput->stream->common;
6864}
6865
6866status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6867{
6868 // only one chain per input thread
6869 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006870 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006871 return INVALID_OPERATION;
6872 }
6873 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006874 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006875 chain->setInBuffer(NULL);
6876 chain->setOutBuffer(NULL);
6877
6878 checkSuspendOnAddEffectChain_l(chain);
6879
Eric Laurent1b928682014-10-02 19:41:47 -07006880 // make sure enabled pre processing effects state is communicated to the HAL as we
6881 // just moved them to a new input stream.
6882 chain->syncHalEffectsState();
6883
Eric Laurent81784c32012-11-19 14:55:58 -08006884 mEffectChains.add(chain);
6885
6886 return NO_ERROR;
6887}
6888
6889size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6890{
6891 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6892 ALOGW_IF(mEffectChains.size() != 1,
6893 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6894 chain.get(), mEffectChains.size(), this);
6895 if (mEffectChains.size() == 1) {
6896 mEffectChains.removeAt(0);
6897 }
6898 return 0;
6899}
6900
Eric Laurent1c333e22014-05-20 10:48:17 -07006901status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6902 audio_patch_handle_t *handle)
6903{
6904 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006905
6906 // store new device and send to effects
6907 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07006908 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07006909 for (size_t i = 0; i < mEffectChains.size(); i++) {
6910 mEffectChains[i]->setDevice_l(mInDevice);
6911 }
6912
6913 // disable AEC and NS if the device is a BT SCO headset supporting those
6914 // pre processings
6915 if (mTracks.size() > 0) {
6916 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6917 mAudioFlinger->btNrecIsOff();
6918 for (size_t i = 0; i < mTracks.size(); i++) {
6919 sp<RecordTrack> track = mTracks[i];
6920 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6921 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6922 }
6923 }
6924
6925 // store new source and send to effects
6926 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6927 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07006928 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07006929 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07006930 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006931 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006932
Eric Laurent054d9d32015-04-24 08:48:48 -07006933 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006934 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6935 status = hwDevice->create_audio_patch(hwDevice,
6936 patch->num_sources,
6937 patch->sources,
6938 patch->num_sinks,
6939 patch->sinks,
6940 handle);
6941 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006942 char *address;
6943 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
6944 address = audio_device_address_to_parameter(
6945 patch->sources[0].ext.device.type,
6946 patch->sources[0].ext.device.address);
6947 } else {
6948 address = (char *)calloc(1, 1);
6949 }
6950 AudioParameter param = AudioParameter(String8(address));
6951 free(address);
6952 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
6953 (int)patch->sources[0].ext.device.type);
6954 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
6955 (int)patch->sinks[0].ext.mix.usecase.source);
6956 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6957 param.toString().string());
6958 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07006959 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006960
Eric Laurent296fb132015-05-01 11:38:42 -07006961 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
6962
Eric Laurent1c333e22014-05-20 10:48:17 -07006963 return status;
6964}
6965
6966status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6967{
6968 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006969
6970 mInDevice = AUDIO_DEVICE_NONE;
6971
Eric Laurent1c333e22014-05-20 10:48:17 -07006972 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6973 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6974 status = hwDevice->release_audio_patch(hwDevice, handle);
6975 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006976 AudioParameter param;
6977 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
6978 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6979 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07006980 }
6981 return status;
6982}
6983
Eric Laurent83b88082014-06-20 18:31:16 -07006984void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6985{
6986 Mutex::Autolock _l(mLock);
6987 mTracks.add(record);
6988}
6989
6990void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6991{
6992 Mutex::Autolock _l(mLock);
6993 destroyTrack_l(record);
6994}
6995
6996void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6997{
6998 ThreadBase::getAudioPortConfig(config);
6999 config->role = AUDIO_PORT_ROLE_SINK;
7000 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7001 config->ext.mix.usecase.source = mAudioSource;
7002}
Eric Laurent1c333e22014-05-20 10:48:17 -07007003
Glenn Kasten63238ef2015-03-02 15:50:29 -08007004} // namespace android