blob: 40bf3491c296272ddd05aa67baacc86ce2c412e1 [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;
Andy Hungf98ec8d2015-05-19 12:53:24 -0700700 const audio_channel_representation_t representation = audio_channel_mask_get_representation(mask);
701
702 switch (representation) {
703 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
704 if (output) {
705 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
706 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
707 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
708 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
709 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
710 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
711 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
712 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
713 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
714 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
715 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
716 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
717 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
718 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
719 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
720 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
721 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
722 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
723 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
724 } else {
725 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
726 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
727 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
728 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
729 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
730 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
731 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
732 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
733 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
734 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
735 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
736 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
737 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
738 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
739 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
740 }
741 const int len = s.length();
742 if (len > 2) {
743 char *str = s.lockBuffer(len); // needed?
744 s.unlockBuffer(len - 2); // remove trailing ", "
745 }
746 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800747 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700748 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
749 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
750 return s;
751 default:
752 s.appendFormat("unknown mask, representation:%d bits:%#x",
753 representation, audio_channel_mask_get_bits(mask));
754 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800755 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800756}
757
Glenn Kasten0f11b512014-01-31 16:18:54 -0800758void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800759{
760 const size_t SIZE = 256;
761 char buffer[SIZE];
762 String8 result;
763
764 bool locked = AudioFlinger::dumpTryLock(mLock);
765 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700766 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800767 }
768
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800769 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700770 dprintf(fd, " I/O handle: %d\n", mId);
771 dprintf(fd, " TID: %d\n", getTid());
772 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700773 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700774 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700775 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700776 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700777 dprintf(fd, " Channel count: %u\n", mChannelCount);
778 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800779 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700780 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
781 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700782 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800783 size_t numConfig = mConfigEvents.size();
784 if (numConfig) {
785 for (size_t i = 0; i < numConfig; i++) {
786 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700787 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800788 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700789 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800790 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700791 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800792 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800793 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
794 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
795 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800796
797 if (locked) {
798 mLock.unlock();
799 }
800}
801
802void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
803{
804 const size_t SIZE = 256;
805 char buffer[SIZE];
806 String8 result;
807
Marco Nelissenb2208842014-02-07 14:00:50 -0800808 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000809 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800810 write(fd, buffer, strlen(buffer));
811
Marco Nelissenb2208842014-02-07 14:00:50 -0800812 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800813 sp<EffectChain> chain = mEffectChains[i];
814 if (chain != 0) {
815 chain->dump(fd, args);
816 }
817 }
818}
819
Marco Nelissene14a5d62013-10-03 08:51:24 -0700820void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800821{
822 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700823 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800824}
825
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100826String16 AudioFlinger::ThreadBase::getWakeLockTag()
827{
828 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800829 case MIXER:
830 return String16("AudioMix");
831 case DIRECT:
832 return String16("AudioDirectOut");
833 case DUPLICATING:
834 return String16("AudioDup");
835 case RECORD:
836 return String16("AudioIn");
837 case OFFLOAD:
838 return String16("AudioOffload");
839 default:
840 ALOG_ASSERT(false);
841 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100842 }
843}
844
Marco Nelissene14a5d62013-10-03 08:51:24 -0700845void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800846{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800847 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800848 if (mPowerManager != 0) {
849 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700850 status_t status;
851 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700852 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700853 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100854 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700855 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700856 uid,
857 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700858 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700859 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700860 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100861 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700862 String16("media"),
863 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700864 }
Eric Laurent81784c32012-11-19 14:55:58 -0800865 if (status == NO_ERROR) {
866 mWakeLockToken = binder;
867 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800868 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800869 }
870}
871
872void AudioFlinger::ThreadBase::releaseWakeLock()
873{
874 Mutex::Autolock _l(mLock);
875 releaseWakeLock_l();
876}
877
878void AudioFlinger::ThreadBase::releaseWakeLock_l()
879{
880 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800881 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800882 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700883 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
884 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800885 }
886 mWakeLockToken.clear();
887 }
888}
889
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800890void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
891 Mutex::Autolock _l(mLock);
892 updateWakeLockUids_l(uids);
893}
894
895void AudioFlinger::ThreadBase::getPowerManager_l() {
896
897 if (mPowerManager == 0) {
898 // use checkService() to avoid blocking if power service is not up yet
899 sp<IBinder> binder =
900 defaultServiceManager()->checkService(String16("power"));
901 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800902 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800903 } else {
904 mPowerManager = interface_cast<IPowerManager>(binder);
905 binder->linkToDeath(mDeathRecipient);
906 }
907 }
908}
909
910void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
911
912 getPowerManager_l();
913 if (mWakeLockToken == NULL) {
914 ALOGE("no wake lock to update!");
915 return;
916 }
917 if (mPowerManager != 0) {
918 sp<IBinder> binder = new BBinder();
919 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700920 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
921 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800922 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800923 }
924}
925
Eric Laurent81784c32012-11-19 14:55:58 -0800926void AudioFlinger::ThreadBase::clearPowerManager()
927{
928 Mutex::Autolock _l(mLock);
929 releaseWakeLock_l();
930 mPowerManager.clear();
931}
932
Glenn Kasten0f11b512014-01-31 16:18:54 -0800933void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800934{
935 sp<ThreadBase> thread = mThread.promote();
936 if (thread != 0) {
937 thread->clearPowerManager();
938 }
939 ALOGW("power manager service died !!!");
940}
941
942void AudioFlinger::ThreadBase::setEffectSuspended(
943 const effect_uuid_t *type, bool suspend, int sessionId)
944{
945 Mutex::Autolock _l(mLock);
946 setEffectSuspended_l(type, suspend, sessionId);
947}
948
949void AudioFlinger::ThreadBase::setEffectSuspended_l(
950 const effect_uuid_t *type, bool suspend, int sessionId)
951{
952 sp<EffectChain> chain = getEffectChain_l(sessionId);
953 if (chain != 0) {
954 if (type != NULL) {
955 chain->setEffectSuspended_l(type, suspend);
956 } else {
957 chain->setEffectSuspendedAll_l(suspend);
958 }
959 }
960
961 updateSuspendedSessions_l(type, suspend, sessionId);
962}
963
964void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
965{
966 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
967 if (index < 0) {
968 return;
969 }
970
971 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
972 mSuspendedSessions.valueAt(index);
973
974 for (size_t i = 0; i < sessionEffects.size(); i++) {
975 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
976 for (int j = 0; j < desc->mRefCount; j++) {
977 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
978 chain->setEffectSuspendedAll_l(true);
979 } else {
980 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
981 desc->mType.timeLow);
982 chain->setEffectSuspended_l(&desc->mType, true);
983 }
984 }
985 }
986}
987
988void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
989 bool suspend,
990 int sessionId)
991{
992 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
993
994 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
995
996 if (suspend) {
997 if (index >= 0) {
998 sessionEffects = mSuspendedSessions.valueAt(index);
999 } else {
1000 mSuspendedSessions.add(sessionId, sessionEffects);
1001 }
1002 } else {
1003 if (index < 0) {
1004 return;
1005 }
1006 sessionEffects = mSuspendedSessions.valueAt(index);
1007 }
1008
1009
1010 int key = EffectChain::kKeyForSuspendAll;
1011 if (type != NULL) {
1012 key = type->timeLow;
1013 }
1014 index = sessionEffects.indexOfKey(key);
1015
1016 sp<SuspendedSessionDesc> desc;
1017 if (suspend) {
1018 if (index >= 0) {
1019 desc = sessionEffects.valueAt(index);
1020 } else {
1021 desc = new SuspendedSessionDesc();
1022 if (type != NULL) {
1023 desc->mType = *type;
1024 }
1025 sessionEffects.add(key, desc);
1026 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1027 }
1028 desc->mRefCount++;
1029 } else {
1030 if (index < 0) {
1031 return;
1032 }
1033 desc = sessionEffects.valueAt(index);
1034 if (--desc->mRefCount == 0) {
1035 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1036 sessionEffects.removeItemsAt(index);
1037 if (sessionEffects.isEmpty()) {
1038 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1039 sessionId);
1040 mSuspendedSessions.removeItem(sessionId);
1041 }
1042 }
1043 }
1044 if (!sessionEffects.isEmpty()) {
1045 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1046 }
1047}
1048
1049void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1050 bool enabled,
1051 int sessionId)
1052{
1053 Mutex::Autolock _l(mLock);
1054 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1055}
1056
1057void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1058 bool enabled,
1059 int sessionId)
1060{
1061 if (mType != RECORD) {
1062 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1063 // another session. This gives the priority to well behaved effect control panels
1064 // and applications not using global effects.
1065 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1066 // global effects
1067 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1068 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1069 }
1070 }
1071
1072 sp<EffectChain> chain = getEffectChain_l(sessionId);
1073 if (chain != 0) {
1074 chain->checkSuspendOnEffectEnabled(effect, enabled);
1075 }
1076}
1077
1078// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1079sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1080 const sp<AudioFlinger::Client>& client,
1081 const sp<IEffectClient>& effectClient,
1082 int32_t priority,
1083 int sessionId,
1084 effect_descriptor_t *desc,
1085 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001086 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001087{
1088 sp<EffectModule> effect;
1089 sp<EffectHandle> handle;
1090 status_t lStatus;
1091 sp<EffectChain> chain;
1092 bool chainCreated = false;
1093 bool effectCreated = false;
1094 bool effectRegistered = false;
1095
1096 lStatus = initCheck();
1097 if (lStatus != NO_ERROR) {
1098 ALOGW("createEffect_l() Audio driver not initialized.");
1099 goto Exit;
1100 }
1101
Andy Hung98ef9782014-03-04 14:46:50 -08001102 // Reject any effect on Direct output threads for now, since the format of
1103 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1104 if (mType == DIRECT) {
1105 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001106 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001107 lStatus = BAD_VALUE;
1108 goto Exit;
1109 }
1110
Andy Hung389cfdb2014-08-07 17:49:53 -07001111 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001112 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001113 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1114 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1115 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001116 lStatus = BAD_VALUE;
1117 goto Exit;
1118 }
1119
Eric Laurent5baf2af2013-09-12 17:37:00 -07001120 // Allow global effects only on offloaded and mixer threads
1121 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1122 switch (mType) {
1123 case MIXER:
1124 case OFFLOAD:
1125 break;
1126 case DIRECT:
1127 case DUPLICATING:
1128 case RECORD:
1129 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001130 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1131 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001132 lStatus = BAD_VALUE;
1133 goto Exit;
1134 }
Eric Laurent81784c32012-11-19 14:55:58 -08001135 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001136
Eric Laurent81784c32012-11-19 14:55:58 -08001137 // Only Pre processor effects are allowed on input threads and only on input threads
1138 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1139 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1140 desc->name, desc->flags, mType);
1141 lStatus = BAD_VALUE;
1142 goto Exit;
1143 }
1144
1145 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1146
1147 { // scope for mLock
1148 Mutex::Autolock _l(mLock);
1149
1150 // check for existing effect chain with the requested audio session
1151 chain = getEffectChain_l(sessionId);
1152 if (chain == 0) {
1153 // create a new chain for this session
1154 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1155 chain = new EffectChain(this, sessionId);
1156 addEffectChain_l(chain);
1157 chain->setStrategy(getStrategyForSession_l(sessionId));
1158 chainCreated = true;
1159 } else {
1160 effect = chain->getEffectFromDesc_l(desc);
1161 }
1162
1163 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1164
1165 if (effect == 0) {
1166 int id = mAudioFlinger->nextUniqueId();
1167 // Check CPU and memory usage
1168 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1169 if (lStatus != NO_ERROR) {
1170 goto Exit;
1171 }
1172 effectRegistered = true;
1173 // create a new effect module if none present in the chain
1174 effect = new EffectModule(this, chain, desc, id, sessionId);
1175 lStatus = effect->status();
1176 if (lStatus != NO_ERROR) {
1177 goto Exit;
1178 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001179 effect->setOffloaded(mType == OFFLOAD, mId);
1180
Eric Laurent81784c32012-11-19 14:55:58 -08001181 lStatus = chain->addEffect_l(effect);
1182 if (lStatus != NO_ERROR) {
1183 goto Exit;
1184 }
1185 effectCreated = true;
1186
1187 effect->setDevice(mOutDevice);
1188 effect->setDevice(mInDevice);
1189 effect->setMode(mAudioFlinger->getMode());
1190 effect->setAudioSource(mAudioSource);
1191 }
1192 // create effect handle and connect it to effect module
1193 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001194 lStatus = handle->initCheck();
1195 if (lStatus == OK) {
1196 lStatus = effect->addHandle(handle.get());
1197 }
Eric Laurent81784c32012-11-19 14:55:58 -08001198 if (enabled != NULL) {
1199 *enabled = (int)effect->isEnabled();
1200 }
1201 }
1202
1203Exit:
1204 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1205 Mutex::Autolock _l(mLock);
1206 if (effectCreated) {
1207 chain->removeEffect_l(effect);
1208 }
1209 if (effectRegistered) {
1210 AudioSystem::unregisterEffect(effect->id());
1211 }
1212 if (chainCreated) {
1213 removeEffectChain_l(chain);
1214 }
1215 handle.clear();
1216 }
1217
Glenn Kasten9156ef32013-08-06 15:39:08 -07001218 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001219 return handle;
1220}
1221
1222sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1223{
1224 Mutex::Autolock _l(mLock);
1225 return getEffect_l(sessionId, effectId);
1226}
1227
1228sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1229{
1230 sp<EffectChain> chain = getEffectChain_l(sessionId);
1231 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1232}
1233
1234// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1235// PlaybackThread::mLock held
1236status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1237{
1238 // check for existing effect chain with the requested audio session
1239 int sessionId = effect->sessionId();
1240 sp<EffectChain> chain = getEffectChain_l(sessionId);
1241 bool chainCreated = false;
1242
Eric Laurent5baf2af2013-09-12 17:37:00 -07001243 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1244 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1245 this, effect->desc().name, effect->desc().flags);
1246
Eric Laurent81784c32012-11-19 14:55:58 -08001247 if (chain == 0) {
1248 // create a new chain for this session
1249 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1250 chain = new EffectChain(this, sessionId);
1251 addEffectChain_l(chain);
1252 chain->setStrategy(getStrategyForSession_l(sessionId));
1253 chainCreated = true;
1254 }
1255 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1256
1257 if (chain->getEffectFromId_l(effect->id()) != 0) {
1258 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1259 this, effect->desc().name, chain.get());
1260 return BAD_VALUE;
1261 }
1262
Eric Laurent5baf2af2013-09-12 17:37:00 -07001263 effect->setOffloaded(mType == OFFLOAD, mId);
1264
Eric Laurent81784c32012-11-19 14:55:58 -08001265 status_t status = chain->addEffect_l(effect);
1266 if (status != NO_ERROR) {
1267 if (chainCreated) {
1268 removeEffectChain_l(chain);
1269 }
1270 return status;
1271 }
1272
1273 effect->setDevice(mOutDevice);
1274 effect->setDevice(mInDevice);
1275 effect->setMode(mAudioFlinger->getMode());
1276 effect->setAudioSource(mAudioSource);
1277 return NO_ERROR;
1278}
1279
1280void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1281
1282 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1283 effect_descriptor_t desc = effect->desc();
1284 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1285 detachAuxEffect_l(effect->id());
1286 }
1287
1288 sp<EffectChain> chain = effect->chain().promote();
1289 if (chain != 0) {
1290 // remove effect chain if removing last effect
1291 if (chain->removeEffect_l(effect) == 0) {
1292 removeEffectChain_l(chain);
1293 }
1294 } else {
1295 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1296 }
1297}
1298
1299void AudioFlinger::ThreadBase::lockEffectChains_l(
1300 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1301{
1302 effectChains = mEffectChains;
1303 for (size_t i = 0; i < mEffectChains.size(); i++) {
1304 mEffectChains[i]->lock();
1305 }
1306}
1307
1308void AudioFlinger::ThreadBase::unlockEffectChains(
1309 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1310{
1311 for (size_t i = 0; i < effectChains.size(); i++) {
1312 effectChains[i]->unlock();
1313 }
1314}
1315
1316sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1317{
1318 Mutex::Autolock _l(mLock);
1319 return getEffectChain_l(sessionId);
1320}
1321
1322sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1323{
1324 size_t size = mEffectChains.size();
1325 for (size_t i = 0; i < size; i++) {
1326 if (mEffectChains[i]->sessionId() == sessionId) {
1327 return mEffectChains[i];
1328 }
1329 }
1330 return 0;
1331}
1332
1333void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1334{
1335 Mutex::Autolock _l(mLock);
1336 size_t size = mEffectChains.size();
1337 for (size_t i = 0; i < size; i++) {
1338 mEffectChains[i]->setMode_l(mode);
1339 }
1340}
1341
Eric Laurent83b88082014-06-20 18:31:16 -07001342void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1343{
1344 config->type = AUDIO_PORT_TYPE_MIX;
1345 config->ext.mix.handle = mId;
1346 config->sample_rate = mSampleRate;
1347 config->format = mFormat;
1348 config->channel_mask = mChannelMask;
1349 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1350 AUDIO_PORT_CONFIG_FORMAT;
1351}
1352
1353
Eric Laurent81784c32012-11-19 14:55:58 -08001354// ----------------------------------------------------------------------------
1355// Playback
1356// ----------------------------------------------------------------------------
1357
1358AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1359 AudioStreamOut* output,
1360 audio_io_handle_t id,
1361 audio_devices_t device,
1362 type_t type)
1363 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001364 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001365 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001366 mMixerBuffer(NULL),
1367 mMixerBufferSize(0),
1368 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1369 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001370 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001371 mEffectBuffer(NULL),
1372 mEffectBufferSize(0),
1373 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1374 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001375 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001376 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001377 // mStreamTypes[] initialized in constructor body
1378 mOutput(output),
1379 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1380 mMixerStatus(MIXER_IDLE),
1381 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1382 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001383 mBytesRemaining(0),
1384 mCurrentWriteLength(0),
1385 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001386 mWriteAckSequence(0),
1387 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001388 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001389 mScreenState(AudioFlinger::mScreenState),
1390 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001391 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001392 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001393 // mLatchD, mLatchQ,
1394 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001395{
Glenn Kastend7dca052015-03-05 16:05:54 -08001396 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1397 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001398
1399 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1400 // it would be safer to explicitly pass initial masterVolume/masterMute as
1401 // parameter.
1402 //
1403 // If the HAL we are using has support for master volume or master mute,
1404 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1405 // and the mute set to false).
1406 mMasterVolume = audioFlinger->masterVolume_l();
1407 mMasterMute = audioFlinger->masterMute_l();
1408 if (mOutput && mOutput->audioHwDev) {
1409 if (mOutput->audioHwDev->canSetMasterVolume()) {
1410 mMasterVolume = 1.0;
1411 }
1412
1413 if (mOutput->audioHwDev->canSetMasterMute()) {
1414 mMasterMute = false;
1415 }
1416 }
1417
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001418 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001419
Eric Laurent223fd5c2014-11-11 13:43:36 -08001420 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001421 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001422 stream = (audio_stream_type_t) (stream + 1)) {
1423 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1424 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1425 }
Eric Laurent81784c32012-11-19 14:55:58 -08001426}
1427
1428AudioFlinger::PlaybackThread::~PlaybackThread()
1429{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001430 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001431 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001432 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001433 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001434}
1435
1436void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1437{
1438 dumpInternals(fd, args);
1439 dumpTracks(fd, args);
1440 dumpEffectChains(fd, args);
1441}
1442
Glenn Kasten0f11b512014-01-31 16:18:54 -08001443void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001444{
1445 const size_t SIZE = 256;
1446 char buffer[SIZE];
1447 String8 result;
1448
Marco Nelissenb2208842014-02-07 14:00:50 -08001449 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001450 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1451 const stream_type_t *st = &mStreamTypes[i];
1452 if (i > 0) {
1453 result.appendFormat(", ");
1454 }
1455 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1456 if (st->mute) {
1457 result.append("M");
1458 }
1459 }
1460 result.append("\n");
1461 write(fd, result.string(), result.length());
1462 result.clear();
1463
Eric Laurent81784c32012-11-19 14:55:58 -08001464 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1465 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001466 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001467 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001468
1469 size_t numtracks = mTracks.size();
1470 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001471 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001472 size_t numactiveseen = 0;
1473 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001474 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001475 Track::appendDumpHeader(result);
1476 for (size_t i = 0; i < numtracks; ++i) {
1477 sp<Track> track = mTracks[i];
1478 if (track != 0) {
1479 bool active = mActiveTracks.indexOf(track) >= 0;
1480 if (active) {
1481 numactiveseen++;
1482 }
1483 track->dump(buffer, SIZE, active);
1484 result.append(buffer);
1485 }
1486 }
1487 } else {
1488 result.append("\n");
1489 }
1490 if (numactiveseen != numactive) {
1491 // some tracks in the active list were not in the tracks list
1492 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1493 " not in the track list\n");
1494 result.append(buffer);
1495 Track::appendDumpHeader(result);
1496 for (size_t i = 0; i < numactive; ++i) {
1497 sp<Track> track = mActiveTracks[i].promote();
1498 if (track != 0 && mTracks.indexOf(track) < 0) {
1499 track->dump(buffer, SIZE, true);
1500 result.append(buffer);
1501 }
1502 }
1503 }
1504
1505 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001506}
1507
1508void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1509{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001510 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001511
1512 dumpBase(fd, args);
1513
Elliott Hughes87cebad2014-05-22 10:14:43 -07001514 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1515 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1516 dprintf(fd, " Total writes: %d\n", mNumWrites);
1517 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1518 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1519 dprintf(fd, " Suspend count: %d\n", mSuspended);
1520 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1521 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1522 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1523 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001524 AudioStreamOut *output = mOutput;
1525 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1526 String8 flagsAsString = outputFlagsToString(flags);
1527 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001528}
1529
1530// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001531
1532void AudioFlinger::PlaybackThread::onFirstRef()
1533{
Glenn Kastend7dca052015-03-05 16:05:54 -08001534 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001535}
1536
1537// ThreadBase virtuals
1538void AudioFlinger::PlaybackThread::preExit()
1539{
1540 ALOGV(" preExit()");
1541 // FIXME this is using hard-coded strings but in the future, this functionality will be
1542 // converted to use audio HAL extensions required to support tunneling
1543 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1544}
1545
1546// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1547sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1548 const sp<AudioFlinger::Client>& client,
1549 audio_stream_type_t streamType,
1550 uint32_t sampleRate,
1551 audio_format_t format,
1552 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001553 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001554 const sp<IMemory>& sharedBuffer,
1555 int sessionId,
1556 IAudioFlinger::track_flags_t *flags,
1557 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001558 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001559 status_t *status)
1560{
Glenn Kasten74935e42013-12-19 08:56:45 -08001561 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001562 sp<Track> track;
1563 status_t lStatus;
1564
1565 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1566
1567 // client expresses a preference for FAST, but we get the final say
1568 if (*flags & IAudioFlinger::TRACK_FAST) {
1569 if (
1570 // not timed
1571 (!isTimed) &&
1572 // either of these use cases:
1573 (
1574 // use case 1: shared buffer with any frame count
1575 (
1576 (sharedBuffer != 0)
1577 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001578 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001579 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001580 // we formerly checked for a callback handler (non-0 tid),
1581 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001582 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001583 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001584 )
1585 ) &&
1586 // PCM data
1587 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001588 // identical channel mask to sink, or mono in and stereo sink
1589 (channelMask == mChannelMask ||
1590 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1591 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001592 // hardware sample rate
1593 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001594 // normal mixer has an associated fast mixer
1595 hasFastMixer() &&
1596 // there are sufficient fast track slots available
1597 (mFastTrackAvailMask != 0)
1598 // FIXME test that MixerThread for this fast track has a capable output HAL
1599 // FIXME add a permission test also?
1600 ) {
1601 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1602 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001603 // read the fast track multiplier property the first time it is needed
1604 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1605 if (ok != 0) {
1606 ALOGE("%s pthread_once failed: %d", __func__, ok);
1607 }
1608 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001609 }
1610 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1611 frameCount, mFrameCount);
1612 } else {
1613 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001614 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1615 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001616 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001617 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001618 audio_is_linear_pcm(format),
1619 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1620 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001621 }
1622 }
1623 // For normal PCM streaming tracks, update minimum frame count.
1624 // For compatibility with AudioTrack calculation, buffer depth is forced
1625 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1626 // This is probably too conservative, but legacy application code may depend on it.
1627 // If you change this calculation, also review the start threshold which is related.
1628 if (!(*flags & IAudioFlinger::TRACK_FAST)
1629 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001630 // this must match AudioTrack.cpp calculateMinFrameCount().
1631 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001632 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1633 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1634 if (minBufCount < 2) {
1635 minBufCount = 2;
1636 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001637 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1638 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001639 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001640 minBufCount * sourceFramesNeededWithTimestretch(
1641 sampleRate, mNormalFrameCount,
1642 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001643 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001644 frameCount = minFrameCount;
1645 }
Eric Laurent81784c32012-11-19 14:55:58 -08001646 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001647 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001648
Glenn Kastenc3df8382014-03-13 15:05:25 -07001649 switch (mType) {
1650
1651 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001652 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001653 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001654 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1655 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001656 sampleRate, format, channelMask, mOutput, mFormat);
1657 lStatus = BAD_VALUE;
1658 goto Exit;
1659 }
1660 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001661 break;
1662
1663 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001664 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001665 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1666 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001667 sampleRate, format, channelMask, mOutput, mFormat);
1668 lStatus = BAD_VALUE;
1669 goto Exit;
1670 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001671 break;
1672
1673 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001674 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001675 ALOGE("createTrack_l() Bad parameter: format %#x \""
1676 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001677 format, mOutput, mFormat);
1678 lStatus = BAD_VALUE;
1679 goto Exit;
1680 }
Andy Hungcd044842014-08-07 11:04:34 -07001681 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001682 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1683 lStatus = BAD_VALUE;
1684 goto Exit;
1685 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001686 break;
1687
Eric Laurent81784c32012-11-19 14:55:58 -08001688 }
1689
1690 lStatus = initCheck();
1691 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001692 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001693 goto Exit;
1694 }
1695
1696 { // scope for mLock
1697 Mutex::Autolock _l(mLock);
1698
1699 // all tracks in same audio session must share the same routing strategy otherwise
1700 // conflicts will happen when tracks are moved from one output to another by audio policy
1701 // manager
1702 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1703 for (size_t i = 0; i < mTracks.size(); ++i) {
1704 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001705 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001706 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1707 if (sessionId == t->sessionId() && strategy != actual) {
1708 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1709 strategy, actual);
1710 lStatus = BAD_VALUE;
1711 goto Exit;
1712 }
1713 }
1714 }
1715
1716 if (!isTimed) {
1717 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001718 channelMask, frameCount, NULL, sharedBuffer,
1719 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001720 } else {
1721 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001722 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001723 }
Glenn Kasten03003332013-08-06 15:40:54 -07001724
1725 // new Track always returns non-NULL,
1726 // but TimedTrack::create() is a factory that could fail by returning NULL
1727 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1728 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001729 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001730 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001731 goto Exit;
1732 }
1733 mTracks.add(track);
1734
1735 sp<EffectChain> chain = getEffectChain_l(sessionId);
1736 if (chain != 0) {
1737 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1738 track->setMainBuffer(chain->inBuffer());
1739 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1740 chain->incTrackCnt();
1741 }
1742
1743 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1744 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1745 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1746 // so ask activity manager to do this on our behalf
1747 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1748 }
1749 }
1750
1751 lStatus = NO_ERROR;
1752
1753Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001754 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001755 return track;
1756}
1757
1758uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1759{
1760 return latency;
1761}
1762
1763uint32_t AudioFlinger::PlaybackThread::latency() const
1764{
1765 Mutex::Autolock _l(mLock);
1766 return latency_l();
1767}
1768uint32_t AudioFlinger::PlaybackThread::latency_l() const
1769{
1770 if (initCheck() == NO_ERROR) {
1771 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1772 } else {
1773 return 0;
1774 }
1775}
1776
1777void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1778{
1779 Mutex::Autolock _l(mLock);
1780 // Don't apply master volume in SW if our HAL can do it for us.
1781 if (mOutput && mOutput->audioHwDev &&
1782 mOutput->audioHwDev->canSetMasterVolume()) {
1783 mMasterVolume = 1.0;
1784 } else {
1785 mMasterVolume = value;
1786 }
1787}
1788
1789void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1790{
1791 Mutex::Autolock _l(mLock);
1792 // Don't apply master mute in SW if our HAL can do it for us.
1793 if (mOutput && mOutput->audioHwDev &&
1794 mOutput->audioHwDev->canSetMasterMute()) {
1795 mMasterMute = false;
1796 } else {
1797 mMasterMute = muted;
1798 }
1799}
1800
1801void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1802{
1803 Mutex::Autolock _l(mLock);
1804 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001805 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001806}
1807
1808void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1809{
1810 Mutex::Autolock _l(mLock);
1811 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001812 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001813}
1814
1815float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1816{
1817 Mutex::Autolock _l(mLock);
1818 return mStreamTypes[stream].volume;
1819}
1820
1821// addTrack_l() must be called with ThreadBase::mLock held
1822status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1823{
1824 status_t status = ALREADY_EXISTS;
1825
1826 // set retry count for buffer fill
1827 track->mRetryCount = kMaxTrackStartupRetries;
1828 if (mActiveTracks.indexOf(track) < 0) {
1829 // the track is newly added, make sure it fills up all its
1830 // buffers before playing. This is to ensure the client will
1831 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001832 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001833 TrackBase::track_state state = track->mState;
1834 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001835 status = AudioSystem::startOutput(mId, track->streamType(),
1836 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001837 mLock.lock();
1838 // abort track was stopped/paused while we released the lock
1839 if (state != track->mState) {
1840 if (status == NO_ERROR) {
1841 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001842 AudioSystem::stopOutput(mId, track->streamType(),
1843 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001844 mLock.lock();
1845 }
1846 return INVALID_OPERATION;
1847 }
1848 // abort if start is rejected by audio policy manager
1849 if (status != NO_ERROR) {
1850 return PERMISSION_DENIED;
1851 }
1852#ifdef ADD_BATTERY_DATA
1853 // to track the speaker usage
1854 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1855#endif
1856 }
1857
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001858 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001859 track->mResetDone = false;
1860 track->mPresentationCompleteFrames = 0;
1861 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001862 mWakeLockUids.add(track->uid());
1863 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001864 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001865 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1866 if (chain != 0) {
1867 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1868 track->sessionId());
1869 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001870 }
1871
1872 status = NO_ERROR;
1873 }
1874
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001875 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001876 return status;
1877}
1878
Eric Laurentbfb1b832013-01-07 09:53:42 -08001879bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001880{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001881 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001882 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001883 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1884 track->mState = TrackBase::STOPPED;
1885 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001886 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001887 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001888 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001889 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001890
1891 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001892}
1893
1894void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1895{
1896 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1897 mTracks.remove(track);
1898 deleteTrackName_l(track->name());
1899 // redundant as track is about to be destroyed, for dumpsys only
1900 track->mName = -1;
1901 if (track->isFastTrack()) {
1902 int index = track->mFastIndex;
1903 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1904 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1905 mFastTrackAvailMask |= 1 << index;
1906 // redundant as track is about to be destroyed, for dumpsys only
1907 track->mFastIndex = -1;
1908 }
1909 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1910 if (chain != 0) {
1911 chain->decTrackCnt();
1912 }
1913}
1914
Eric Laurentede6c3b2013-09-19 14:37:46 -07001915void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001916{
1917 // Thread could be blocked waiting for async
1918 // so signal it to handle state changes immediately
1919 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1920 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1921 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001922 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001923}
1924
Eric Laurent81784c32012-11-19 14:55:58 -08001925String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1926{
Eric Laurent81784c32012-11-19 14:55:58 -08001927 Mutex::Autolock _l(mLock);
1928 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001929 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001930 }
1931
Glenn Kastend8ea6992013-07-16 14:17:15 -07001932 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1933 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001934 free(s);
1935 return out_s8;
1936}
1937
Eric Laurent73e26b62015-04-27 16:55:58 -07001938void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
1939 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
1940 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08001941
Eric Laurent73e26b62015-04-27 16:55:58 -07001942 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08001943
1944 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07001945 case AUDIO_OUTPUT_OPENED:
1946 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07001947 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07001948 desc->mChannelMask = mChannelMask;
1949 desc->mSamplingRate = mSampleRate;
1950 desc->mFormat = mFormat;
1951 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08001952 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07001953 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001954 break;
1955
Eric Laurent73e26b62015-04-27 16:55:58 -07001956 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08001957 default:
1958 break;
1959 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001960 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001961}
1962
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963void AudioFlinger::PlaybackThread::writeCallback()
1964{
1965 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001966 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001967}
1968
1969void AudioFlinger::PlaybackThread::drainCallback()
1970{
1971 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001972 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973}
1974
Eric Laurent3b4529e2013-09-05 18:09:19 -07001975void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001976{
1977 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001978 // reject out of sequence requests
1979 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1980 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001981 mWaitWorkCV.signal();
1982 }
1983}
1984
Eric Laurent3b4529e2013-09-05 18:09:19 -07001985void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001986{
1987 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001988 // reject out of sequence requests
1989 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1990 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001991 mWaitWorkCV.signal();
1992 }
1993}
1994
1995// static
1996int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001997 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001998 void *cookie)
1999{
2000 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2001 ALOGV("asyncCallback() event %d", event);
2002 switch (event) {
2003 case STREAM_CBK_EVENT_WRITE_READY:
2004 me->writeCallback();
2005 break;
2006 case STREAM_CBK_EVENT_DRAIN_READY:
2007 me->drainCallback();
2008 break;
2009 default:
2010 ALOGW("asyncCallback() unknown event %d", event);
2011 break;
2012 }
2013 return 0;
2014}
2015
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002016void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002017{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002018 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002019 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2020 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002021 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002022 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002023 }
Andy Hung9a592762014-07-21 21:56:01 -07002024 if ((mType == MIXER || mType == DUPLICATING)
2025 && !isValidPcmSinkChannelMask(mChannelMask)) {
2026 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2027 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002028 }
Andy Hunge5412692014-05-16 11:25:07 -07002029 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002030 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2031 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002032 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002033 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002034 }
Andy Hung6146c082014-03-18 11:56:15 -07002035 if ((mType == MIXER || mType == DUPLICATING)
2036 && !isValidPcmSinkFormat(mFormat)) {
2037 LOG_FATAL("HAL format %#x not supported for mixed output",
2038 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002039 }
Phil Burk062e67a2015-02-11 13:40:50 -08002040 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002041 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2042 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002043 if (mFrameCount & 15) {
2044 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2045 mFrameCount);
2046 }
2047
Eric Laurentbfb1b832013-01-07 09:53:42 -08002048 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2049 (mOutput->stream->set_callback != NULL)) {
2050 if (mOutput->stream->set_callback(mOutput->stream,
2051 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2052 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002053 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002054 }
2055 }
2056
Eric Laurentd1f69b02014-12-15 14:33:13 -08002057 mHwSupportsPause = false;
2058 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2059 if (mOutput->stream->pause != NULL) {
2060 if (mOutput->stream->resume != NULL) {
2061 mHwSupportsPause = true;
2062 } else {
2063 ALOGW("direct output implements pause but not resume");
2064 }
2065 } else if (mOutput->stream->resume != NULL) {
2066 ALOGW("direct output implements resume but not pause");
2067 }
2068 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002069 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2070 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2071 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002072
Andy Hungfbfc3952015-01-15 13:33:51 -08002073 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2074 // For best precision, we use float instead of the associated output
2075 // device format (typically PCM 16 bit).
2076
2077 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2078 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2079 mBufferSize = mFrameSize * mFrameCount;
2080
2081 // TODO: We currently use the associated output device channel mask and sample rate.
2082 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2083 // (if a valid mask) to avoid premature downmix.
2084 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2085 // instead of the output device sample rate to avoid loss of high frequency information.
2086 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2087 }
2088
Andy Hung09a50072014-02-27 14:30:47 -08002089 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002090 double multiplier = 1.0;
2091 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2092 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002093 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2094 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002095 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2096 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2097 maxNormalFrameCount = maxNormalFrameCount & ~15;
2098 if (maxNormalFrameCount < minNormalFrameCount) {
2099 maxNormalFrameCount = minNormalFrameCount;
2100 }
2101 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2102 if (multiplier <= 1.0) {
2103 multiplier = 1.0;
2104 } else if (multiplier <= 2.0) {
2105 if (2 * mFrameCount <= maxNormalFrameCount) {
2106 multiplier = 2.0;
2107 } else {
2108 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2109 }
2110 } else {
2111 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002112 // 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 -08002113 // track, but we sometimes have to do this to satisfy the maximum frame count
2114 // constraint)
2115 // FIXME this rounding up should not be done if no HAL SRC
2116 uint32_t truncMult = (uint32_t) multiplier;
2117 if ((truncMult & 1)) {
2118 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2119 ++truncMult;
2120 }
2121 }
2122 multiplier = (double) truncMult;
2123 }
2124 }
2125 mNormalFrameCount = multiplier * mFrameCount;
2126 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002127 if (mType == MIXER || mType == DUPLICATING) {
2128 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2129 }
Andy Hung09a50072014-02-27 14:30:47 -08002130 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002131 mNormalFrameCount);
2132
Andy Hung010a1a12014-03-13 13:57:33 -07002133 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2134 // Originally this was int16_t[] array, need to remove legacy implications.
2135 free(mSinkBuffer);
2136 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002137 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2138 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2139 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002140 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002141
Andy Hung69aed5f2014-02-25 17:24:40 -08002142 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2143 // drives the output.
2144 free(mMixerBuffer);
2145 mMixerBuffer = NULL;
2146 if (mMixerBufferEnabled) {
2147 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2148 mMixerBufferSize = mNormalFrameCount * mChannelCount
2149 * audio_bytes_per_sample(mMixerBufferFormat);
2150 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2151 }
Andy Hung98ef9782014-03-04 14:46:50 -08002152 free(mEffectBuffer);
2153 mEffectBuffer = NULL;
2154 if (mEffectBufferEnabled) {
2155 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2156 mEffectBufferSize = mNormalFrameCount * mChannelCount
2157 * audio_bytes_per_sample(mEffectBufferFormat);
2158 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2159 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002160
Eric Laurent81784c32012-11-19 14:55:58 -08002161 // force reconfiguration of effect chains and engines to take new buffer size and audio
2162 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002163 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2165 // matter.
2166 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2167 Vector< sp<EffectChain> > effectChains = mEffectChains;
2168 for (size_t i = 0; i < effectChains.size(); i ++) {
2169 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2170 }
2171}
2172
2173
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002174status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002175{
2176 if (halFrames == NULL || dspFrames == NULL) {
2177 return BAD_VALUE;
2178 }
2179 Mutex::Autolock _l(mLock);
2180 if (initCheck() != NO_ERROR) {
2181 return INVALID_OPERATION;
2182 }
2183 size_t framesWritten = mBytesWritten / mFrameSize;
2184 *halFrames = framesWritten;
2185
2186 if (isSuspended()) {
2187 // return an estimation of rendered frames when the output is suspended
2188 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2189 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2190 return NO_ERROR;
2191 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002192 status_t status;
2193 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002194 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002195 *dspFrames = (size_t)frames;
2196 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002197 }
2198}
2199
2200uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2201{
2202 Mutex::Autolock _l(mLock);
2203 uint32_t result = 0;
2204 if (getEffectChain_l(sessionId) != 0) {
2205 result = EFFECT_SESSION;
2206 }
2207
2208 for (size_t i = 0; i < mTracks.size(); ++i) {
2209 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002210 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002211 result |= TRACK_SESSION;
2212 break;
2213 }
2214 }
2215
2216 return result;
2217}
2218
2219uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2220{
2221 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2222 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2223 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2224 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2225 }
2226 for (size_t i = 0; i < mTracks.size(); i++) {
2227 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002228 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002229 return AudioSystem::getStrategyForStream(track->streamType());
2230 }
2231 }
2232 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2233}
2234
2235
Phil Burk062e67a2015-02-11 13:40:50 -08002236AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002237{
2238 Mutex::Autolock _l(mLock);
2239 return mOutput;
2240}
2241
Phil Burk062e67a2015-02-11 13:40:50 -08002242AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002243{
2244 Mutex::Autolock _l(mLock);
2245 AudioStreamOut *output = mOutput;
2246 mOutput = NULL;
2247 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2248 // must push a NULL and wait for ack
2249 mOutputSink.clear();
2250 mPipeSink.clear();
2251 mNormalSink.clear();
2252 return output;
2253}
2254
2255// this method must always be called either with ThreadBase mLock held or inside the thread loop
2256audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2257{
2258 if (mOutput == NULL) {
2259 return NULL;
2260 }
2261 return &mOutput->stream->common;
2262}
2263
2264uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2265{
2266 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2267}
2268
2269status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2270{
2271 if (!isValidSyncEvent(event)) {
2272 return BAD_VALUE;
2273 }
2274
2275 Mutex::Autolock _l(mLock);
2276
2277 for (size_t i = 0; i < mTracks.size(); ++i) {
2278 sp<Track> track = mTracks[i];
2279 if (event->triggerSession() == track->sessionId()) {
2280 (void) track->setSyncEvent(event);
2281 return NO_ERROR;
2282 }
2283 }
2284
2285 return NAME_NOT_FOUND;
2286}
2287
2288bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2289{
2290 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2291}
2292
2293void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2294 const Vector< sp<Track> >& tracksToRemove)
2295{
2296 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002297 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002298 for (size_t i = 0 ; i < count ; i++) {
2299 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002300 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002301 AudioSystem::stopOutput(mId, track->streamType(),
2302 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303#ifdef ADD_BATTERY_DATA
2304 // to track the speaker usage
2305 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2306#endif
2307 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002308 AudioSystem::releaseOutput(mId, track->streamType(),
2309 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310 }
Eric Laurent81784c32012-11-19 14:55:58 -08002311 }
2312 }
2313 }
Eric Laurent81784c32012-11-19 14:55:58 -08002314}
2315
2316void AudioFlinger::PlaybackThread::checkSilentMode_l()
2317{
2318 if (!mMasterMute) {
2319 char value[PROPERTY_VALUE_MAX];
2320 if (property_get("ro.audio.silent", value, "0") > 0) {
2321 char *endptr;
2322 unsigned long ul = strtoul(value, &endptr, 0);
2323 if (*endptr == '\0' && ul != 0) {
2324 ALOGD("Silence is golden");
2325 // The setprop command will not allow a property to be changed after
2326 // the first time it is set, so we don't have to worry about un-muting.
2327 setMasterMute_l(true);
2328 }
2329 }
2330 }
2331}
2332
2333// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002334ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002335{
2336 // FIXME rewrite to reduce number of system calls
2337 mLastWriteTime = systemTime();
2338 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002340 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002341
2342 // If an NBAIO sink is present, use it to write the normal mixer's submix
2343 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002344
Andy Hung010a1a12014-03-13 13:57:33 -07002345 const size_t count = mBytesRemaining / mFrameSize;
2346
Simon Wilson2d590962012-11-29 15:18:50 -08002347 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002348 // update the setpoint when AudioFlinger::mScreenState changes
2349 uint32_t screenState = AudioFlinger::mScreenState;
2350 if (screenState != mScreenState) {
2351 mScreenState = screenState;
2352 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2353 if (pipe != NULL) {
2354 pipe->setAvgFrames((mScreenState & 1) ?
2355 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2356 }
2357 }
Andy Hung010a1a12014-03-13 13:57:33 -07002358 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002359 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002360 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002361 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002362 } else {
2363 bytesWritten = framesWritten;
2364 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002365 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002366 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002367 if (status == NO_ERROR) {
2368 size_t totalFramesWritten = mNormalSink->framesWritten();
2369 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2370 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002371 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002372 mLatchDValid = true;
2373 }
2374 }
Eric Laurent81784c32012-11-19 14:55:58 -08002375 // otherwise use the HAL / AudioStreamOut directly
2376 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002377 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002378
Eric Laurentbfb1b832013-01-07 09:53:42 -08002379 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002380 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2381 mWriteAckSequence += 2;
2382 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002384 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002385 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002386 // FIXME We should have an implementation of timestamps for direct output threads.
2387 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002388 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 if (mUseAsyncWrite &&
2390 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2391 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002392 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002393 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002394 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 }
Eric Laurent81784c32012-11-19 14:55:58 -08002396 }
2397
Eric Laurent81784c32012-11-19 14:55:58 -08002398 mNumWrites++;
2399 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002400 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002401 return bytesWritten;
2402}
2403
2404void AudioFlinger::PlaybackThread::threadLoop_drain()
2405{
2406 if (mOutput->stream->drain) {
2407 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2408 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002409 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2410 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002411 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002412 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002413 }
2414 mOutput->stream->drain(mOutput->stream,
2415 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2416 : AUDIO_DRAIN_ALL);
2417 }
2418}
2419
2420void AudioFlinger::PlaybackThread::threadLoop_exit()
2421{
Eric Laurent275e8e92014-11-30 15:14:47 -08002422 {
2423 Mutex::Autolock _l(mLock);
2424 for (size_t i = 0; i < mTracks.size(); i++) {
2425 sp<Track> track = mTracks[i];
2426 track->invalidate();
2427 }
2428 }
Eric Laurent81784c32012-11-19 14:55:58 -08002429}
2430
2431/*
2432The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002433 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002434 - activeSleepTime from activeSleepTimeUs()
2435 - idleSleepTime from idleSleepTimeUs()
2436 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2437 - maxPeriod from frame count and sample rate (MIXER only)
2438
2439The parameters that affect these derived values are:
2440 - frame count
2441 - frame size
2442 - sample rate
2443 - device type: A2DP or not
2444 - device latency
2445 - format: PCM or not
2446 - active sleep time
2447 - idle sleep time
2448*/
2449
2450void AudioFlinger::PlaybackThread::cacheParameters_l()
2451{
Andy Hung25c2dac2014-02-27 14:56:00 -08002452 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002453 activeSleepTime = activeSleepTimeUs();
2454 idleSleepTime = idleSleepTimeUs();
2455}
2456
2457void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2458{
Glenn Kasten7c027242012-12-26 14:43:16 -08002459 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002460 this, streamType, mTracks.size());
2461 Mutex::Autolock _l(mLock);
2462
2463 size_t size = mTracks.size();
2464 for (size_t i = 0; i < size; i++) {
2465 sp<Track> t = mTracks[i];
2466 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002467 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002468 }
2469 }
2470}
2471
2472status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2473{
2474 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002475 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2476 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002477 bool ownsBuffer = false;
2478
2479 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2480 if (session > 0) {
2481 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002482 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002483 if (mType != DIRECT) {
2484 size_t numSamples = mNormalFrameCount * mChannelCount;
2485 buffer = new int16_t[numSamples];
2486 memset(buffer, 0, numSamples * sizeof(int16_t));
2487 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2488 ownsBuffer = true;
2489 }
2490
2491 // Attach all tracks with same session ID to this chain.
2492 for (size_t i = 0; i < mTracks.size(); ++i) {
2493 sp<Track> track = mTracks[i];
2494 if (session == track->sessionId()) {
2495 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2496 buffer);
2497 track->setMainBuffer(buffer);
2498 chain->incTrackCnt();
2499 }
2500 }
2501
2502 // indicate all active tracks in the chain
2503 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2504 sp<Track> track = mActiveTracks[i].promote();
2505 if (track == 0) {
2506 continue;
2507 }
2508 if (session == track->sessionId()) {
2509 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2510 chain->incActiveTrackCnt();
2511 }
2512 }
2513 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002514 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002515 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002516 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2517 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002518 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2519 // chains list in order to be processed last as it contains output stage effects
2520 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2521 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2522 // after track specific effects and before output stage
2523 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2524 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2525 // Effect chain for other sessions are inserted at beginning of effect
2526 // chains list to be processed before output mix effects. Relative order between other
2527 // sessions is not important
2528 size_t size = mEffectChains.size();
2529 size_t i = 0;
2530 for (i = 0; i < size; i++) {
2531 if (mEffectChains[i]->sessionId() < session) {
2532 break;
2533 }
2534 }
2535 mEffectChains.insertAt(chain, i);
2536 checkSuspendOnAddEffectChain_l(chain);
2537
2538 return NO_ERROR;
2539}
2540
2541size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2542{
2543 int session = chain->sessionId();
2544
2545 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2546
2547 for (size_t i = 0; i < mEffectChains.size(); i++) {
2548 if (chain == mEffectChains[i]) {
2549 mEffectChains.removeAt(i);
2550 // detach all active tracks from the chain
2551 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2552 sp<Track> track = mActiveTracks[i].promote();
2553 if (track == 0) {
2554 continue;
2555 }
2556 if (session == track->sessionId()) {
2557 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2558 chain.get(), session);
2559 chain->decActiveTrackCnt();
2560 }
2561 }
2562
2563 // detach all tracks with same session ID from this chain
2564 for (size_t i = 0; i < mTracks.size(); ++i) {
2565 sp<Track> track = mTracks[i];
2566 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002567 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002568 chain->decTrackCnt();
2569 }
2570 }
2571 break;
2572 }
2573 }
2574 return mEffectChains.size();
2575}
2576
2577status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2578 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2579{
2580 Mutex::Autolock _l(mLock);
2581 return attachAuxEffect_l(track, EffectId);
2582}
2583
2584status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2585 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2586{
2587 status_t status = NO_ERROR;
2588
2589 if (EffectId == 0) {
2590 track->setAuxBuffer(0, NULL);
2591 } else {
2592 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2593 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2594 if (effect != 0) {
2595 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2596 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2597 } else {
2598 status = INVALID_OPERATION;
2599 }
2600 } else {
2601 status = BAD_VALUE;
2602 }
2603 }
2604 return status;
2605}
2606
2607void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2608{
2609 for (size_t i = 0; i < mTracks.size(); ++i) {
2610 sp<Track> track = mTracks[i];
2611 if (track->auxEffectId() == effectId) {
2612 attachAuxEffect_l(track, 0);
2613 }
2614 }
2615}
2616
2617bool AudioFlinger::PlaybackThread::threadLoop()
2618{
2619 Vector< sp<Track> > tracksToRemove;
2620
2621 standbyTime = systemTime();
2622
2623 // MIXER
2624 nsecs_t lastWarning = 0;
2625
2626 // DUPLICATING
2627 // FIXME could this be made local to while loop?
2628 writeFrames = 0;
2629
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002630 int lastGeneration = 0;
2631
Eric Laurent81784c32012-11-19 14:55:58 -08002632 cacheParameters_l();
2633 sleepTime = idleSleepTime;
2634
2635 if (mType == MIXER) {
2636 sleepTimeShift = 0;
2637 }
2638
2639 CpuStats cpuStats;
2640 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2641
2642 acquireWakeLock();
2643
Glenn Kasten9e58b552013-01-18 15:09:48 -08002644 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2645 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2646 // and then that string will be logged at the next convenient opportunity.
2647 const char *logString = NULL;
2648
Eric Laurent664539d2013-09-23 18:24:31 -07002649 checkSilentMode_l();
2650
Eric Laurent81784c32012-11-19 14:55:58 -08002651 while (!exitPending())
2652 {
2653 cpuStats.sample(myName);
2654
2655 Vector< sp<EffectChain> > effectChains;
2656
Eric Laurent81784c32012-11-19 14:55:58 -08002657 { // scope for mLock
2658
2659 Mutex::Autolock _l(mLock);
2660
Eric Laurent021cf962014-05-13 10:18:14 -07002661 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002662
Glenn Kasten9e58b552013-01-18 15:09:48 -08002663 if (logString != NULL) {
2664 mNBLogWriter->logTimestamp();
2665 mNBLogWriter->log(logString);
2666 logString = NULL;
2667 }
2668
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002669 // Gather the framesReleased counters for all active tracks,
2670 // and latch them atomically with the timestamp.
2671 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2672 mLatchD.mFramesReleased.clear();
2673 size_t size = mActiveTracks.size();
2674 for (size_t i = 0; i < size; i++) {
2675 sp<Track> t = mActiveTracks[i].promote();
2676 if (t != 0) {
2677 mLatchD.mFramesReleased.add(t.get(),
2678 t->mAudioTrackServerProxy->framesReleased());
2679 }
2680 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002681 if (mLatchDValid) {
2682 mLatchQ = mLatchD;
2683 mLatchDValid = false;
2684 mLatchQValid = true;
2685 }
2686
Eric Laurent81784c32012-11-19 14:55:58 -08002687 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 if (mSignalPending) {
2689 // A signal was raised while we were unlocked
2690 mSignalPending = false;
2691 } else if (waitingAsyncCallback_l()) {
2692 if (exitPending()) {
2693 break;
2694 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002695 bool released = false;
2696 // The following works around a bug in the offload driver. Ideally we would release
2697 // the wake lock every time, but that causes the last offload buffer(s) to be
2698 // dropped while the device is on battery, so we need to hold a wake lock during
2699 // the drain phase.
2700 if (mBytesRemaining && !(mDrainSequence & 1)) {
2701 releaseWakeLock_l();
2702 released = true;
2703 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002704 mWakeLockUids.clear();
2705 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002706 ALOGV("wait async completion");
2707 mWaitWorkCV.wait(mLock);
2708 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002709 if (released) {
2710 acquireWakeLock_l();
2711 }
Eric Laurent972a1732013-09-04 09:42:59 -07002712 standbyTime = systemTime() + standbyDelay;
2713 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002714
2715 continue;
2716 }
2717 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002718 isSuspended()) {
2719 // put audio hardware into standby after short delay
2720 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002721
2722 threadLoop_standby();
2723
2724 mStandby = true;
2725 }
2726
2727 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2728 // we're about to wait, flush the binder command buffer
2729 IPCThreadState::self()->flushCommands();
2730
2731 clearOutputTracks();
2732
2733 if (exitPending()) {
2734 break;
2735 }
2736
2737 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002738 mWakeLockUids.clear();
2739 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002740 // wait until we have something to do...
2741 ALOGV("%s going to sleep", myName.string());
2742 mWaitWorkCV.wait(mLock);
2743 ALOGV("%s waking up", myName.string());
2744 acquireWakeLock_l();
2745
2746 mMixerStatus = MIXER_IDLE;
2747 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2748 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002749 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002750 checkSilentMode_l();
2751
2752 standbyTime = systemTime() + standbyDelay;
2753 sleepTime = idleSleepTime;
2754 if (mType == MIXER) {
2755 sleepTimeShift = 0;
2756 }
2757
2758 continue;
2759 }
2760 }
Eric Laurent81784c32012-11-19 14:55:58 -08002761 // mMixerStatusIgnoringFastTracks is also updated internally
2762 mMixerStatus = prepareTracks_l(&tracksToRemove);
2763
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002764 // compare with previously applied list
2765 if (lastGeneration != mActiveTracksGeneration) {
2766 // update wakelock
2767 updateWakeLockUids_l(mWakeLockUids);
2768 lastGeneration = mActiveTracksGeneration;
2769 }
2770
Eric Laurent81784c32012-11-19 14:55:58 -08002771 // prevent any changes in effect chain list and in each effect chain
2772 // during mixing and effect process as the audio buffers could be deleted
2773 // or modified if an effect is created or deleted
2774 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002775 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002776
Eric Laurentbfb1b832013-01-07 09:53:42 -08002777 if (mBytesRemaining == 0) {
2778 mCurrentWriteLength = 0;
2779 if (mMixerStatus == MIXER_TRACKS_READY) {
2780 // threadLoop_mix() sets mCurrentWriteLength
2781 threadLoop_mix();
2782 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2783 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2784 // threadLoop_sleepTime sets sleepTime to 0 if data
2785 // must be written to HAL
2786 threadLoop_sleepTime();
2787 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002788 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002789 }
2790 }
Andy Hung98ef9782014-03-04 14:46:50 -08002791 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2792 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2793 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2794 // or mSinkBuffer (if there are no effects).
2795 //
2796 // This is done pre-effects computation; if effects change to
2797 // support higher precision, this needs to move.
2798 //
2799 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2800 // TODO use sleepTime == 0 as an additional condition.
2801 if (mMixerBufferValid) {
2802 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2803 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2804
2805 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2806 mNormalFrameCount * mChannelCount);
2807 }
2808
Eric Laurentbfb1b832013-01-07 09:53:42 -08002809 mBytesRemaining = mCurrentWriteLength;
2810 if (isSuspended()) {
2811 sleepTime = suspendSleepTimeUs();
2812 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002813 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002814 mBytesRemaining = 0;
2815 }
Eric Laurent81784c32012-11-19 14:55:58 -08002816
Eric Laurentbfb1b832013-01-07 09:53:42 -08002817 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002818 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819 for (size_t i = 0; i < effectChains.size(); i ++) {
2820 effectChains[i]->process_l();
2821 }
Eric Laurent81784c32012-11-19 14:55:58 -08002822 }
2823 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002824 // Process effect chains for offloaded thread even if no audio
2825 // was read from audio track: process only updates effect state
2826 // and thus does have to be synchronized with audio writes but may have
2827 // to be called while waiting for async write callback
2828 if (mType == OFFLOAD) {
2829 for (size_t i = 0; i < effectChains.size(); i ++) {
2830 effectChains[i]->process_l();
2831 }
2832 }
Eric Laurent81784c32012-11-19 14:55:58 -08002833
Andy Hung98ef9782014-03-04 14:46:50 -08002834 // Only if the Effects buffer is enabled and there is data in the
2835 // Effects buffer (buffer valid), we need to
2836 // copy into the sink buffer.
2837 // TODO use sleepTime == 0 as an additional condition.
2838 if (mEffectBufferValid) {
2839 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2840 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2841 mNormalFrameCount * mChannelCount);
2842 }
2843
Eric Laurent81784c32012-11-19 14:55:58 -08002844 // enable changes in effect chain
2845 unlockEffectChains(effectChains);
2846
Eric Laurentbfb1b832013-01-07 09:53:42 -08002847 if (!waitingAsyncCallback()) {
2848 // sleepTime == 0 means we must write to audio hardware
2849 if (sleepTime == 0) {
2850 if (mBytesRemaining) {
2851 ssize_t ret = threadLoop_write();
2852 if (ret < 0) {
2853 mBytesRemaining = 0;
2854 } else {
2855 mBytesWritten += ret;
2856 mBytesRemaining -= ret;
2857 }
2858 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2859 (mMixerStatus == MIXER_DRAIN_ALL)) {
2860 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002861 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002862 if (mType == MIXER) {
2863 // write blocked detection
2864 nsecs_t now = systemTime();
2865 nsecs_t delta = now - mLastWriteTime;
2866 if (!mStandby && delta > maxPeriod) {
2867 mNumDelayedWrites++;
2868 if ((now - lastWarning) > kWarningThrottleNs) {
2869 ATRACE_NAME("underrun");
2870 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2871 ns2ms(delta), mNumDelayedWrites, this);
2872 lastWarning = now;
2873 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 }
2875 }
Eric Laurent81784c32012-11-19 14:55:58 -08002876
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002878 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002880 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 }
Eric Laurent81784c32012-11-19 14:55:58 -08002882 }
2883
2884 // Finally let go of removed track(s), without the lock held
2885 // since we can't guarantee the destructors won't acquire that
2886 // same lock. This will also mutate and push a new fast mixer state.
2887 threadLoop_removeTracks(tracksToRemove);
2888 tracksToRemove.clear();
2889
2890 // FIXME I don't understand the need for this here;
2891 // it was in the original code but maybe the
2892 // assignment in saveOutputTracks() makes this unnecessary?
2893 clearOutputTracks();
2894
2895 // Effect chains will be actually deleted here if they were removed from
2896 // mEffectChains list during mixing or effects processing
2897 effectChains.clear();
2898
2899 // FIXME Note that the above .clear() is no longer necessary since effectChains
2900 // is now local to this block, but will keep it for now (at least until merge done).
2901 }
2902
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 threadLoop_exit();
2904
Eric Laurentcf817a22014-08-04 20:36:31 -07002905 if (!mStandby) {
2906 threadLoop_standby();
2907 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002908 }
2909
2910 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002911 mWakeLockUids.clear();
2912 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002913
2914 ALOGV("Thread %p type %d exiting", this, mType);
2915 return false;
2916}
2917
Eric Laurentbfb1b832013-01-07 09:53:42 -08002918// removeTracks_l() must be called with ThreadBase::mLock held
2919void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2920{
2921 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002922 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 for (size_t i=0 ; i<count ; i++) {
2924 const sp<Track>& track = tracksToRemove.itemAt(i);
2925 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002926 mWakeLockUids.remove(track->uid());
2927 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002928 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2929 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2930 if (chain != 0) {
2931 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2932 track->sessionId());
2933 chain->decActiveTrackCnt();
2934 }
2935 if (track->isTerminated()) {
2936 removeTrack_l(track);
2937 }
2938 }
2939 }
2940
2941}
Eric Laurent81784c32012-11-19 14:55:58 -08002942
Eric Laurentaccc1472013-09-20 09:36:34 -07002943status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2944{
2945 if (mNormalSink != 0) {
2946 return mNormalSink->getTimestamp(timestamp);
2947 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002948 if ((mType == OFFLOAD || mType == DIRECT)
2949 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002950 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002951 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002952 if (ret == 0) {
2953 timestamp.mPosition = (uint32_t)position64;
2954 return NO_ERROR;
2955 }
2956 }
2957 return INVALID_OPERATION;
2958}
Eric Laurent1c333e22014-05-20 10:48:17 -07002959
Eric Laurent054d9d32015-04-24 08:48:48 -07002960status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
2961 audio_patch_handle_t *handle)
2962{
2963 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2964 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2965 if (mFastMixer != 0) {
2966 FastMixerStateQueue *sq = mFastMixer->sq();
2967 FastMixerState *state = sq->begin();
2968 if (!(state->mCommand & FastMixerState::IDLE)) {
2969 previousCommand = state->mCommand;
2970 state->mCommand = FastMixerState::HOT_IDLE;
2971 sq->end();
2972 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2973 } else {
2974 sq->end(false /*didModify*/);
2975 }
2976 }
2977 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
2978
2979 if (!(previousCommand & FastMixerState::IDLE)) {
2980 ALOG_ASSERT(mFastMixer != 0);
2981 FastMixerStateQueue *sq = mFastMixer->sq();
2982 FastMixerState *state = sq->begin();
2983 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
2984 state->mCommand = previousCommand;
2985 sq->end();
2986 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2987 }
2988
2989 return status;
2990}
2991
Eric Laurent1c333e22014-05-20 10:48:17 -07002992status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2993 audio_patch_handle_t *handle)
2994{
2995 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07002996
2997 // store new device and send to effects
2998 audio_devices_t type = AUDIO_DEVICE_NONE;
2999 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3000 type |= patch->sinks[i].ext.device.type;
3001 }
3002
3003#ifdef ADD_BATTERY_DATA
3004 // when changing the audio output device, call addBatteryData to notify
3005 // the change
3006 if (mOutDevice != type) {
3007 uint32_t params = 0;
3008 // check whether speaker is on
3009 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3010 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003011 }
3012
Eric Laurent054d9d32015-04-24 08:48:48 -07003013 audio_devices_t deviceWithoutSpeaker
3014 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3015 // check if any other device (except speaker) is on
3016 if (type & deviceWithoutSpeaker) {
3017 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3018 }
3019
3020 if (params != 0) {
3021 addBatteryData(params);
3022 }
3023 }
3024#endif
3025
3026 for (size_t i = 0; i < mEffectChains.size(); i++) {
3027 mEffectChains[i]->setDevice_l(type);
3028 }
3029 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003030 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003031
3032 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003033 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3034 status = hwDevice->create_audio_patch(hwDevice,
3035 patch->num_sources,
3036 patch->sources,
3037 patch->num_sinks,
3038 patch->sinks,
3039 handle);
3040 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003041 char *address;
3042 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3043 //FIXME: we only support address on first sink with HAL version < 3.0
3044 address = audio_device_address_to_parameter(
3045 patch->sinks[0].ext.device.type,
3046 patch->sinks[0].ext.device.address);
3047 } else {
3048 address = (char *)calloc(1, 1);
3049 }
3050 AudioParameter param = AudioParameter(String8(address));
3051 free(address);
3052 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3053 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3054 param.toString().string());
3055 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003056 }
Eric Laurent296fb132015-05-01 11:38:42 -07003057 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003058 return status;
3059}
3060
Eric Laurent054d9d32015-04-24 08:48:48 -07003061status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3062{
3063 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3064 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3065 if (mFastMixer != 0) {
3066 FastMixerStateQueue *sq = mFastMixer->sq();
3067 FastMixerState *state = sq->begin();
3068 if (!(state->mCommand & FastMixerState::IDLE)) {
3069 previousCommand = state->mCommand;
3070 state->mCommand = FastMixerState::HOT_IDLE;
3071 sq->end();
3072 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3073 } else {
3074 sq->end(false /*didModify*/);
3075 }
3076 }
3077
3078 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3079
3080 if (!(previousCommand & FastMixerState::IDLE)) {
3081 ALOG_ASSERT(mFastMixer != 0);
3082 FastMixerStateQueue *sq = mFastMixer->sq();
3083 FastMixerState *state = sq->begin();
3084 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3085 state->mCommand = previousCommand;
3086 sq->end();
3087 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3088 }
3089
3090 return status;
3091}
3092
Eric Laurent1c333e22014-05-20 10:48:17 -07003093status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3094{
3095 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003096
3097 mOutDevice = AUDIO_DEVICE_NONE;
3098
Eric Laurent1c333e22014-05-20 10:48:17 -07003099 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3100 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3101 status = hwDevice->release_audio_patch(hwDevice, handle);
3102 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003103 AudioParameter param;
3104 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3105 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3106 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003107 }
3108 return status;
3109}
3110
Eric Laurent83b88082014-06-20 18:31:16 -07003111void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3112{
3113 Mutex::Autolock _l(mLock);
3114 mTracks.add(track);
3115}
3116
3117void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3118{
3119 Mutex::Autolock _l(mLock);
3120 destroyTrack_l(track);
3121}
3122
3123void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3124{
3125 ThreadBase::getAudioPortConfig(config);
3126 config->role = AUDIO_PORT_ROLE_SOURCE;
3127 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3128 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3129}
3130
Eric Laurent81784c32012-11-19 14:55:58 -08003131// ----------------------------------------------------------------------------
3132
3133AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
3134 audio_io_handle_t id, audio_devices_t device, type_t type)
3135 : PlaybackThread(audioFlinger, output, id, device, type),
3136 // mAudioMixer below
3137 // mFastMixer below
3138 mFastMixerFutex(0)
3139 // mOutputSink below
3140 // mPipeSink below
3141 // mNormalSink below
3142{
3143 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003144 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003145 "mFrameCount=%d, mNormalFrameCount=%d",
3146 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3147 mNormalFrameCount);
3148 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3149
Andy Hungfbfc3952015-01-15 13:33:51 -08003150 if (type == DUPLICATING) {
3151 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3152 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3153 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3154 return;
3155 }
Eric Laurent81784c32012-11-19 14:55:58 -08003156 // create an NBAIO sink for the HAL output stream, and negotiate
3157 mOutputSink = new AudioStreamOutSink(output->stream);
3158 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003159 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003160 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3161 ALOG_ASSERT(index == 0);
3162
3163 // initialize fast mixer depending on configuration
3164 bool initFastMixer;
3165 switch (kUseFastMixer) {
3166 case FastMixer_Never:
3167 initFastMixer = false;
3168 break;
3169 case FastMixer_Always:
3170 initFastMixer = true;
3171 break;
3172 case FastMixer_Static:
3173 case FastMixer_Dynamic:
3174 initFastMixer = mFrameCount < mNormalFrameCount;
3175 break;
3176 }
3177 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003178 audio_format_t fastMixerFormat;
3179 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3180 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3181 } else {
3182 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3183 }
3184 if (mFormat != fastMixerFormat) {
3185 // change our Sink format to accept our intermediate precision
3186 mFormat = fastMixerFormat;
3187 free(mSinkBuffer);
3188 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3189 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3190 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3191 }
Eric Laurent81784c32012-11-19 14:55:58 -08003192
3193 // create a MonoPipe to connect our submix to FastMixer
3194 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003195 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003196 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003197 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003198 format.mFormat = fastMixerFormat;
3199 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3200
Eric Laurent81784c32012-11-19 14:55:58 -08003201 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3202 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3203 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3204 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3205 const NBAIO_Format offers[1] = {format};
3206 size_t numCounterOffers = 0;
3207 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3208 ALOG_ASSERT(index == 0);
3209 monoPipe->setAvgFrames((mScreenState & 1) ?
3210 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3211 mPipeSink = monoPipe;
3212
Glenn Kasten46909e72013-02-26 09:20:22 -08003213#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003214 if (mTeeSinkOutputEnabled) {
3215 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003216 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3217 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003218 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003219 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003220 ALOG_ASSERT(index == 0);
3221 mTeeSink = teeSink;
3222 PipeReader *teeSource = new PipeReader(*teeSink);
3223 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003224 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003225 ALOG_ASSERT(index == 0);
3226 mTeeSource = teeSource;
3227 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003228#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003229
3230 // create fast mixer and configure it initially with just one fast track for our submix
3231 mFastMixer = new FastMixer();
3232 FastMixerStateQueue *sq = mFastMixer->sq();
3233#ifdef STATE_QUEUE_DUMP
3234 sq->setObserverDump(&mStateQueueObserverDump);
3235 sq->setMutatorDump(&mStateQueueMutatorDump);
3236#endif
3237 FastMixerState *state = sq->begin();
3238 FastTrack *fastTrack = &state->mFastTracks[0];
3239 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3240 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3241 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003242 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3243 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003244 fastTrack->mGeneration++;
3245 state->mFastTracksGen++;
3246 state->mTrackMask = 1;
3247 // fast mixer will use the HAL output sink
3248 state->mOutputSink = mOutputSink.get();
3249 state->mOutputSinkGen++;
3250 state->mFrameCount = mFrameCount;
3251 state->mCommand = FastMixerState::COLD_IDLE;
3252 // already done in constructor initialization list
3253 //mFastMixerFutex = 0;
3254 state->mColdFutexAddr = &mFastMixerFutex;
3255 state->mColdGen++;
3256 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003257#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003258 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003259#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003260 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3261 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003262 sq->end();
3263 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3264
3265 // start the fast mixer
3266 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3267 pid_t tid = mFastMixer->getTid();
3268 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3269 if (err != 0) {
3270 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3271 kPriorityFastMixer, getpid_cached, tid, err);
3272 }
3273
3274#ifdef AUDIO_WATCHDOG
3275 // create and start the watchdog
3276 mAudioWatchdog = new AudioWatchdog();
3277 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3278 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3279 tid = mAudioWatchdog->getTid();
3280 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3281 if (err != 0) {
3282 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3283 kPriorityFastMixer, getpid_cached, tid, err);
3284 }
3285#endif
3286
Eric Laurent81784c32012-11-19 14:55:58 -08003287 }
3288
3289 switch (kUseFastMixer) {
3290 case FastMixer_Never:
3291 case FastMixer_Dynamic:
3292 mNormalSink = mOutputSink;
3293 break;
3294 case FastMixer_Always:
3295 mNormalSink = mPipeSink;
3296 break;
3297 case FastMixer_Static:
3298 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3299 break;
3300 }
3301}
3302
3303AudioFlinger::MixerThread::~MixerThread()
3304{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003305 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003306 FastMixerStateQueue *sq = mFastMixer->sq();
3307 FastMixerState *state = sq->begin();
3308 if (state->mCommand == FastMixerState::COLD_IDLE) {
3309 int32_t old = android_atomic_inc(&mFastMixerFutex);
3310 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003311 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003312 }
3313 }
3314 state->mCommand = FastMixerState::EXIT;
3315 sq->end();
3316 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3317 mFastMixer->join();
3318 // Though the fast mixer thread has exited, it's state queue is still valid.
3319 // We'll use that extract the final state which contains one remaining fast track
3320 // corresponding to our sub-mix.
3321 state = sq->begin();
3322 ALOG_ASSERT(state->mTrackMask == 1);
3323 FastTrack *fastTrack = &state->mFastTracks[0];
3324 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3325 delete fastTrack->mBufferProvider;
3326 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003327 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003328#ifdef AUDIO_WATCHDOG
3329 if (mAudioWatchdog != 0) {
3330 mAudioWatchdog->requestExit();
3331 mAudioWatchdog->requestExitAndWait();
3332 mAudioWatchdog.clear();
3333 }
3334#endif
3335 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003336 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003337 delete mAudioMixer;
3338}
3339
3340
3341uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3342{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003343 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003344 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3345 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3346 }
3347 return latency;
3348}
3349
3350
3351void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3352{
3353 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3354}
3355
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003357{
3358 // FIXME we should only do one push per cycle; confirm this is true
3359 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003360 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003361 FastMixerStateQueue *sq = mFastMixer->sq();
3362 FastMixerState *state = sq->begin();
3363 if (state->mCommand != FastMixerState::MIX_WRITE &&
3364 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3365 if (state->mCommand == FastMixerState::COLD_IDLE) {
3366 int32_t old = android_atomic_inc(&mFastMixerFutex);
3367 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003368 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003369 }
3370#ifdef AUDIO_WATCHDOG
3371 if (mAudioWatchdog != 0) {
3372 mAudioWatchdog->resume();
3373 }
3374#endif
3375 }
3376 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003377#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003378 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003379 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003380#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003381 sq->end();
3382 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3383 if (kUseFastMixer == FastMixer_Dynamic) {
3384 mNormalSink = mPipeSink;
3385 }
3386 } else {
3387 sq->end(false /*didModify*/);
3388 }
3389 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003391}
3392
3393void AudioFlinger::MixerThread::threadLoop_standby()
3394{
3395 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003396 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003397 FastMixerStateQueue *sq = mFastMixer->sq();
3398 FastMixerState *state = sq->begin();
3399 if (!(state->mCommand & FastMixerState::IDLE)) {
3400 state->mCommand = FastMixerState::COLD_IDLE;
3401 state->mColdFutexAddr = &mFastMixerFutex;
3402 state->mColdGen++;
3403 mFastMixerFutex = 0;
3404 sq->end();
3405 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3406 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3407 if (kUseFastMixer == FastMixer_Dynamic) {
3408 mNormalSink = mOutputSink;
3409 }
3410#ifdef AUDIO_WATCHDOG
3411 if (mAudioWatchdog != 0) {
3412 mAudioWatchdog->pause();
3413 }
3414#endif
3415 } else {
3416 sq->end(false /*didModify*/);
3417 }
3418 }
3419 PlaybackThread::threadLoop_standby();
3420}
3421
Eric Laurentbfb1b832013-01-07 09:53:42 -08003422bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3423{
3424 return false;
3425}
3426
3427bool AudioFlinger::PlaybackThread::shouldStandby_l()
3428{
3429 return !mStandby;
3430}
3431
3432bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3433{
3434 Mutex::Autolock _l(mLock);
3435 return waitingAsyncCallback_l();
3436}
3437
Eric Laurent81784c32012-11-19 14:55:58 -08003438// shared by MIXER and DIRECT, overridden by DUPLICATING
3439void AudioFlinger::PlaybackThread::threadLoop_standby()
3440{
3441 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003442 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003443 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003444 // discard any pending drain or write ack by incrementing sequence
3445 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3446 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003447 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003448 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3449 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003450 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003451 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003452}
3453
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003454void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3455{
3456 ALOGV("signal playback thread");
3457 broadcast_l();
3458}
3459
Eric Laurent81784c32012-11-19 14:55:58 -08003460void AudioFlinger::MixerThread::threadLoop_mix()
3461{
3462 // obtain the presentation timestamp of the next output buffer
3463 int64_t pts;
3464 status_t status = INVALID_OPERATION;
3465
3466 if (mNormalSink != 0) {
3467 status = mNormalSink->getNextWriteTimestamp(&pts);
3468 } else {
3469 status = mOutputSink->getNextWriteTimestamp(&pts);
3470 }
3471
3472 if (status != NO_ERROR) {
3473 pts = AudioBufferProvider::kInvalidPTS;
3474 }
3475
3476 // mix buffers...
3477 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003478 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003479 // increase sleep time progressively when application underrun condition clears.
3480 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3481 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3482 // such that we would underrun the audio HAL.
3483 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3484 sleepTimeShift--;
3485 }
3486 sleepTime = 0;
3487 standbyTime = systemTime() + standbyDelay;
3488 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003489
Eric Laurent81784c32012-11-19 14:55:58 -08003490}
3491
3492void AudioFlinger::MixerThread::threadLoop_sleepTime()
3493{
3494 // If no tracks are ready, sleep once for the duration of an output
3495 // buffer size, then write 0s to the output
3496 if (sleepTime == 0) {
3497 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3498 sleepTime = activeSleepTime >> sleepTimeShift;
3499 if (sleepTime < kMinThreadSleepTimeUs) {
3500 sleepTime = kMinThreadSleepTimeUs;
3501 }
3502 // reduce sleep time in case of consecutive application underruns to avoid
3503 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3504 // duration we would end up writing less data than needed by the audio HAL if
3505 // the condition persists.
3506 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3507 sleepTimeShift++;
3508 }
3509 } else {
3510 sleepTime = idleSleepTime;
3511 }
3512 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003513 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3514 // before effects processing or output.
3515 if (mMixerBufferValid) {
3516 memset(mMixerBuffer, 0, mMixerBufferSize);
3517 } else {
3518 memset(mSinkBuffer, 0, mSinkBufferSize);
3519 }
Eric Laurent81784c32012-11-19 14:55:58 -08003520 sleepTime = 0;
3521 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3522 "anticipated start");
3523 }
3524 // TODO add standby time extension fct of effect tail
3525}
3526
3527// prepareTracks_l() must be called with ThreadBase::mLock held
3528AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3529 Vector< sp<Track> > *tracksToRemove)
3530{
3531
3532 mixer_state mixerStatus = MIXER_IDLE;
3533 // find out which tracks need to be processed
3534 size_t count = mActiveTracks.size();
3535 size_t mixedTracks = 0;
3536 size_t tracksWithEffect = 0;
3537 // counts only _active_ fast tracks
3538 size_t fastTracks = 0;
3539 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3540
3541 float masterVolume = mMasterVolume;
3542 bool masterMute = mMasterMute;
3543
3544 if (masterMute) {
3545 masterVolume = 0;
3546 }
3547 // Delegate master volume control to effect in output mix effect chain if needed
3548 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3549 if (chain != 0) {
3550 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3551 chain->setVolume_l(&v, &v);
3552 masterVolume = (float)((v + (1 << 23)) >> 24);
3553 chain.clear();
3554 }
3555
3556 // prepare a new state to push
3557 FastMixerStateQueue *sq = NULL;
3558 FastMixerState *state = NULL;
3559 bool didModify = false;
3560 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003561 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003562 sq = mFastMixer->sq();
3563 state = sq->begin();
3564 }
3565
Andy Hung69aed5f2014-02-25 17:24:40 -08003566 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003567 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003568
Eric Laurent81784c32012-11-19 14:55:58 -08003569 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003570 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003571 if (t == 0) {
3572 continue;
3573 }
3574
3575 // this const just means the local variable doesn't change
3576 Track* const track = t.get();
3577
3578 // process fast tracks
3579 if (track->isFastTrack()) {
3580
3581 // It's theoretically possible (though unlikely) for a fast track to be created
3582 // and then removed within the same normal mix cycle. This is not a problem, as
3583 // the track never becomes active so it's fast mixer slot is never touched.
3584 // The converse, of removing an (active) track and then creating a new track
3585 // at the identical fast mixer slot within the same normal mix cycle,
3586 // is impossible because the slot isn't marked available until the end of each cycle.
3587 int j = track->mFastIndex;
3588 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3589 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3590 FastTrack *fastTrack = &state->mFastTracks[j];
3591
3592 // Determine whether the track is currently in underrun condition,
3593 // and whether it had a recent underrun.
3594 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3595 FastTrackUnderruns underruns = ftDump->mUnderruns;
3596 uint32_t recentFull = (underruns.mBitFields.mFull -
3597 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3598 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3599 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3600 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3601 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3602 uint32_t recentUnderruns = recentPartial + recentEmpty;
3603 track->mObservedUnderruns = underruns;
3604 // don't count underruns that occur while stopping or pausing
3605 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003606 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3607 recentUnderruns > 0) {
3608 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3609 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003610 }
3611
3612 // This is similar to the state machine for normal tracks,
3613 // with a few modifications for fast tracks.
3614 bool isActive = true;
3615 switch (track->mState) {
3616 case TrackBase::STOPPING_1:
3617 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003619 track->mState = TrackBase::STOPPING_2;
3620 }
3621 break;
3622 case TrackBase::PAUSING:
3623 // ramp down is not yet implemented
3624 track->setPaused();
3625 break;
3626 case TrackBase::RESUMING:
3627 // ramp up is not yet implemented
3628 track->mState = TrackBase::ACTIVE;
3629 break;
3630 case TrackBase::ACTIVE:
3631 if (recentFull > 0 || recentPartial > 0) {
3632 // track has provided at least some frames recently: reset retry count
3633 track->mRetryCount = kMaxTrackRetries;
3634 }
3635 if (recentUnderruns == 0) {
3636 // no recent underruns: stay active
3637 break;
3638 }
3639 // there has recently been an underrun of some kind
3640 if (track->sharedBuffer() == 0) {
3641 // were any of the recent underruns "empty" (no frames available)?
3642 if (recentEmpty == 0) {
3643 // no, then ignore the partial underruns as they are allowed indefinitely
3644 break;
3645 }
3646 // there has recently been an "empty" underrun: decrement the retry counter
3647 if (--(track->mRetryCount) > 0) {
3648 break;
3649 }
3650 // indicate to client process that the track was disabled because of underrun;
3651 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003652 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003653 // remove from active list, but state remains ACTIVE [confusing but true]
3654 isActive = false;
3655 break;
3656 }
3657 // fall through
3658 case TrackBase::STOPPING_2:
3659 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003660 case TrackBase::STOPPED:
3661 case TrackBase::FLUSHED: // flush() while active
3662 // Check for presentation complete if track is inactive
3663 // We have consumed all the buffers of this track.
3664 // This would be incomplete if we auto-paused on underrun
3665 {
3666 size_t audioHALFrames =
3667 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3668 size_t framesWritten = mBytesWritten / mFrameSize;
3669 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3670 // track stays in active list until presentation is complete
3671 break;
3672 }
3673 }
3674 if (track->isStopping_2()) {
3675 track->mState = TrackBase::STOPPED;
3676 }
3677 if (track->isStopped()) {
3678 // Can't reset directly, as fast mixer is still polling this track
3679 // track->reset();
3680 // So instead mark this track as needing to be reset after push with ack
3681 resetMask |= 1 << i;
3682 }
3683 isActive = false;
3684 break;
3685 case TrackBase::IDLE:
3686 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003687 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003688 }
3689
3690 if (isActive) {
3691 // was it previously inactive?
3692 if (!(state->mTrackMask & (1 << j))) {
3693 ExtendedAudioBufferProvider *eabp = track;
3694 VolumeProvider *vp = track;
3695 fastTrack->mBufferProvider = eabp;
3696 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003697 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003698 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003699 fastTrack->mGeneration++;
3700 state->mTrackMask |= 1 << j;
3701 didModify = true;
3702 // no acknowledgement required for newly active tracks
3703 }
3704 // cache the combined master volume and stream type volume for fast mixer; this
3705 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003706 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003707 ++fastTracks;
3708 } else {
3709 // was it previously active?
3710 if (state->mTrackMask & (1 << j)) {
3711 fastTrack->mBufferProvider = NULL;
3712 fastTrack->mGeneration++;
3713 state->mTrackMask &= ~(1 << j);
3714 didModify = true;
3715 // If any fast tracks were removed, we must wait for acknowledgement
3716 // because we're about to decrement the last sp<> on those tracks.
3717 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3718 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003719 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003720 }
3721 tracksToRemove->add(track);
3722 // Avoids a misleading display in dumpsys
3723 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3724 }
3725 continue;
3726 }
3727
3728 { // local variable scope to avoid goto warning
3729
3730 audio_track_cblk_t* cblk = track->cblk();
3731
3732 // The first time a track is added we wait
3733 // for all its buffers to be filled before processing it
3734 int name = track->name();
3735 // make sure that we have enough frames to mix one full buffer.
3736 // enforce this condition only once to enable draining the buffer in case the client
3737 // app does not call stop() and relies on underrun to stop:
3738 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3739 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003740 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003741 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003742 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003743
3744 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003745 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003746 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3747 // add frames already consumed but not yet released by the resampler
3748 // because mAudioTrackServerProxy->framesReady() will include these frames
3749 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3750
Eric Laurent81784c32012-11-19 14:55:58 -08003751 uint32_t minFrames = 1;
3752 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3753 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003754 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003755 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003756
3757 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003758 if (ATRACE_ENABLED()) {
3759 // I wish we had formatted trace names
3760 char traceName[16];
3761 strcpy(traceName, "nRdy");
3762 int name = track->name();
3763 if (AudioMixer::TRACK0 <= name &&
3764 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3765 name -= AudioMixer::TRACK0;
3766 traceName[4] = (name / 10) + '0';
3767 traceName[5] = (name % 10) + '0';
3768 } else {
3769 traceName[4] = '?';
3770 traceName[5] = '?';
3771 }
3772 traceName[6] = '\0';
3773 ATRACE_INT(traceName, framesReady);
3774 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003775 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003776 !track->isPaused() && !track->isTerminated())
3777 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003778 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003779
3780 mixedTracks++;
3781
Andy Hung69aed5f2014-02-25 17:24:40 -08003782 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3783 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003784 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003785 if (track->mainBuffer() != mSinkBuffer &&
3786 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003787 if (mEffectBufferEnabled) {
3788 mEffectBufferValid = true; // Later can set directly.
3789 }
Eric Laurent81784c32012-11-19 14:55:58 -08003790 chain = getEffectChain_l(track->sessionId());
3791 // Delegate volume control to effect in track effect chain if needed
3792 if (chain != 0) {
3793 tracksWithEffect++;
3794 } else {
3795 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3796 "session %d",
3797 name, track->sessionId());
3798 }
3799 }
3800
3801
3802 int param = AudioMixer::VOLUME;
3803 if (track->mFillingUpStatus == Track::FS_FILLED) {
3804 // no ramp for the first volume setting
3805 track->mFillingUpStatus = Track::FS_ACTIVE;
3806 if (track->mState == TrackBase::RESUMING) {
3807 track->mState = TrackBase::ACTIVE;
3808 param = AudioMixer::RAMP_VOLUME;
3809 }
3810 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003811 // FIXME should not make a decision based on mServer
3812 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003813 // If the track is stopped before the first frame was mixed,
3814 // do not apply ramp
3815 param = AudioMixer::RAMP_VOLUME;
3816 }
3817
3818 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003819 uint32_t vl, vr; // in U8.24 integer format
3820 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003821 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003822 vl = vr = 0;
3823 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003824 if (track->isPausing()) {
3825 track->setPaused();
3826 }
3827 } else {
3828
3829 // read original volumes with volume control
3830 float typeVolume = mStreamTypes[track->streamType()].volume;
3831 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003832 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003833 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003834 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3835 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003836 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003837 if (vlf > GAIN_FLOAT_UNITY) {
3838 ALOGV("Track left volume out of range: %.3g", vlf);
3839 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003840 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003841 if (vrf > GAIN_FLOAT_UNITY) {
3842 ALOGV("Track right volume out of range: %.3g", vrf);
3843 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003844 }
3845 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003846 vlf *= v;
3847 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003848 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003849 // then derive vl and vr as U8.24 versions for the effect chain
3850 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3851 vl = (uint32_t) (scaleto8_24 * vlf);
3852 vr = (uint32_t) (scaleto8_24 * vrf);
3853 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003854 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003855 // send level comes from shared memory and so may be corrupt
3856 if (sendLevel > MAX_GAIN_INT) {
3857 ALOGV("Track send level out of range: %04X", sendLevel);
3858 sendLevel = MAX_GAIN_INT;
3859 }
Andy Hung6be49402014-05-30 10:42:03 -07003860 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3861 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003862 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003863
Eric Laurent81784c32012-11-19 14:55:58 -08003864 // Delegate volume control to effect in track effect chain if needed
3865 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3866 // Do not ramp volume if volume is controlled by effect
3867 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003868 // Update remaining floating point volume levels
3869 vlf = (float)vl / (1 << 24);
3870 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003871 track->mHasVolumeController = true;
3872 } else {
3873 // force no volume ramp when volume controller was just disabled or removed
3874 // from effect chain to avoid volume spike
3875 if (track->mHasVolumeController) {
3876 param = AudioMixer::VOLUME;
3877 }
3878 track->mHasVolumeController = false;
3879 }
3880
Eric Laurent81784c32012-11-19 14:55:58 -08003881 // XXX: these things DON'T need to be done each time
3882 mAudioMixer->setBufferProvider(name, track);
3883 mAudioMixer->enable(name);
3884
Andy Hung6be49402014-05-30 10:42:03 -07003885 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3886 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3887 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003888 mAudioMixer->setParameter(
3889 name,
3890 AudioMixer::TRACK,
3891 AudioMixer::FORMAT, (void *)track->format());
3892 mAudioMixer->setParameter(
3893 name,
3894 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003895 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003896 mAudioMixer->setParameter(
3897 name,
3898 AudioMixer::TRACK,
3899 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003900 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003901 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003902 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003903 if (reqSampleRate == 0) {
3904 reqSampleRate = mSampleRate;
3905 } else if (reqSampleRate > maxSampleRate) {
3906 reqSampleRate = maxSampleRate;
3907 }
Eric Laurent81784c32012-11-19 14:55:58 -08003908 mAudioMixer->setParameter(
3909 name,
3910 AudioMixer::RESAMPLE,
3911 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003912 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003913
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003914 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003915 mAudioMixer->setParameter(
3916 name,
3917 AudioMixer::TIMESTRETCH,
3918 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003919 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003920
Andy Hung69aed5f2014-02-25 17:24:40 -08003921 /*
3922 * Select the appropriate output buffer for the track.
3923 *
Andy Hung98ef9782014-03-04 14:46:50 -08003924 * Tracks with effects go into their own effects chain buffer
3925 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003926 *
3927 * Other tracks can use mMixerBuffer for higher precision
3928 * channel accumulation. If this buffer is enabled
3929 * (mMixerBufferEnabled true), then selected tracks will accumulate
3930 * into it.
3931 *
3932 */
3933 if (mMixerBufferEnabled
3934 && (track->mainBuffer() == mSinkBuffer
3935 || track->mainBuffer() == mMixerBuffer)) {
3936 mAudioMixer->setParameter(
3937 name,
3938 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003939 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003940 mAudioMixer->setParameter(
3941 name,
3942 AudioMixer::TRACK,
3943 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3944 // TODO: override track->mainBuffer()?
3945 mMixerBufferValid = true;
3946 } else {
3947 mAudioMixer->setParameter(
3948 name,
3949 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003950 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003951 mAudioMixer->setParameter(
3952 name,
3953 AudioMixer::TRACK,
3954 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3955 }
Eric Laurent81784c32012-11-19 14:55:58 -08003956 mAudioMixer->setParameter(
3957 name,
3958 AudioMixer::TRACK,
3959 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3960
3961 // reset retry count
3962 track->mRetryCount = kMaxTrackRetries;
3963
3964 // If one track is ready, set the mixer ready if:
3965 // - the mixer was not ready during previous round OR
3966 // - no other track is not ready
3967 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3968 mixerStatus != MIXER_TRACKS_ENABLED) {
3969 mixerStatus = MIXER_TRACKS_READY;
3970 }
3971 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003972 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003973 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003974 }
Eric Laurent81784c32012-11-19 14:55:58 -08003975 // clear effect chain input buffer if an active track underruns to avoid sending
3976 // previous audio buffer again to effects
3977 chain = getEffectChain_l(track->sessionId());
3978 if (chain != 0) {
3979 chain->clearInputBuffer();
3980 }
3981
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003982 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003983 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3984 track->isStopped() || track->isPaused()) {
3985 // We have consumed all the buffers of this track.
3986 // Remove it from the list of active tracks.
3987 // TODO: use actual buffer filling status instead of latency when available from
3988 // audio HAL
3989 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3990 size_t framesWritten = mBytesWritten / mFrameSize;
3991 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3992 if (track->isStopped()) {
3993 track->reset();
3994 }
3995 tracksToRemove->add(track);
3996 }
3997 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003998 // No buffers for this track. Give it a few chances to
3999 // fill a buffer, then remove it from active list.
4000 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004001 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004002 tracksToRemove->add(track);
4003 // indicate to client process that the track was disabled because of underrun;
4004 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07004005 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08004006 // If one track is not ready, mark the mixer also not ready if:
4007 // - the mixer was ready during previous round OR
4008 // - no other track is ready
4009 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4010 mixerStatus != MIXER_TRACKS_READY) {
4011 mixerStatus = MIXER_TRACKS_ENABLED;
4012 }
4013 }
4014 mAudioMixer->disable(name);
4015 }
4016
4017 } // local variable scope to avoid goto warning
4018track_is_ready: ;
4019
4020 }
4021
4022 // Push the new FastMixer state if necessary
4023 bool pauseAudioWatchdog = false;
4024 if (didModify) {
4025 state->mFastTracksGen++;
4026 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4027 if (kUseFastMixer == FastMixer_Dynamic &&
4028 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4029 state->mCommand = FastMixerState::COLD_IDLE;
4030 state->mColdFutexAddr = &mFastMixerFutex;
4031 state->mColdGen++;
4032 mFastMixerFutex = 0;
4033 if (kUseFastMixer == FastMixer_Dynamic) {
4034 mNormalSink = mOutputSink;
4035 }
4036 // If we go into cold idle, need to wait for acknowledgement
4037 // so that fast mixer stops doing I/O.
4038 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4039 pauseAudioWatchdog = true;
4040 }
Eric Laurent81784c32012-11-19 14:55:58 -08004041 }
4042 if (sq != NULL) {
4043 sq->end(didModify);
4044 sq->push(block);
4045 }
4046#ifdef AUDIO_WATCHDOG
4047 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4048 mAudioWatchdog->pause();
4049 }
4050#endif
4051
4052 // Now perform the deferred reset on fast tracks that have stopped
4053 while (resetMask != 0) {
4054 size_t i = __builtin_ctz(resetMask);
4055 ALOG_ASSERT(i < count);
4056 resetMask &= ~(1 << i);
4057 sp<Track> t = mActiveTracks[i].promote();
4058 if (t == 0) {
4059 continue;
4060 }
4061 Track* track = t.get();
4062 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4063 track->reset();
4064 }
4065
4066 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004067 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004068
Eric Laurent97d547d2014-09-02 14:45:53 -07004069 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4070 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004071 }
4072
4073 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004074 // as long as there are effects we should clear the effects buffer, to avoid
4075 // passing a non-clean buffer to the effect chain
4076 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004077 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004078 // sink or mix buffer must be cleared if all tracks are connected to an
4079 // effect chain as in this case the mixer will not write to the sink or mix buffer
4080 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004081 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4082 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004083 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004084 if (mMixerBufferValid) {
4085 memset(mMixerBuffer, 0, mMixerBufferSize);
4086 // TODO: In testing, mSinkBuffer below need not be cleared because
4087 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4088 // after mixing.
4089 //
4090 // To enforce this guarantee:
4091 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4092 // (mixedTracks == 0 && fastTracks > 0))
4093 // must imply MIXER_TRACKS_READY.
4094 // Later, we may clear buffers regardless, and skip much of this logic.
4095 }
Andy Hung98ef9782014-03-04 14:46:50 -08004096 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004097 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004098 }
4099
4100 // if any fast tracks, then status is ready
4101 mMixerStatusIgnoringFastTracks = mixerStatus;
4102 if (fastTracks > 0) {
4103 mixerStatus = MIXER_TRACKS_READY;
4104 }
4105 return mixerStatus;
4106}
4107
4108// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004109int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4110 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004111{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004112 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004113}
4114
4115// deleteTrackName_l() must be called with ThreadBase::mLock held
4116void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4117{
4118 ALOGV("remove track (%d) and delete from mixer", name);
4119 mAudioMixer->deleteTrackName(name);
4120}
4121
Eric Laurent10351942014-05-08 18:49:52 -07004122// checkForNewParameter_l() must be called with ThreadBase::mLock held
4123bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4124 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004125{
Eric Laurent81784c32012-11-19 14:55:58 -08004126 bool reconfig = false;
4127
Eric Laurent10351942014-05-08 18:49:52 -07004128 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004129
Eric Laurent10351942014-05-08 18:49:52 -07004130 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4131 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004132 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004133 FastMixerStateQueue *sq = mFastMixer->sq();
4134 FastMixerState *state = sq->begin();
4135 if (!(state->mCommand & FastMixerState::IDLE)) {
4136 previousCommand = state->mCommand;
4137 state->mCommand = FastMixerState::HOT_IDLE;
4138 sq->end();
4139 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4140 } else {
4141 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004142 }
Eric Laurent10351942014-05-08 18:49:52 -07004143 }
Eric Laurent81784c32012-11-19 14:55:58 -08004144
Eric Laurent10351942014-05-08 18:49:52 -07004145 AudioParameter param = AudioParameter(keyValuePair);
4146 int value;
4147 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4148 reconfig = true;
4149 }
4150 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004151 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004152 status = BAD_VALUE;
4153 } else {
4154 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004155 reconfig = true;
4156 }
Eric Laurent10351942014-05-08 18:49:52 -07004157 }
4158 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004159 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004160 status = BAD_VALUE;
4161 } else {
4162 // no need to save value, since it's constant
4163 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004164 }
Eric Laurent10351942014-05-08 18:49:52 -07004165 }
4166 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4167 // do not accept frame count changes if tracks are open as the track buffer
4168 // size depends on frame count and correct behavior would not be guaranteed
4169 // if frame count is changed after track creation
4170 if (!mTracks.isEmpty()) {
4171 status = INVALID_OPERATION;
4172 } else {
4173 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004174 }
Eric Laurent10351942014-05-08 18:49:52 -07004175 }
4176 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004177#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004178 // when changing the audio output device, call addBatteryData to notify
4179 // the change
4180 if (mOutDevice != value) {
4181 uint32_t params = 0;
4182 // check whether speaker is on
4183 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4184 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004185 }
Eric Laurent10351942014-05-08 18:49:52 -07004186
4187 audio_devices_t deviceWithoutSpeaker
4188 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4189 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004190 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004191 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4192 }
4193
4194 if (params != 0) {
4195 addBatteryData(params);
4196 }
4197 }
Eric Laurent81784c32012-11-19 14:55:58 -08004198#endif
4199
Eric Laurent10351942014-05-08 18:49:52 -07004200 // forward device change to effects that have requested to be
4201 // aware of attached audio device.
4202 if (value != AUDIO_DEVICE_NONE) {
4203 mOutDevice = value;
4204 for (size_t i = 0; i < mEffectChains.size(); i++) {
4205 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004206 }
4207 }
Eric Laurent10351942014-05-08 18:49:52 -07004208 }
Eric Laurent81784c32012-11-19 14:55:58 -08004209
Eric Laurent10351942014-05-08 18:49:52 -07004210 if (status == NO_ERROR) {
4211 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4212 keyValuePair.string());
4213 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004214 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004215 mStandby = true;
4216 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004217 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004218 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004219 }
Eric Laurent10351942014-05-08 18:49:52 -07004220 if (status == NO_ERROR && reconfig) {
4221 readOutputParameters_l();
4222 delete mAudioMixer;
4223 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4224 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004225 int name = getTrackName_l(mTracks[i]->mChannelMask,
4226 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004227 if (name < 0) {
4228 break;
4229 }
4230 mTracks[i]->mName = name;
4231 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004232 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004233 }
Eric Laurent81784c32012-11-19 14:55:58 -08004234 }
4235
4236 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004237 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004238 FastMixerStateQueue *sq = mFastMixer->sq();
4239 FastMixerState *state = sq->begin();
4240 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4241 state->mCommand = previousCommand;
4242 sq->end();
4243 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4244 }
4245
4246 return reconfig;
4247}
4248
4249
4250void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4251{
4252 const size_t SIZE = 256;
4253 char buffer[SIZE];
4254 String8 result;
4255
4256 PlaybackThread::dumpInternals(fd, args);
4257
Elliott Hughes87cebad2014-05-22 10:14:43 -07004258 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004259
4260 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004261 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004262 copy.dump(fd);
4263
4264#ifdef STATE_QUEUE_DUMP
4265 // Similar for state queue
4266 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4267 observerCopy.dump(fd);
4268 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4269 mutatorCopy.dump(fd);
4270#endif
4271
Glenn Kasten46909e72013-02-26 09:20:22 -08004272#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004273 // Write the tee output to a .wav file
4274 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004275#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004276
4277#ifdef AUDIO_WATCHDOG
4278 if (mAudioWatchdog != 0) {
4279 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4280 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4281 wdCopy.dump(fd);
4282 }
4283#endif
4284}
4285
4286uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4287{
4288 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4289}
4290
4291uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4292{
4293 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4294}
4295
4296void AudioFlinger::MixerThread::cacheParameters_l()
4297{
4298 PlaybackThread::cacheParameters_l();
4299
4300 // FIXME: Relaxed timing because of a certain device that can't meet latency
4301 // Should be reduced to 2x after the vendor fixes the driver issue
4302 // increase threshold again due to low power audio mode. The way this warning
4303 // threshold is calculated and its usefulness should be reconsidered anyway.
4304 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4305}
4306
4307// ----------------------------------------------------------------------------
4308
4309AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4310 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4311 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4312 // mLeftVolFloat, mRightVolFloat
4313{
4314}
4315
Eric Laurentbfb1b832013-01-07 09:53:42 -08004316AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4317 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4318 ThreadBase::type_t type)
4319 : PlaybackThread(audioFlinger, output, id, device, type)
4320 // mLeftVolFloat, mRightVolFloat
4321{
4322}
4323
Eric Laurent81784c32012-11-19 14:55:58 -08004324AudioFlinger::DirectOutputThread::~DirectOutputThread()
4325{
4326}
4327
Eric Laurentbfb1b832013-01-07 09:53:42 -08004328void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4329{
4330 audio_track_cblk_t* cblk = track->cblk();
4331 float left, right;
4332
4333 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4334 left = right = 0;
4335 } else {
4336 float typeVolume = mStreamTypes[track->streamType()].volume;
4337 float v = mMasterVolume * typeVolume;
4338 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004339 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4340 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4341 if (left > GAIN_FLOAT_UNITY) {
4342 left = GAIN_FLOAT_UNITY;
4343 }
4344 left *= v;
4345 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4346 if (right > GAIN_FLOAT_UNITY) {
4347 right = GAIN_FLOAT_UNITY;
4348 }
4349 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004350 }
4351
4352 if (lastTrack) {
4353 if (left != mLeftVolFloat || right != mRightVolFloat) {
4354 mLeftVolFloat = left;
4355 mRightVolFloat = right;
4356
4357 // Convert volumes from float to 8.24
4358 uint32_t vl = (uint32_t)(left * (1 << 24));
4359 uint32_t vr = (uint32_t)(right * (1 << 24));
4360
4361 // Delegate volume control to effect in track effect chain if needed
4362 // only one effect chain can be present on DirectOutputThread, so if
4363 // there is one, the track is connected to it
4364 if (!mEffectChains.isEmpty()) {
4365 mEffectChains[0]->setVolume_l(&vl, &vr);
4366 left = (float)vl / (1 << 24);
4367 right = (float)vr / (1 << 24);
4368 }
4369 if (mOutput->stream->set_volume) {
4370 mOutput->stream->set_volume(mOutput->stream, left, right);
4371 }
4372 }
4373 }
4374}
4375
4376
Eric Laurent81784c32012-11-19 14:55:58 -08004377AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4378 Vector< sp<Track> > *tracksToRemove
4379)
4380{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004381 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004382 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004383 bool doHwPause = false;
4384 bool doHwResume = false;
4385 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004386
4387 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004388 for (size_t i = 0; i < count; i++) {
4389 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004390 // The track died recently
4391 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004392 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004393 }
4394
4395 Track* const track = t.get();
4396 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004397 // Only consider last track started for volume and mixer state control.
4398 // In theory an older track could underrun and restart after the new one starts
4399 // but as we only care about the transition phase between two tracks on a
4400 // direct output, it is not a problem to ignore the underrun case.
4401 sp<Track> l = mLatestActiveTrack.promote();
4402 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004403
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004404 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004405 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004406 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004407 doHwPause = true;
4408 mHwPaused = true;
4409 }
4410 tracksToRemove->add(track);
4411 } else if (track->isFlushPending()) {
4412 track->flushAck();
4413 if (last) {
4414 flushPending = true;
4415 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004416 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004417 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004418 if (last && mHwPaused) {
4419 doHwResume = true;
4420 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004421 }
4422 }
4423
Eric Laurent81784c32012-11-19 14:55:58 -08004424 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004425 // for all its buffers to be filled before processing it.
4426 // Allow draining the buffer in case the client
4427 // app does not call stop() and relies on underrun to stop:
4428 // hence the test on (track->mRetryCount > 1).
4429 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004430 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004431 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4432 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004433 minFrames = mNormalFrameCount;
4434 } else {
4435 minFrames = 1;
4436 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004437
Eric Laurentab5cdba2014-06-09 17:22:27 -07004438 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4439 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004440 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004441 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004442
4443 if (track->mFillingUpStatus == Track::FS_FILLED) {
4444 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004445 // make sure processVolume_l() will apply new volume even if 0
4446 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004447 if (!mHwSupportsPause) {
4448 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004449 }
4450 }
4451
4452 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004453 processVolume_l(track, last);
4454 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004455 // reset retry count
4456 track->mRetryCount = kMaxTrackRetriesDirect;
4457 mActiveTrack = t;
4458 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004459 if (usesHwAvSync() && mHwPaused) {
4460 doHwResume = true;
4461 mHwPaused = false;
4462 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004463 }
Eric Laurent81784c32012-11-19 14:55:58 -08004464 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004465 // clear effect chain input buffer if the last active track started underruns
4466 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004467 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004468 mEffectChains[0]->clearInputBuffer();
4469 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004470 if (track->isStopping_1()) {
4471 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004472 if (last && mHwPaused) {
4473 doHwResume = true;
4474 mHwPaused = false;
4475 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004476 }
4477 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4478 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004479 // We have consumed all the buffers of this track.
4480 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004481 size_t audioHALFrames;
4482 if (audio_is_linear_pcm(mFormat)) {
4483 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4484 } else {
4485 audioHALFrames = 0;
4486 }
4487
Eric Laurent81784c32012-11-19 14:55:58 -08004488 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004489 if (mStandby || !last ||
4490 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004491 if (track->isStopping_2()) {
4492 track->mState = TrackBase::STOPPED;
4493 }
Eric Laurent81784c32012-11-19 14:55:58 -08004494 if (track->isStopped()) {
4495 track->reset();
4496 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004497 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004498 }
4499 } else {
4500 // No buffers for this track. Give it a few chances to
4501 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004502 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004503 if (--(track->mRetryCount) <= 0) {
4504 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004505 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004506 // indicate to client process that the track was disabled because of underrun;
4507 // it will then automatically call start() when data is available
4508 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004509 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004510 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004511 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4512 doHwPause = true;
4513 mHwPaused = true;
4514 }
Eric Laurent81784c32012-11-19 14:55:58 -08004515 }
4516 }
4517 }
4518 }
4519
Eric Laurentd1f69b02014-12-15 14:33:13 -08004520 // if an active track did not command a flush, check for pending flush on stopped tracks
4521 if (!flushPending) {
4522 for (size_t i = 0; i < mTracks.size(); i++) {
4523 if (mTracks[i]->isFlushPending()) {
4524 mTracks[i]->flushAck();
4525 flushPending = true;
4526 }
4527 }
4528 }
4529
4530 // make sure the pause/flush/resume sequence is executed in the right order.
4531 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4532 // before flush and then resume HW. This can happen in case of pause/flush/resume
4533 // if resume is received before pause is executed.
4534 if (mHwSupportsPause && !mStandby &&
4535 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4536 mOutput->stream->pause(mOutput->stream);
4537 }
4538 if (flushPending) {
4539 flushHw_l();
4540 }
4541 if (mHwSupportsPause && !mStandby && doHwResume) {
4542 mOutput->stream->resume(mOutput->stream);
4543 }
Eric Laurent81784c32012-11-19 14:55:58 -08004544 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004545 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004546
4547 return mixerStatus;
4548}
4549
4550void AudioFlinger::DirectOutputThread::threadLoop_mix()
4551{
Eric Laurent81784c32012-11-19 14:55:58 -08004552 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004553 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004554 // output audio to hardware
4555 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004556 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004557 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004558 status_t status = mActiveTrack->getNextBuffer(&buffer);
4559 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004560 memset(curBuf, 0, frameCount * mFrameSize);
4561 break;
4562 }
4563 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4564 frameCount -= buffer.frameCount;
4565 curBuf += buffer.frameCount * mFrameSize;
4566 mActiveTrack->releaseBuffer(&buffer);
4567 }
Andy Hung2098f272014-02-27 14:00:06 -08004568 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004569 sleepTime = 0;
4570 standbyTime = systemTime() + standbyDelay;
4571 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004572}
4573
4574void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4575{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004576 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004577 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004578 sleepTime = idleSleepTime;
4579 return;
4580 }
Eric Laurent81784c32012-11-19 14:55:58 -08004581 if (sleepTime == 0) {
4582 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4583 sleepTime = activeSleepTime;
4584 } else {
4585 sleepTime = idleSleepTime;
4586 }
4587 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004588 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004589 sleepTime = 0;
4590 }
4591}
4592
Eric Laurentd1f69b02014-12-15 14:33:13 -08004593void AudioFlinger::DirectOutputThread::threadLoop_exit()
4594{
4595 {
4596 Mutex::Autolock _l(mLock);
4597 bool flushPending = false;
4598 for (size_t i = 0; i < mTracks.size(); i++) {
4599 if (mTracks[i]->isFlushPending()) {
4600 mTracks[i]->flushAck();
4601 flushPending = true;
4602 }
4603 }
4604 if (flushPending) {
4605 flushHw_l();
4606 }
4607 }
4608 PlaybackThread::threadLoop_exit();
4609}
4610
4611// must be called with thread mutex locked
4612bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4613{
4614 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004615 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004616
4617 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4618 // after a timeout and we will enter standby then.
4619 if (mTracks.size() > 0) {
4620 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004621 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4622 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004623 }
4624
Eric Laurentb369caf2015-03-30 20:51:47 -07004625 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004626}
4627
Eric Laurent81784c32012-11-19 14:55:58 -08004628// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004629int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004630 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004631{
4632 return 0;
4633}
4634
4635// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004636void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004637{
4638}
4639
Eric Laurent10351942014-05-08 18:49:52 -07004640// checkForNewParameter_l() must be called with ThreadBase::mLock held
4641bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4642 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004643{
4644 bool reconfig = false;
4645
Eric Laurent10351942014-05-08 18:49:52 -07004646 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004647
Eric Laurent10351942014-05-08 18:49:52 -07004648 AudioParameter param = AudioParameter(keyValuePair);
4649 int value;
4650 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4651 // forward device change to effects that have requested to be
4652 // aware of attached audio device.
4653 if (value != AUDIO_DEVICE_NONE) {
4654 mOutDevice = value;
4655 for (size_t i = 0; i < mEffectChains.size(); i++) {
4656 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004657 }
4658 }
Eric Laurent81784c32012-11-19 14:55:58 -08004659 }
Eric Laurent10351942014-05-08 18:49:52 -07004660 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4661 // do not accept frame count changes if tracks are open as the track buffer
4662 // size depends on frame count and correct behavior would not be garantied
4663 // if frame count is changed after track creation
4664 if (!mTracks.isEmpty()) {
4665 status = INVALID_OPERATION;
4666 } else {
4667 reconfig = true;
4668 }
4669 }
4670 if (status == NO_ERROR) {
4671 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4672 keyValuePair.string());
4673 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004674 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004675 mStandby = true;
4676 mBytesWritten = 0;
4677 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4678 keyValuePair.string());
4679 }
4680 if (status == NO_ERROR && reconfig) {
4681 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004682 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004683 }
4684 }
4685
Eric Laurent81784c32012-11-19 14:55:58 -08004686 return reconfig;
4687}
4688
4689uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4690{
4691 uint32_t time;
4692 if (audio_is_linear_pcm(mFormat)) {
4693 time = PlaybackThread::activeSleepTimeUs();
4694 } else {
4695 time = 10000;
4696 }
4697 return time;
4698}
4699
4700uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4701{
4702 uint32_t time;
4703 if (audio_is_linear_pcm(mFormat)) {
4704 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4705 } else {
4706 time = 10000;
4707 }
4708 return time;
4709}
4710
4711uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4712{
4713 uint32_t time;
4714 if (audio_is_linear_pcm(mFormat)) {
4715 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4716 } else {
4717 time = 10000;
4718 }
4719 return time;
4720}
4721
4722void AudioFlinger::DirectOutputThread::cacheParameters_l()
4723{
4724 PlaybackThread::cacheParameters_l();
4725
4726 // use shorter standby delay as on normal output to release
4727 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004728 // no delay on outputs with HW A/V sync
4729 if (usesHwAvSync()) {
4730 standbyDelay = 0;
4731 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004732 standbyDelay = microseconds(activeSleepTime*2);
4733 } else {
4734 standbyDelay = kOffloadStandbyDelayNs;
4735 }
Eric Laurent81784c32012-11-19 14:55:58 -08004736}
4737
Eric Laurente659ef42014-09-29 13:06:46 -07004738void AudioFlinger::DirectOutputThread::flushHw_l()
4739{
Phil Burk062e67a2015-02-11 13:40:50 -08004740 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004741 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004742}
4743
Eric Laurent81784c32012-11-19 14:55:58 -08004744// ----------------------------------------------------------------------------
4745
Eric Laurentbfb1b832013-01-07 09:53:42 -08004746AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004747 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004748 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004749 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004750 mWriteAckSequence(0),
4751 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004752{
4753}
4754
4755AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4756{
4757}
4758
4759void AudioFlinger::AsyncCallbackThread::onFirstRef()
4760{
4761 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4762}
4763
4764bool AudioFlinger::AsyncCallbackThread::threadLoop()
4765{
4766 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004767 uint32_t writeAckSequence;
4768 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004769
4770 {
4771 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004772 while (!((mWriteAckSequence & 1) ||
4773 (mDrainSequence & 1) ||
4774 exitPending())) {
4775 mWaitWorkCV.wait(mLock);
4776 }
4777
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 if (exitPending()) {
4779 break;
4780 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004781 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4782 mWriteAckSequence, mDrainSequence);
4783 writeAckSequence = mWriteAckSequence;
4784 mWriteAckSequence &= ~1;
4785 drainSequence = mDrainSequence;
4786 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004787 }
4788 {
Eric Laurent4de95592013-09-26 15:28:21 -07004789 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4790 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004791 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004792 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004793 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004794 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004795 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004796 }
4797 }
4798 }
4799 }
4800 return false;
4801}
4802
4803void AudioFlinger::AsyncCallbackThread::exit()
4804{
4805 ALOGV("AsyncCallbackThread::exit");
4806 Mutex::Autolock _l(mLock);
4807 requestExit();
4808 mWaitWorkCV.broadcast();
4809}
4810
Eric Laurent3b4529e2013-09-05 18:09:19 -07004811void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004812{
4813 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004814 // bit 0 is cleared
4815 mWriteAckSequence = sequence << 1;
4816}
4817
4818void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4819{
4820 Mutex::Autolock _l(mLock);
4821 // ignore unexpected callbacks
4822 if (mWriteAckSequence & 2) {
4823 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004824 mWaitWorkCV.signal();
4825 }
4826}
4827
Eric Laurent3b4529e2013-09-05 18:09:19 -07004828void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004829{
4830 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004831 // bit 0 is cleared
4832 mDrainSequence = sequence << 1;
4833}
4834
4835void AudioFlinger::AsyncCallbackThread::resetDraining()
4836{
4837 Mutex::Autolock _l(mLock);
4838 // ignore unexpected callbacks
4839 if (mDrainSequence & 2) {
4840 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004841 mWaitWorkCV.signal();
4842 }
4843}
4844
4845
4846// ----------------------------------------------------------------------------
4847AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4848 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4849 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004850 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004851{
Eric Laurentfd477972013-10-25 18:10:40 -07004852 //FIXME: mStandby should be set to true by ThreadBase constructor
4853 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004854}
4855
Eric Laurentbfb1b832013-01-07 09:53:42 -08004856void AudioFlinger::OffloadThread::threadLoop_exit()
4857{
4858 if (mFlushPending || mHwPaused) {
4859 // If a flush is pending or track was paused, just discard buffered data
4860 flushHw_l();
4861 } else {
4862 mMixerStatus = MIXER_DRAIN_ALL;
4863 threadLoop_drain();
4864 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004865 if (mUseAsyncWrite) {
4866 ALOG_ASSERT(mCallbackThread != 0);
4867 mCallbackThread->exit();
4868 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004869 PlaybackThread::threadLoop_exit();
4870}
4871
4872AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4873 Vector< sp<Track> > *tracksToRemove
4874)
4875{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004876 size_t count = mActiveTracks.size();
4877
4878 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004879 bool doHwPause = false;
4880 bool doHwResume = false;
4881
Eric Laurentede6c3b2013-09-19 14:37:46 -07004882 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4883
Eric Laurentbfb1b832013-01-07 09:53:42 -08004884 // find out which tracks need to be processed
4885 for (size_t i = 0; i < count; i++) {
4886 sp<Track> t = mActiveTracks[i].promote();
4887 // The track died recently
4888 if (t == 0) {
4889 continue;
4890 }
4891 Track* const track = t.get();
4892 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004893 // Only consider last track started for volume and mixer state control.
4894 // In theory an older track could underrun and restart after the new one starts
4895 // but as we only care about the transition phase between two tracks on a
4896 // direct output, it is not a problem to ignore the underrun case.
4897 sp<Track> l = mLatestActiveTrack.promote();
4898 bool last = l.get() == track;
4899
Haynes Mathew George7844f672014-01-15 12:32:55 -08004900 if (track->isInvalid()) {
4901 ALOGW("An invalidated track shouldn't be in active list");
4902 tracksToRemove->add(track);
4903 continue;
4904 }
4905
4906 if (track->mState == TrackBase::IDLE) {
4907 ALOGW("An idle track shouldn't be in active list");
4908 continue;
4909 }
4910
Eric Laurentbfb1b832013-01-07 09:53:42 -08004911 if (track->isPausing()) {
4912 track->setPaused();
4913 if (last) {
4914 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004915 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004916 mHwPaused = true;
4917 }
4918 // If we were part way through writing the mixbuffer to
4919 // the HAL we must save this until we resume
4920 // BUG - this will be wrong if a different track is made active,
4921 // in that case we want to discard the pending data in the
4922 // mixbuffer and tell the client to present it again when the
4923 // track is resumed
4924 mPausedWriteLength = mCurrentWriteLength;
4925 mPausedBytesRemaining = mBytesRemaining;
4926 mBytesRemaining = 0; // stop writing
4927 }
4928 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004929 } else if (track->isFlushPending()) {
4930 track->flushAck();
4931 if (last) {
4932 mFlushPending = true;
4933 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004934 } else if (track->isResumePending()){
4935 track->resumeAck();
4936 if (last) {
4937 if (mPausedBytesRemaining) {
4938 // Need to continue write that was interrupted
4939 mCurrentWriteLength = mPausedWriteLength;
4940 mBytesRemaining = mPausedBytesRemaining;
4941 mPausedBytesRemaining = 0;
4942 }
4943 if (mHwPaused) {
4944 doHwResume = true;
4945 mHwPaused = false;
4946 // threadLoop_mix() will handle the case that we need to
4947 // resume an interrupted write
4948 }
4949 // enable write to audio HAL
4950 sleepTime = 0;
4951
4952 // Do not handle new data in this iteration even if track->framesReady()
4953 mixerStatus = MIXER_TRACKS_ENABLED;
4954 }
4955 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004956 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004957 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958 if (track->mFillingUpStatus == Track::FS_FILLED) {
4959 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004960 // make sure processVolume_l() will apply new volume even if 0
4961 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004962 }
4963
4964 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004965 sp<Track> previousTrack = mPreviousTrack.promote();
4966 if (previousTrack != 0) {
4967 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004968 // Flush any data still being written from last track
4969 mBytesRemaining = 0;
4970 if (mPausedBytesRemaining) {
4971 // Last track was paused so we also need to flush saved
4972 // mixbuffer state and invalidate track so that it will
4973 // re-submit that unwritten data when it is next resumed
4974 mPausedBytesRemaining = 0;
4975 // Invalidate is a bit drastic - would be more efficient
4976 // to have a flag to tell client that some of the
4977 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004978 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004979 }
4980 // flush data already sent to the DSP if changing audio session as audio
4981 // comes from a different source. Also invalidate previous track to force a
4982 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004983 if (previousTrack->sessionId() != track->sessionId()) {
4984 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004985 }
4986 }
4987 }
4988 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004989 // reset retry count
4990 track->mRetryCount = kMaxTrackRetriesOffload;
4991 mActiveTrack = t;
4992 mixerStatus = MIXER_TRACKS_READY;
4993 }
4994 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004995 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004996 if (track->isStopping_1()) {
4997 // Hardware buffer can hold a large amount of audio so we must
4998 // wait for all current track's data to drain before we say
4999 // that the track is stopped.
5000 if (mBytesRemaining == 0) {
5001 // Only start draining when all data in mixbuffer
5002 // has been written
5003 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5004 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005005 // do not drain if no data was ever sent to HAL (mStandby == true)
5006 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005007 // do not modify drain sequence if we are already draining. This happens
5008 // when resuming from pause after drain.
5009 if ((mDrainSequence & 1) == 0) {
5010 sleepTime = 0;
5011 standbyTime = systemTime() + standbyDelay;
5012 mixerStatus = MIXER_DRAIN_TRACK;
5013 mDrainSequence += 2;
5014 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005015 if (mHwPaused) {
5016 // It is possible to move from PAUSED to STOPPING_1 without
5017 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005018 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005019 mHwPaused = false;
5020 }
5021 }
5022 }
5023 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005024 // Drain has completed or we are in standby, signal presentation complete
5025 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005026 track->mState = TrackBase::STOPPED;
5027 size_t audioHALFrames =
5028 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5029 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005030 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005031 track->presentationComplete(framesWritten, audioHALFrames);
5032 track->reset();
5033 tracksToRemove->add(track);
5034 }
5035 } else {
5036 // No buffers for this track. Give it a few chances to
5037 // fill a buffer, then remove it from active list.
5038 if (--(track->mRetryCount) <= 0) {
5039 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5040 track->name());
5041 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005042 // indicate to client process that the track was disabled because of underrun;
5043 // it will then automatically call start() when data is available
5044 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005045 } else if (last){
5046 mixerStatus = MIXER_TRACKS_ENABLED;
5047 }
5048 }
5049 }
5050 // compute volume for this track
5051 processVolume_l(track, last);
5052 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005053
Eric Laurentea0fade2013-10-04 16:23:48 -07005054 // make sure the pause/flush/resume sequence is executed in the right order.
5055 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5056 // before flush and then resume HW. This can happen in case of pause/flush/resume
5057 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005058 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005059 mOutput->stream->pause(mOutput->stream);
5060 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005061 if (mFlushPending) {
5062 flushHw_l();
5063 mFlushPending = false;
5064 }
Eric Laurentfd477972013-10-25 18:10:40 -07005065 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005066 mOutput->stream->resume(mOutput->stream);
5067 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005068
Eric Laurentbfb1b832013-01-07 09:53:42 -08005069 // remove all the tracks that need to be...
5070 removeTracks_l(*tracksToRemove);
5071
5072 return mixerStatus;
5073}
5074
Eric Laurentbfb1b832013-01-07 09:53:42 -08005075// must be called with thread mutex locked
5076bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5077{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005078 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5079 mWriteAckSequence, mDrainSequence);
5080 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005081 return true;
5082 }
5083 return false;
5084}
5085
Eric Laurentbfb1b832013-01-07 09:53:42 -08005086bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5087{
5088 Mutex::Autolock _l(mLock);
5089 return waitingAsyncCallback_l();
5090}
5091
5092void AudioFlinger::OffloadThread::flushHw_l()
5093{
Eric Laurente659ef42014-09-29 13:06:46 -07005094 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005095 // Flush anything still waiting in the mixbuffer
5096 mCurrentWriteLength = 0;
5097 mBytesRemaining = 0;
5098 mPausedWriteLength = 0;
5099 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005100
Eric Laurentbfb1b832013-01-07 09:53:42 -08005101 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005102 // discard any pending drain or write ack by incrementing sequence
5103 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5104 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005105 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005106 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5107 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005108 }
5109}
5110
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005111void AudioFlinger::OffloadThread::onAddNewTrack_l()
5112{
5113 sp<Track> previousTrack = mPreviousTrack.promote();
5114 sp<Track> latestTrack = mLatestActiveTrack.promote();
5115
5116 if (previousTrack != 0 && latestTrack != 0 &&
5117 (previousTrack->sessionId() != latestTrack->sessionId())) {
5118 mFlushPending = true;
5119 }
5120 PlaybackThread::onAddNewTrack_l();
5121}
5122
Eric Laurentbfb1b832013-01-07 09:53:42 -08005123// ----------------------------------------------------------------------------
5124
Eric Laurent81784c32012-11-19 14:55:58 -08005125AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5126 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
5127 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5128 DUPLICATING),
5129 mWaitTimeMs(UINT_MAX)
5130{
5131 addOutputTrack(mainThread);
5132}
5133
5134AudioFlinger::DuplicatingThread::~DuplicatingThread()
5135{
5136 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5137 mOutputTracks[i]->destroy();
5138 }
5139}
5140
5141void AudioFlinger::DuplicatingThread::threadLoop_mix()
5142{
5143 // mix buffers...
5144 if (outputsReady(outputTracks)) {
5145 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5146 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005147 if (mMixerBufferValid) {
5148 memset(mMixerBuffer, 0, mMixerBufferSize);
5149 } else {
5150 memset(mSinkBuffer, 0, mSinkBufferSize);
5151 }
Eric Laurent81784c32012-11-19 14:55:58 -08005152 }
5153 sleepTime = 0;
5154 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005155 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005156 standbyTime = systemTime() + standbyDelay;
5157}
5158
5159void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5160{
5161 if (sleepTime == 0) {
5162 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5163 sleepTime = activeSleepTime;
5164 } else {
5165 sleepTime = idleSleepTime;
5166 }
5167 } else if (mBytesWritten != 0) {
5168 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5169 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005170 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005171 } else {
5172 // flush remaining overflow buffers in output tracks
5173 writeFrames = 0;
5174 }
5175 sleepTime = 0;
5176 }
5177}
5178
Eric Laurentbfb1b832013-01-07 09:53:42 -08005179ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005180{
5181 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005182 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005183 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005184 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005185 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005186}
5187
5188void AudioFlinger::DuplicatingThread::threadLoop_standby()
5189{
5190 // DuplicatingThread implements standby by stopping all tracks
5191 for (size_t i = 0; i < outputTracks.size(); i++) {
5192 outputTracks[i]->stop();
5193 }
5194}
5195
5196void AudioFlinger::DuplicatingThread::saveOutputTracks()
5197{
5198 outputTracks = mOutputTracks;
5199}
5200
5201void AudioFlinger::DuplicatingThread::clearOutputTracks()
5202{
5203 outputTracks.clear();
5204}
5205
5206void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5207{
5208 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005209 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5210 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5211 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5212 const size_t frameCount =
5213 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5214 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5215 // from different OutputTracks and their associated MixerThreads (e.g. one may
5216 // nearly empty and the other may be dropping data).
5217
5218 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005219 this,
5220 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005221 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005222 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005223 frameCount,
5224 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005225 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005226 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005227 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005228 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005229 updateWaitTime_l();
5230 }
5231}
5232
5233void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5234{
5235 Mutex::Autolock _l(mLock);
5236 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5237 if (mOutputTracks[i]->thread() == thread) {
5238 mOutputTracks[i]->destroy();
5239 mOutputTracks.removeAt(i);
5240 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005241 if (thread->getOutput() == mOutput) {
5242 mOutput = NULL;
5243 }
Eric Laurent81784c32012-11-19 14:55:58 -08005244 return;
5245 }
5246 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005247 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005248}
5249
5250// caller must hold mLock
5251void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5252{
5253 mWaitTimeMs = UINT_MAX;
5254 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5255 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5256 if (strong != 0) {
5257 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5258 if (waitTimeMs < mWaitTimeMs) {
5259 mWaitTimeMs = waitTimeMs;
5260 }
5261 }
5262 }
5263}
5264
5265
5266bool AudioFlinger::DuplicatingThread::outputsReady(
5267 const SortedVector< sp<OutputTrack> > &outputTracks)
5268{
5269 for (size_t i = 0; i < outputTracks.size(); i++) {
5270 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5271 if (thread == 0) {
5272 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5273 outputTracks[i].get());
5274 return false;
5275 }
5276 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5277 // see note at standby() declaration
5278 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5279 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5280 thread.get());
5281 return false;
5282 }
5283 }
5284 return true;
5285}
5286
5287uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5288{
5289 return (mWaitTimeMs * 1000) / 2;
5290}
5291
5292void AudioFlinger::DuplicatingThread::cacheParameters_l()
5293{
5294 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5295 updateWaitTime_l();
5296
5297 MixerThread::cacheParameters_l();
5298}
5299
5300// ----------------------------------------------------------------------------
5301// Record
5302// ----------------------------------------------------------------------------
5303
5304AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5305 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005306 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005307 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005308 audio_devices_t inDevice
5309#ifdef TEE_SINK
5310 , const sp<NBAIO_Sink>& teeSink
5311#endif
5312 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005313 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005314 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005315 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005316 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005317#ifdef TEE_SINK
5318 , mTeeSink(teeSink)
5319#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005320 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5321 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005322 // mFastCapture below
5323 , mFastCaptureFutex(0)
5324 // mInputSource
5325 // mPipeSink
5326 // mPipeSource
5327 , mPipeFramesP2(0)
5328 // mPipeMemory
5329 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005330 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005331{
Glenn Kastend7dca052015-03-05 16:05:54 -08005332 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5333 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005334
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005335 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005336
5337 // create an NBAIO source for the HAL input stream, and negotiate
5338 mInputSource = new AudioStreamInSource(input->stream);
5339 size_t numCounterOffers = 0;
5340 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5341 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5342 ALOG_ASSERT(index == 0);
5343
5344 // initialize fast capture depending on configuration
5345 bool initFastCapture;
5346 switch (kUseFastCapture) {
5347 case FastCapture_Never:
5348 initFastCapture = false;
5349 break;
5350 case FastCapture_Always:
5351 initFastCapture = true;
5352 break;
5353 case FastCapture_Static:
5354 uint32_t primaryOutputSampleRate;
5355 {
5356 AutoMutex _l(audioFlinger->mHardwareLock);
5357 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5358 }
5359 initFastCapture =
5360 // either capture sample rate is same as (a reasonable) primary output sample rate
Andy Hungdb4c0312015-05-06 08:46:52 -07005361 ((isMusicRate(primaryOutputSampleRate) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005362 (mSampleRate == primaryOutputSampleRate)) ||
5363 // or primary output sample rate is unknown, and capture sample rate is reasonable
5364 ((primaryOutputSampleRate == 0) &&
Andy Hungdb4c0312015-05-06 08:46:52 -07005365 isMusicRate(mSampleRate))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005366 // and the buffer size is < 12 ms
5367 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005368 break;
5369 // case FastCapture_Dynamic:
5370 }
5371
5372 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005373 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005374 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005375 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005376 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5377 void *pipeBuffer;
5378 const sp<MemoryDealer> roHeap(readOnlyHeap());
5379 sp<IMemory> pipeMemory;
5380 if ((roHeap == 0) ||
5381 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5382 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5383 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5384 goto failed;
5385 }
5386 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5387 memset(pipeBuffer, 0, pipeSize);
5388 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5389 const NBAIO_Format offers[1] = {format};
5390 size_t numCounterOffers = 0;
5391 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5392 ALOG_ASSERT(index == 0);
5393 mPipeSink = pipe;
5394 PipeReader *pipeReader = new PipeReader(*pipe);
5395 numCounterOffers = 0;
5396 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5397 ALOG_ASSERT(index == 0);
5398 mPipeSource = pipeReader;
5399 mPipeFramesP2 = pipeFramesP2;
5400 mPipeMemory = pipeMemory;
5401
5402 // create fast capture
5403 mFastCapture = new FastCapture();
5404 FastCaptureStateQueue *sq = mFastCapture->sq();
5405#ifdef STATE_QUEUE_DUMP
5406 // FIXME
5407#endif
5408 FastCaptureState *state = sq->begin();
5409 state->mCblk = NULL;
5410 state->mInputSource = mInputSource.get();
5411 state->mInputSourceGen++;
5412 state->mPipeSink = pipe;
5413 state->mPipeSinkGen++;
5414 state->mFrameCount = mFrameCount;
5415 state->mCommand = FastCaptureState::COLD_IDLE;
5416 // already done in constructor initialization list
5417 //mFastCaptureFutex = 0;
5418 state->mColdFutexAddr = &mFastCaptureFutex;
5419 state->mColdGen++;
5420 state->mDumpState = &mFastCaptureDumpState;
5421#ifdef TEE_SINK
5422 // FIXME
5423#endif
5424 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5425 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5426 sq->end();
5427 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5428
5429 // start the fast capture
5430 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5431 pid_t tid = mFastCapture->getTid();
5432 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5433 if (err != 0) {
5434 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5435 kPriorityFastCapture, getpid_cached, tid, err);
5436 }
5437
5438#ifdef AUDIO_WATCHDOG
5439 // FIXME
5440#endif
5441
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005442 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005443 }
5444failed: ;
5445
5446 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005447}
5448
Eric Laurent81784c32012-11-19 14:55:58 -08005449AudioFlinger::RecordThread::~RecordThread()
5450{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005451 if (mFastCapture != 0) {
5452 FastCaptureStateQueue *sq = mFastCapture->sq();
5453 FastCaptureState *state = sq->begin();
5454 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5455 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5456 if (old == -1) {
5457 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5458 }
5459 }
5460 state->mCommand = FastCaptureState::EXIT;
5461 sq->end();
5462 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5463 mFastCapture->join();
5464 mFastCapture.clear();
5465 }
5466 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005467 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005468 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005469}
5470
5471void AudioFlinger::RecordThread::onFirstRef()
5472{
Glenn Kastend7dca052015-03-05 16:05:54 -08005473 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005474}
5475
Eric Laurent81784c32012-11-19 14:55:58 -08005476bool AudioFlinger::RecordThread::threadLoop()
5477{
Eric Laurent81784c32012-11-19 14:55:58 -08005478 nsecs_t lastWarning = 0;
5479
5480 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005481
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005482reacquire_wakelock:
5483 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005484 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005485 {
5486 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005487 size_t size = mActiveTracks.size();
5488 activeTracksGen = mActiveTracksGen;
5489 if (size > 0) {
5490 // FIXME an arbitrary choice
5491 activeTrack = mActiveTracks[0];
5492 acquireWakeLock_l(activeTrack->uid());
5493 if (size > 1) {
5494 SortedVector<int> tmp;
5495 for (size_t i = 0; i < size; i++) {
5496 tmp.add(mActiveTracks[i]->uid());
5497 }
5498 updateWakeLockUids_l(tmp);
5499 }
5500 } else {
5501 acquireWakeLock_l(-1);
5502 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005503 }
5504
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005505 // used to request a deferred sleep, to be executed later while mutex is unlocked
5506 uint32_t sleepUs = 0;
5507
5508 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005509 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005510 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005511
Glenn Kasten5edadd42013-08-14 16:30:49 -07005512 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005513 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005514 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005515 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005516 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005517 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005518 }
5519
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005520 // activeTracks accumulates a copy of a subset of mActiveTracks
5521 Vector< sp<RecordTrack> > activeTracks;
5522
Glenn Kasten735f45f2014-08-18 15:51:59 -07005523 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005524 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005525
Glenn Kasten735f45f2014-08-18 15:51:59 -07005526 // reference to a fast track which is about to be removed
5527 sp<RecordTrack> fastTrackToRemove;
5528
Eric Laurent81784c32012-11-19 14:55:58 -08005529 { // scope for mLock
5530 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005531
Eric Laurent021cf962014-05-13 10:18:14 -07005532 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005533
Eric Laurent000a4192014-01-29 15:17:32 -08005534 // check exitPending here because checkForNewParameters_l() and
5535 // checkForNewParameters_l() can temporarily release mLock
5536 if (exitPending()) {
5537 break;
5538 }
5539
Glenn Kasten2b806402013-11-20 16:37:38 -08005540 // if no active track(s), then standby and release wakelock
5541 size_t size = mActiveTracks.size();
5542 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005543 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005544 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005545 releaseWakeLock_l();
5546 ALOGV("RecordThread: loop stopping");
5547 // go to sleep
5548 mWaitWorkCV.wait(mLock);
5549 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005550 goto reacquire_wakelock;
5551 }
5552
Glenn Kasten2b806402013-11-20 16:37:38 -08005553 if (mActiveTracksGen != activeTracksGen) {
5554 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005555 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005556 for (size_t i = 0; i < size; i++) {
5557 tmp.add(mActiveTracks[i]->uid());
5558 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005559 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005560 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005561
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005562 bool doBroadcast = false;
5563 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005564
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005565 activeTrack = mActiveTracks[i];
5566 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005567 if (activeTrack->isFastTrack()) {
5568 ALOG_ASSERT(fastTrackToRemove == 0);
5569 fastTrackToRemove = activeTrack;
5570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005571 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005572 mActiveTracks.remove(activeTrack);
5573 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005574 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005575 continue;
5576 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005577
5578 TrackBase::track_state activeTrackState = activeTrack->mState;
5579 switch (activeTrackState) {
5580
5581 case TrackBase::PAUSING:
5582 mActiveTracks.remove(activeTrack);
5583 mActiveTracksGen++;
5584 doBroadcast = true;
5585 size--;
5586 continue;
5587
5588 case TrackBase::STARTING_1:
5589 sleepUs = 10000;
5590 i++;
5591 continue;
5592
5593 case TrackBase::STARTING_2:
5594 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005595 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005596 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005597 break;
5598
5599 case TrackBase::ACTIVE:
5600 break;
5601
5602 case TrackBase::IDLE:
5603 i++;
5604 continue;
5605
5606 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005607 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005608 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005609
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005610 activeTracks.add(activeTrack);
5611 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005612
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005613 if (activeTrack->isFastTrack()) {
5614 ALOG_ASSERT(!mFastTrackAvail);
5615 ALOG_ASSERT(fastTrack == 0);
5616 fastTrack = activeTrack;
5617 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005618 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005619 if (doBroadcast) {
5620 mStartStopCond.broadcast();
5621 }
5622
5623 // sleep if there are no active tracks to process
5624 if (activeTracks.size() == 0) {
5625 if (sleepUs == 0) {
5626 sleepUs = kRecordThreadSleepUs;
5627 }
5628 continue;
5629 }
5630 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005631
Eric Laurent81784c32012-11-19 14:55:58 -08005632 lockEffectChains_l(effectChains);
5633 }
5634
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005635 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005636
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005637 size_t size = effectChains.size();
5638 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005639 // thread mutex is not locked, but effect chain is locked
5640 effectChains[i]->process_l();
5641 }
5642
Glenn Kasten735f45f2014-08-18 15:51:59 -07005643 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005644 if (mFastCapture != 0) {
5645 FastCaptureStateQueue *sq = mFastCapture->sq();
5646 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005647 bool didModify = false;
5648 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005649 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5650 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5651 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5652 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5653 if (old == -1) {
5654 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5655 }
5656 }
5657 state->mCommand = FastCaptureState::READ_WRITE;
5658#if 0 // FIXME
5659 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005660 FastThreadDumpState::kSamplingNforLowRamDevice :
5661 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005662#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005663 didModify = true;
5664 }
5665 audio_track_cblk_t *cblkOld = state->mCblk;
5666 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5667 if (cblkNew != cblkOld) {
5668 state->mCblk = cblkNew;
5669 // block until acked if removing a fast track
5670 if (cblkOld != NULL) {
5671 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5672 }
5673 didModify = true;
5674 }
5675 sq->end(didModify);
5676 if (didModify) {
5677 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005678#if 0
5679 if (kUseFastCapture == FastCapture_Dynamic) {
5680 mNormalSource = mPipeSource;
5681 }
5682#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005683 }
5684 }
5685
Glenn Kasten735f45f2014-08-18 15:51:59 -07005686 // now run the fast track destructor with thread mutex unlocked
5687 fastTrackToRemove.clear();
5688
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005689 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5690 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5691 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5692 // If destination is non-contiguous, first read past the nominal end of buffer, then
5693 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005694
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005695 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005696 ssize_t framesRead;
5697
5698 // If an NBAIO source is present, use it to read the normal capture's data
5699 if (mPipeSource != 0) {
5700 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005701 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005702 framesToRead, AudioBufferProvider::kInvalidPTS);
5703 if (framesRead == 0) {
5704 // since pipe is non-blocking, simulate blocking input
5705 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5706 }
5707 // otherwise use the HAL / AudioStreamIn directly
5708 } else {
5709 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005710 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005711 if (bytesRead < 0) {
5712 framesRead = bytesRead;
5713 } else {
5714 framesRead = bytesRead / mFrameSize;
5715 }
5716 }
5717
5718 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5719 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005720 // Force input into standby so that it tries to recover at next read attempt
5721 inputStandBy();
5722 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005723 }
5724 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005725 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005726 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005727 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005728
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005729 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005730 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005731 }
5732 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005733 {
5734 size_t part1 = mRsmpInFramesP2 - rear;
5735 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005736 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005737 (framesRead - part1) * mFrameSize);
5738 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005739 }
5740 rear = mRsmpInRear += framesRead;
5741
5742 size = activeTracks.size();
5743 // loop over each active track
5744 for (size_t i = 0; i < size; i++) {
5745 activeTrack = activeTracks[i];
5746
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005747 // skip fast tracks, as those are handled directly by FastCapture
5748 if (activeTrack->isFastTrack()) {
5749 continue;
5750 }
5751
Andy Hung73c02e42015-03-29 01:13:58 -07005752 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005753 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5754
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005755 enum {
5756 OVERRUN_UNKNOWN,
5757 OVERRUN_TRUE,
5758 OVERRUN_FALSE
5759 } overrun = OVERRUN_UNKNOWN;
5760
5761 // loop over getNextBuffer to handle circular sink
5762 for (;;) {
5763
5764 activeTrack->mSink.frameCount = ~0;
5765 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5766 size_t framesOut = activeTrack->mSink.frameCount;
5767 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5768
Andy Hung73c02e42015-03-29 01:13:58 -07005769 // check available frames and handle overrun conditions
5770 // if the record track isn't draining fast enough.
5771 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005772 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005773 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5774 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005775 overrun = OVERRUN_TRUE;
5776 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005777 if (framesOut == 0 || framesIn == 0) {
5778 break;
5779 }
5780
Andy Hung6770c6f2015-04-07 13:43:36 -07005781 // Don't allow framesOut to be larger than what is possible with resampling
5782 // from framesIn.
5783 // This isn't strictly necessary but helps limit buffer resizing in
5784 // RecordBufferConverter. TODO: remove when no longer needed.
5785 framesOut = min(framesOut,
5786 destinationFramesPossible(
5787 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005788 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5789 framesOut = activeTrack->mRecordBufferConverter->convert(
5790 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005791
5792 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5793 overrun = OVERRUN_FALSE;
5794 }
5795
5796 if (activeTrack->mFramesToDrop == 0) {
5797 if (framesOut > 0) {
5798 activeTrack->mSink.frameCount = framesOut;
5799 activeTrack->releaseBuffer(&activeTrack->mSink);
5800 }
5801 } else {
5802 // FIXME could do a partial drop of framesOut
5803 if (activeTrack->mFramesToDrop > 0) {
5804 activeTrack->mFramesToDrop -= framesOut;
5805 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005806 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 }
5808 } else {
5809 activeTrack->mFramesToDrop += framesOut;
5810 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5811 activeTrack->mSyncStartEvent->isCancelled()) {
5812 ALOGW("Synced record %s, session %d, trigger session %d",
5813 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5814 activeTrack->sessionId(),
5815 (activeTrack->mSyncStartEvent != 0) ?
5816 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005817 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005818 }
5819 }
5820 }
5821
5822 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005823 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005824 }
5825 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005826
5827 switch (overrun) {
5828 case OVERRUN_TRUE:
5829 // client isn't retrieving buffers fast enough
5830 if (!activeTrack->setOverflow()) {
5831 nsecs_t now = systemTime();
5832 // FIXME should lastWarning per track?
5833 if ((now - lastWarning) > kWarningThrottleNs) {
5834 ALOGW("RecordThread: buffer overflow");
5835 lastWarning = now;
5836 }
5837 }
5838 break;
5839 case OVERRUN_FALSE:
5840 activeTrack->clearOverflow();
5841 break;
5842 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005843 break;
5844 }
5845
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005846 }
5847
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005848unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005849 // enable changes in effect chain
5850 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005851 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005852 }
5853
Glenn Kasten93e471f2013-08-19 08:40:07 -07005854 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005855
5856 {
5857 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005858 for (size_t i = 0; i < mTracks.size(); i++) {
5859 sp<RecordTrack> track = mTracks[i];
5860 track->invalidate();
5861 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005862 mActiveTracks.clear();
5863 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005864 mStartStopCond.broadcast();
5865 }
5866
5867 releaseWakeLock();
5868
5869 ALOGV("RecordThread %p exiting", this);
5870 return false;
5871}
5872
Glenn Kasten93e471f2013-08-19 08:40:07 -07005873void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005874{
5875 if (!mStandby) {
5876 inputStandBy();
5877 mStandby = true;
5878 }
5879}
5880
5881void AudioFlinger::RecordThread::inputStandBy()
5882{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005883 // Idle the fast capture if it's currently running
5884 if (mFastCapture != 0) {
5885 FastCaptureStateQueue *sq = mFastCapture->sq();
5886 FastCaptureState *state = sq->begin();
5887 if (!(state->mCommand & FastCaptureState::IDLE)) {
5888 state->mCommand = FastCaptureState::COLD_IDLE;
5889 state->mColdFutexAddr = &mFastCaptureFutex;
5890 state->mColdGen++;
5891 mFastCaptureFutex = 0;
5892 sq->end();
5893 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5894 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5895#if 0
5896 if (kUseFastCapture == FastCapture_Dynamic) {
5897 // FIXME
5898 }
5899#endif
5900#ifdef AUDIO_WATCHDOG
5901 // FIXME
5902#endif
5903 } else {
5904 sq->end(false /*didModify*/);
5905 }
5906 }
Eric Laurent81784c32012-11-19 14:55:58 -08005907 mInput->stream->common.standby(&mInput->stream->common);
5908}
5909
Glenn Kasten05997e22014-03-13 15:08:33 -07005910// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005911sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005912 const sp<AudioFlinger::Client>& client,
5913 uint32_t sampleRate,
5914 audio_format_t format,
5915 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005916 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005917 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005918 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005919 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005920 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005921 pid_t tid,
5922 status_t *status)
5923{
Glenn Kasten74935e42013-12-19 08:56:45 -08005924 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005925 sp<RecordTrack> track;
5926 status_t lStatus;
5927
Glenn Kasten90e58b12013-07-31 16:16:02 -07005928 // client expresses a preference for FAST, but we get the final say
5929 if (*flags & IAudioFlinger::TRACK_FAST) {
5930 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005931 // we formerly checked for a callback handler (non-0 tid),
5932 // but that is no longer required for TRANSFER_OBTAIN mode
5933 //
Glenn Kasten74105912014-07-03 12:28:53 -07005934 // frame count is not specified, or is exactly the pipe depth
5935 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005936 // PCM data
5937 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005938 // native format
5939 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005940 // native channel mask
5941 (channelMask == mChannelMask) &&
5942 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005943 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005944 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005945 hasFastCapture() &&
5946 // there are sufficient fast track slots available
5947 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005948 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005949 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005950 frameCount, mFrameCount);
5951 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005952 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5953 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005954 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005955 frameCount, mFrameCount, mPipeFramesP2,
5956 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5957 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005958 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005959 }
5960 }
5961
5962 // compute track buffer size in frames, and suggest the notification frame count
5963 if (*flags & IAudioFlinger::TRACK_FAST) {
5964 // fast track: frame count is exactly the pipe depth
5965 frameCount = mPipeFramesP2;
5966 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5967 *notificationFrames = mFrameCount;
5968 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005969 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5970 // or 20 ms if there is a fast capture
5971 // TODO This could be a roundupRatio inline, and const
5972 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5973 * sampleRate + mSampleRate - 1) / mSampleRate;
5974 // minimum number of notification periods is at least kMinNotifications,
5975 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5976 static const size_t kMinNotifications = 3;
5977 static const uint32_t kMinMs = 30;
5978 // TODO This could be a roundupRatio inline
5979 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5980 // TODO This could be a roundupRatio inline
5981 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5982 maxNotificationFrames;
5983 const size_t minFrameCount = maxNotificationFrames *
5984 max(kMinNotifications, minNotificationsByMs);
5985 frameCount = max(frameCount, minFrameCount);
5986 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5987 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005988 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005989 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005990 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005991
Glenn Kasten15e57982013-09-24 11:52:37 -07005992 lStatus = initCheck();
5993 if (lStatus != NO_ERROR) {
5994 ALOGE("createRecordTrack_l() audio driver not initialized");
5995 goto Exit;
5996 }
Eric Laurent81784c32012-11-19 14:55:58 -08005997
5998 { // scope for mLock
5999 Mutex::Autolock _l(mLock);
6000
6001 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006002 format, channelMask, frameCount, NULL, sessionId, uid,
6003 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006004
Glenn Kasten03003332013-08-06 15:40:54 -07006005 lStatus = track->initCheck();
6006 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006007 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006008 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006009 goto Exit;
6010 }
6011 mTracks.add(track);
6012
6013 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6014 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6015 mAudioFlinger->btNrecIsOff();
6016 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6017 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006018
6019 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6020 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6021 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6022 // so ask activity manager to do this on our behalf
6023 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6024 }
Eric Laurent81784c32012-11-19 14:55:58 -08006025 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006026
Eric Laurent81784c32012-11-19 14:55:58 -08006027 lStatus = NO_ERROR;
6028
6029Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006030 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006031 return track;
6032}
6033
6034status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6035 AudioSystem::sync_event_t event,
6036 int triggerSession)
6037{
6038 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6039 sp<ThreadBase> strongMe = this;
6040 status_t status = NO_ERROR;
6041
6042 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006043 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006044 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006046 triggerSession,
6047 recordTrack->sessionId(),
6048 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006049 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006050 // Sync event can be cancelled by the trigger session if the track is not in a
6051 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006052 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006053 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006054 } else {
6055 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006056 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006057 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006058 }
6059 }
6060
6061 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006062 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006063 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006064 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6065 if (recordTrack->mState == TrackBase::PAUSING) {
6066 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006067 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 } else {
6069 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006070 }
6071 return status;
6072 }
6073
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006074 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6075 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6076 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006077 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006078 mActiveTracks.add(recordTrack);
6079 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006080 status_t status = NO_ERROR;
6081 if (recordTrack->isExternalTrack()) {
6082 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006083 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006084 mLock.lock();
6085 // FIXME should verify that recordTrack is still in mActiveTracks
6086 if (status != NO_ERROR) {
6087 mActiveTracks.remove(recordTrack);
6088 mActiveTracksGen++;
6089 recordTrack->clearSyncStartEvent();
6090 ALOGV("RecordThread::start error %d", status);
6091 return status;
6092 }
Eric Laurent81784c32012-11-19 14:55:58 -08006093 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006094 // Catch up with current buffer indices if thread is already running.
6095 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6096 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6097 // see previously buffered data before it called start(), but with greater risk of overrun.
6098
Andy Hung73c02e42015-03-29 01:13:58 -07006099 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006100 // clear any converter state as new data will be discontinuous
6101 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006102 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006103 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006104 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006105 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006106 ALOGV("Record failed to start");
6107 status = BAD_VALUE;
6108 goto startError;
6109 }
Eric Laurent81784c32012-11-19 14:55:58 -08006110 return status;
6111 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006112
Eric Laurent81784c32012-11-19 14:55:58 -08006113startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006114 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006115 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006116 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006117 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006118 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006119 return status;
6120}
6121
Eric Laurent81784c32012-11-19 14:55:58 -08006122void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6123{
6124 sp<SyncEvent> strongEvent = event.promote();
6125
6126 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006127 sp<RefBase> ptr = strongEvent->cookie().promote();
6128 if (ptr != 0) {
6129 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6130 recordTrack->handleSyncStartEvent(strongEvent);
6131 }
Eric Laurent81784c32012-11-19 14:55:58 -08006132 }
6133}
6134
Glenn Kastena8356f62013-07-25 14:37:52 -07006135bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006136 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006137 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006138 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006139 return false;
6140 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006141 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006142 recordTrack->mState = TrackBase::PAUSING;
6143 // do not wait for mStartStopCond if exiting
6144 if (exitPending()) {
6145 return true;
6146 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006147 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006148 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006149 // if we have been restarted, recordTrack is in mActiveTracks here
6150 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006151 ALOGV("Record stopped OK");
6152 return true;
6153 }
6154 return false;
6155}
6156
Glenn Kasten0f11b512014-01-31 16:18:54 -08006157bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006158{
6159 return false;
6160}
6161
Glenn Kasten0f11b512014-01-31 16:18:54 -08006162status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006163{
6164#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6165 if (!isValidSyncEvent(event)) {
6166 return BAD_VALUE;
6167 }
6168
6169 int eventSession = event->triggerSession();
6170 status_t ret = NAME_NOT_FOUND;
6171
6172 Mutex::Autolock _l(mLock);
6173
6174 for (size_t i = 0; i < mTracks.size(); i++) {
6175 sp<RecordTrack> track = mTracks[i];
6176 if (eventSession == track->sessionId()) {
6177 (void) track->setSyncEvent(event);
6178 ret = NO_ERROR;
6179 }
6180 }
6181 return ret;
6182#else
6183 return BAD_VALUE;
6184#endif
6185}
6186
6187// destroyTrack_l() must be called with ThreadBase::mLock held
6188void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6189{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006190 track->terminate();
6191 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006192 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006193 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006194 removeTrack_l(track);
6195 }
6196}
6197
6198void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6199{
6200 mTracks.remove(track);
6201 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006202 if (track->isFastTrack()) {
6203 ALOG_ASSERT(!mFastTrackAvail);
6204 mFastTrackAvail = true;
6205 }
Eric Laurent81784c32012-11-19 14:55:58 -08006206}
6207
6208void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6209{
6210 dumpInternals(fd, args);
6211 dumpTracks(fd, args);
6212 dumpEffectChains(fd, args);
6213}
6214
6215void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6216{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006217 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006218
Glenn Kasten44182c22015-03-05 17:12:23 -08006219 dumpBase(fd, args);
6220
6221 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006222 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006223 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006224 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006225 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006226
6227 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6228 const FastCaptureDumpState copy(mFastCaptureDumpState);
6229 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006230}
6231
Glenn Kasten0f11b512014-01-31 16:18:54 -08006232void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006233{
6234 const size_t SIZE = 256;
6235 char buffer[SIZE];
6236 String8 result;
6237
Marco Nelissenb2208842014-02-07 14:00:50 -08006238 size_t numtracks = mTracks.size();
6239 size_t numactive = mActiveTracks.size();
6240 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006241 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006242 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006243 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006244 RecordTrack::appendDumpHeader(result);
6245 for (size_t i = 0; i < numtracks ; ++i) {
6246 sp<RecordTrack> track = mTracks[i];
6247 if (track != 0) {
6248 bool active = mActiveTracks.indexOf(track) >= 0;
6249 if (active) {
6250 numactiveseen++;
6251 }
6252 track->dump(buffer, SIZE, active);
6253 result.append(buffer);
6254 }
Eric Laurent81784c32012-11-19 14:55:58 -08006255 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006256 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006257 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006258 }
6259
Marco Nelissenb2208842014-02-07 14:00:50 -08006260 if (numactiveseen != numactive) {
6261 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6262 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006263 result.append(buffer);
6264 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006265 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006266 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006267 if (mTracks.indexOf(track) < 0) {
6268 track->dump(buffer, SIZE, true);
6269 result.append(buffer);
6270 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006271 }
Eric Laurent81784c32012-11-19 14:55:58 -08006272
6273 }
6274 write(fd, result.string(), result.size());
6275}
6276
Andy Hung73c02e42015-03-29 01:13:58 -07006277
6278void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6279{
6280 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6281 RecordThread *recordThread = (RecordThread *) threadBase.get();
6282 mRsmpInFront = recordThread->mRsmpInRear;
6283 mRsmpInUnrel = 0;
6284}
6285
6286void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6287 size_t *framesAvailable, bool *hasOverrun)
6288{
6289 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6290 RecordThread *recordThread = (RecordThread *) threadBase.get();
6291 const int32_t rear = recordThread->mRsmpInRear;
6292 const int32_t front = mRsmpInFront;
6293 const ssize_t filled = rear - front;
6294
6295 size_t framesIn;
6296 bool overrun = false;
6297 if (filled < 0) {
6298 // should not happen, but treat like a massive overrun and re-sync
6299 framesIn = 0;
6300 mRsmpInFront = rear;
6301 overrun = true;
6302 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6303 framesIn = (size_t) filled;
6304 } else {
6305 // client is not keeping up with server, but give it latest data
6306 framesIn = recordThread->mRsmpInFrames;
6307 mRsmpInFront = /* front = */ rear - framesIn;
6308 overrun = true;
6309 }
6310 if (framesAvailable != NULL) {
6311 *framesAvailable = framesIn;
6312 }
6313 if (hasOverrun != NULL) {
6314 *hasOverrun = overrun;
6315 }
6316}
6317
Eric Laurent81784c32012-11-19 14:55:58 -08006318// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006319status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6320 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006321{
Andy Hung73c02e42015-03-29 01:13:58 -07006322 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006323 if (threadBase == 0) {
6324 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006325 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006326 return NOT_ENOUGH_DATA;
6327 }
6328 RecordThread *recordThread = (RecordThread *) threadBase.get();
6329 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006330 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006331 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006332 // FIXME should not be P2 (don't want to increase latency)
6333 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006334 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006335 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006336 front &= recordThread->mRsmpInFramesP2 - 1;
6337 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006338 if (part1 > (size_t) filled) {
6339 part1 = filled;
6340 }
6341 size_t ask = buffer->frameCount;
6342 ALOG_ASSERT(ask > 0);
6343 if (part1 > ask) {
6344 part1 = ask;
6345 }
6346 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006347 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006348 buffer->raw = NULL;
6349 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006350 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006351 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006352 }
6353
Andy Hung57446612015-04-19 23:56:46 -07006354 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006355 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006356 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006357 return NO_ERROR;
6358}
6359
6360// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006361void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6362 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006363{
Glenn Kasten85948432013-08-19 12:09:05 -07006364 size_t stepCount = buffer->frameCount;
6365 if (stepCount == 0) {
6366 return;
6367 }
Andy Hung73c02e42015-03-29 01:13:58 -07006368 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6369 mRsmpInUnrel -= stepCount;
6370 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006371 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006372 buffer->frameCount = 0;
6373}
6374
Andy Hung97a893e2015-03-29 01:03:07 -07006375AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6376 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6377 uint32_t srcSampleRate,
6378 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6379 uint32_t dstSampleRate) :
6380 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6381 // mSrcFormat
6382 // mSrcSampleRate
6383 // mDstChannelMask
6384 // mDstFormat
6385 // mDstSampleRate
6386 // mSrcChannelCount
6387 // mDstChannelCount
6388 // mDstFrameSize
6389 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006390 mResampler(NULL),
6391 mIsLegacyDownmix(false),
6392 mIsLegacyUpmix(false),
6393 mRequiresFloat(false),
6394 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006395{
6396 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6397 dstChannelMask, dstFormat, dstSampleRate);
6398}
6399
6400AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6401 free(mBuf);
6402 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006403 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006404}
6405
6406size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6407 AudioBufferProvider *provider, size_t frames)
6408{
Andy Hungd330ee42015-04-20 13:23:41 -07006409 if (mInputConverterProvider != NULL) {
6410 mInputConverterProvider->setBufferProvider(provider);
6411 provider = mInputConverterProvider;
6412 }
6413
6414 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006415 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6416 mSrcSampleRate, mSrcFormat, mDstFormat);
6417
6418 AudioBufferProvider::Buffer buffer;
6419 for (size_t i = frames; i > 0; ) {
6420 buffer.frameCount = i;
6421 status_t status = provider->getNextBuffer(&buffer, 0);
6422 if (status != OK || buffer.frameCount == 0) {
6423 frames -= i; // cannot fill request.
6424 break;
6425 }
Andy Hungd330ee42015-04-20 13:23:41 -07006426 // format convert to destination buffer
6427 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006428
6429 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6430 i -= buffer.frameCount;
6431 provider->releaseBuffer(&buffer);
6432 }
6433 } else {
6434 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6435 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6436
Andy Hungd330ee42015-04-20 13:23:41 -07006437 // reallocate buffer if needed
6438 if (mBufFrameSize != 0 && mBufFrames < frames) {
6439 free(mBuf);
6440 mBufFrames = frames;
6441 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6442 }
Andy Hung97a893e2015-03-29 01:03:07 -07006443 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006444 memset(mBuf, 0, frames * mBufFrameSize);
6445 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6446 // format convert to destination buffer
6447 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006448 }
6449 return frames;
6450}
6451
6452status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6453 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6454 uint32_t srcSampleRate,
6455 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6456 uint32_t dstSampleRate)
6457{
6458 // quick evaluation if there is any change.
6459 if (mSrcFormat == srcFormat
6460 && mSrcChannelMask == srcChannelMask
6461 && mSrcSampleRate == srcSampleRate
6462 && mDstFormat == dstFormat
6463 && mDstChannelMask == dstChannelMask
6464 && mDstSampleRate == dstSampleRate) {
6465 return NO_ERROR;
6466 }
6467
Andy Hungdb4c0312015-05-06 08:46:52 -07006468 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6469 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6470 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006471 const bool valid =
6472 audio_is_input_channel(srcChannelMask)
6473 && audio_is_input_channel(dstChannelMask)
6474 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6475 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6476 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6477 ; // no upsampling checks for now
6478 if (!valid) {
6479 return BAD_VALUE;
6480 }
6481
6482 mSrcFormat = srcFormat;
6483 mSrcChannelMask = srcChannelMask;
6484 mSrcSampleRate = srcSampleRate;
6485 mDstFormat = dstFormat;
6486 mDstChannelMask = dstChannelMask;
6487 mDstSampleRate = dstSampleRate;
6488
6489 // compute derived parameters
6490 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6491 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6492 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6493
Andy Hungd330ee42015-04-20 13:23:41 -07006494 // do we need to resample?
6495 delete mResampler;
6496 mResampler = NULL;
6497 if (mSrcSampleRate != mDstSampleRate) {
6498 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6499 mSrcChannelCount, mDstSampleRate);
6500 mResampler->setSampleRate(mSrcSampleRate);
6501 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6502 }
6503
6504 // are we running legacy channel conversion modes?
6505 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6506 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6507 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6508 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6509 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6510 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6511
6512 // do we need to process in float?
6513 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6514
6515 // do we need a staging buffer to convert for destination (we can still optimize this)?
6516 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6517 if (mResampler != NULL) {
6518 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6519 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6520 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6521 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6522 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006523 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6524 } else {
6525 mBufFrameSize = 0;
6526 }
6527 mBufFrames = 0; // force the buffer to be resized.
6528
Andy Hungd330ee42015-04-20 13:23:41 -07006529 // do we need an input converter buffer provider to give us float?
6530 delete mInputConverterProvider;
6531 mInputConverterProvider = NULL;
6532 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6533 mInputConverterProvider = new ReformatBufferProvider(
6534 audio_channel_count_from_in_mask(mSrcChannelMask),
6535 mSrcFormat,
6536 AUDIO_FORMAT_PCM_FLOAT,
6537 256 /* provider buffer frame count */);
6538 }
6539
6540 // do we need a remixer to do channel mask conversion
6541 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6542 (void) memcpy_by_index_array_initialization_from_channel_mask(
6543 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006544 }
6545 return NO_ERROR;
6546}
6547
Andy Hungd330ee42015-04-20 13:23:41 -07006548void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6549 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006550{
Andy Hungd330ee42015-04-20 13:23:41 -07006551 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006552 if (mBufFrameSize != 0 && mBufFrames < frames) {
6553 free(mBuf);
6554 mBufFrames = frames;
6555 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6556 }
Andy Hungd330ee42015-04-20 13:23:41 -07006557 // do we need to do legacy upmix and downmix?
6558 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006559 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006560 if (mIsLegacyUpmix) {
6561 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6562 (const float *)src, frames);
6563 } else /*mIsLegacyDownmix */ {
6564 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6565 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006566 }
Andy Hungd330ee42015-04-20 13:23:41 -07006567 if (mBuf != NULL) {
6568 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6569 frames * mDstChannelCount);
6570 }
6571 return;
6572 }
6573 // do we need to do channel mask conversion?
6574 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006575 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006576 memcpy_by_index_array(dstBuf, mDstChannelCount,
6577 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6578 if (dstBuf == dst) {
6579 return; // format is the same
6580 }
6581 }
6582 // convert to destination buffer
6583 const void *convertBuf = mBuf != NULL ? mBuf : src;
6584 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6585 frames * mDstChannelCount);
6586}
6587
6588void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6589 void *dst, /*not-a-const*/ void *src, size_t frames)
6590{
6591 // src buffer format is ALWAYS float when entering this routine
6592 if (mIsLegacyUpmix) {
6593 ; // mono to stereo already handled by resampler
6594 } else if (mIsLegacyDownmix
6595 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6596 // the resampler outputs stereo for mono input channel (a feature?)
6597 // must convert to mono
6598 downmix_to_mono_float_from_stereo_float((float *)src,
6599 (const float *)src, frames);
6600 } else if (mSrcChannelMask != mDstChannelMask) {
6601 // convert to mono channel again for channel mask conversion (could be skipped
6602 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006603 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006604 downmix_to_mono_float_from_stereo_float((float *)src,
6605 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006606 }
Andy Hungd330ee42015-04-20 13:23:41 -07006607 // convert to destination format (in place, OK as float is larger than other types)
6608 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6609 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6610 frames * mSrcChannelCount);
6611 }
6612 // channel convert and save to dst
6613 memcpy_by_index_array(dst, mDstChannelCount,
6614 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6615 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006616 }
Andy Hungd330ee42015-04-20 13:23:41 -07006617 // convert to destination format and save to dst
6618 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6619 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006620}
6621
Eric Laurent10351942014-05-08 18:49:52 -07006622bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6623 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006624{
6625 bool reconfig = false;
6626
Eric Laurent10351942014-05-08 18:49:52 -07006627 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006628
Eric Laurent10351942014-05-08 18:49:52 -07006629 audio_format_t reqFormat = mFormat;
6630 uint32_t samplingRate = mSampleRate;
6631 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006632 // possible that we are > 2 channels, use channel index mask
6633 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6634 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6635 }
Eric Laurent10351942014-05-08 18:49:52 -07006636
6637 AudioParameter param = AudioParameter(keyValuePair);
6638 int value;
6639 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6640 // channel count change can be requested. Do we mandate the first client defines the
6641 // HAL sampling rate and channel count or do we allow changes on the fly?
6642 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6643 samplingRate = value;
6644 reconfig = true;
6645 }
6646 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006647 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006648 status = BAD_VALUE;
6649 } else {
6650 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006651 reconfig = true;
6652 }
Eric Laurent10351942014-05-08 18:49:52 -07006653 }
6654 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6655 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006656 if (!audio_is_input_channel(mask) ||
6657 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006658 status = BAD_VALUE;
6659 } else {
6660 channelMask = mask;
6661 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006662 }
Eric Laurent10351942014-05-08 18:49:52 -07006663 }
6664 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6665 // do not accept frame count changes if tracks are open as the track buffer
6666 // size depends on frame count and correct behavior would not be guaranteed
6667 // if frame count is changed after track creation
6668 if (mActiveTracks.size() > 0) {
6669 status = INVALID_OPERATION;
6670 } else {
6671 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006672 }
Eric Laurent10351942014-05-08 18:49:52 -07006673 }
6674 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6675 // forward device change to effects that have requested to be
6676 // aware of attached audio device.
6677 for (size_t i = 0; i < mEffectChains.size(); i++) {
6678 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006679 }
Eric Laurent81784c32012-11-19 14:55:58 -08006680
Eric Laurent10351942014-05-08 18:49:52 -07006681 // store input device and output device but do not forward output device to audio HAL.
6682 // Note that status is ignored by the caller for output device
6683 // (see AudioFlinger::setParameters()
6684 if (audio_is_output_devices(value)) {
6685 mOutDevice = value;
6686 status = BAD_VALUE;
6687 } else {
6688 mInDevice = value;
6689 // disable AEC and NS if the device is a BT SCO headset supporting those
6690 // pre processings
6691 if (mTracks.size() > 0) {
6692 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6693 mAudioFlinger->btNrecIsOff();
6694 for (size_t i = 0; i < mTracks.size(); i++) {
6695 sp<RecordTrack> track = mTracks[i];
6696 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6697 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006698 }
6699 }
6700 }
Eric Laurent10351942014-05-08 18:49:52 -07006701 }
6702 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6703 mAudioSource != (audio_source_t)value) {
6704 // forward device change to effects that have requested to be
6705 // aware of attached audio device.
6706 for (size_t i = 0; i < mEffectChains.size(); i++) {
6707 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006708 }
Eric Laurent10351942014-05-08 18:49:52 -07006709 mAudioSource = (audio_source_t)value;
6710 }
Glenn Kastene198c362013-08-13 09:13:36 -07006711
Eric Laurent10351942014-05-08 18:49:52 -07006712 if (status == NO_ERROR) {
6713 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6714 keyValuePair.string());
6715 if (status == INVALID_OPERATION) {
6716 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006717 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6718 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006719 }
6720 if (reconfig) {
6721 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006722 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6723 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006724 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006725 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006726 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07006727 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006728 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006729 }
Eric Laurent10351942014-05-08 18:49:52 -07006730 if (status == NO_ERROR) {
6731 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006732 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006733 }
6734 }
Eric Laurent81784c32012-11-19 14:55:58 -08006735 }
Eric Laurent10351942014-05-08 18:49:52 -07006736
Eric Laurent81784c32012-11-19 14:55:58 -08006737 return reconfig;
6738}
6739
6740String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6741{
Eric Laurent81784c32012-11-19 14:55:58 -08006742 Mutex::Autolock _l(mLock);
6743 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006744 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006745 }
6746
Glenn Kastend8ea6992013-07-16 14:17:15 -07006747 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6748 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006749 free(s);
6750 return out_s8;
6751}
6752
Eric Laurent73e26b62015-04-27 16:55:58 -07006753void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6754 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6755
6756 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006757
6758 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006759 case AUDIO_INPUT_OPENED:
6760 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006761 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006762 desc->mChannelMask = mChannelMask;
6763 desc->mSamplingRate = mSampleRate;
6764 desc->mFormat = mFormat;
6765 desc->mFrameCount = mFrameCount;
6766 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006767 break;
6768
Eric Laurent73e26b62015-04-27 16:55:58 -07006769 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006770 default:
6771 break;
6772 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006773 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006774}
6775
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006776void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006777{
Eric Laurent81784c32012-11-19 14:55:58 -08006778 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6779 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006780 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006781 if (mChannelCount > FCC_8) {
6782 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6783 }
Andy Hung463be252014-07-10 16:56:07 -07006784 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6785 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006786 if (!audio_is_linear_pcm(mFormat)) {
6787 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006788 }
Eric Laurent665470b2014-07-03 16:37:08 -07006789 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006790 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6791 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006792 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006793 // 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 -07006794 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006795 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006796 // A larger value should allow more old data to be read after a track calls start(),
6797 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006798 //
6799 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006800 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006801 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006802 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006803
6804 // TODO optimize audio capture buffer sizes ...
6805 // Here we calculate the size of the sliding buffer used as a source
6806 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6807 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6808 // be better to have it derived from the pipe depth in the long term.
6809 // The current value is higher than necessary. However it should not add to latency.
6810
Glenn Kasten85948432013-08-19 12:09:05 -07006811 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006812 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006813
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006814 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6815 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006816}
6817
Glenn Kasten5f972c02014-01-13 09:59:31 -08006818uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006819{
6820 Mutex::Autolock _l(mLock);
6821 if (initCheck() != NO_ERROR) {
6822 return 0;
6823 }
6824
6825 return mInput->stream->get_input_frames_lost(mInput->stream);
6826}
6827
6828uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6829{
6830 Mutex::Autolock _l(mLock);
6831 uint32_t result = 0;
6832 if (getEffectChain_l(sessionId) != 0) {
6833 result = EFFECT_SESSION;
6834 }
6835
6836 for (size_t i = 0; i < mTracks.size(); ++i) {
6837 if (sessionId == mTracks[i]->sessionId()) {
6838 result |= TRACK_SESSION;
6839 break;
6840 }
6841 }
6842
6843 return result;
6844}
6845
6846KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6847{
6848 KeyedVector<int, bool> ids;
6849 Mutex::Autolock _l(mLock);
6850 for (size_t j = 0; j < mTracks.size(); ++j) {
6851 sp<RecordThread::RecordTrack> track = mTracks[j];
6852 int sessionId = track->sessionId();
6853 if (ids.indexOfKey(sessionId) < 0) {
6854 ids.add(sessionId, true);
6855 }
6856 }
6857 return ids;
6858}
6859
6860AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6861{
6862 Mutex::Autolock _l(mLock);
6863 AudioStreamIn *input = mInput;
6864 mInput = NULL;
6865 return input;
6866}
6867
6868// this method must always be called either with ThreadBase mLock held or inside the thread loop
6869audio_stream_t* AudioFlinger::RecordThread::stream() const
6870{
6871 if (mInput == NULL) {
6872 return NULL;
6873 }
6874 return &mInput->stream->common;
6875}
6876
6877status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6878{
6879 // only one chain per input thread
6880 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006881 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006882 return INVALID_OPERATION;
6883 }
6884 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006885 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006886 chain->setInBuffer(NULL);
6887 chain->setOutBuffer(NULL);
6888
6889 checkSuspendOnAddEffectChain_l(chain);
6890
Eric Laurent1b928682014-10-02 19:41:47 -07006891 // make sure enabled pre processing effects state is communicated to the HAL as we
6892 // just moved them to a new input stream.
6893 chain->syncHalEffectsState();
6894
Eric Laurent81784c32012-11-19 14:55:58 -08006895 mEffectChains.add(chain);
6896
6897 return NO_ERROR;
6898}
6899
6900size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6901{
6902 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6903 ALOGW_IF(mEffectChains.size() != 1,
6904 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6905 chain.get(), mEffectChains.size(), this);
6906 if (mEffectChains.size() == 1) {
6907 mEffectChains.removeAt(0);
6908 }
6909 return 0;
6910}
6911
Eric Laurent1c333e22014-05-20 10:48:17 -07006912status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6913 audio_patch_handle_t *handle)
6914{
6915 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006916
6917 // store new device and send to effects
6918 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07006919 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07006920 for (size_t i = 0; i < mEffectChains.size(); i++) {
6921 mEffectChains[i]->setDevice_l(mInDevice);
6922 }
6923
6924 // disable AEC and NS if the device is a BT SCO headset supporting those
6925 // pre processings
6926 if (mTracks.size() > 0) {
6927 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6928 mAudioFlinger->btNrecIsOff();
6929 for (size_t i = 0; i < mTracks.size(); i++) {
6930 sp<RecordTrack> track = mTracks[i];
6931 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6932 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6933 }
6934 }
6935
6936 // store new source and send to effects
6937 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6938 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07006939 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07006940 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07006941 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006942 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006943
Eric Laurent054d9d32015-04-24 08:48:48 -07006944 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006945 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6946 status = hwDevice->create_audio_patch(hwDevice,
6947 patch->num_sources,
6948 patch->sources,
6949 patch->num_sinks,
6950 patch->sinks,
6951 handle);
6952 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006953 char *address;
6954 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
6955 address = audio_device_address_to_parameter(
6956 patch->sources[0].ext.device.type,
6957 patch->sources[0].ext.device.address);
6958 } else {
6959 address = (char *)calloc(1, 1);
6960 }
6961 AudioParameter param = AudioParameter(String8(address));
6962 free(address);
6963 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
6964 (int)patch->sources[0].ext.device.type);
6965 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
6966 (int)patch->sinks[0].ext.mix.usecase.source);
6967 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6968 param.toString().string());
6969 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07006970 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006971
Eric Laurent296fb132015-05-01 11:38:42 -07006972 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
6973
Eric Laurent1c333e22014-05-20 10:48:17 -07006974 return status;
6975}
6976
6977status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6978{
6979 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006980
6981 mInDevice = AUDIO_DEVICE_NONE;
6982
Eric Laurent1c333e22014-05-20 10:48:17 -07006983 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6984 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6985 status = hwDevice->release_audio_patch(hwDevice, handle);
6986 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006987 AudioParameter param;
6988 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
6989 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6990 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07006991 }
6992 return status;
6993}
6994
Eric Laurent83b88082014-06-20 18:31:16 -07006995void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6996{
6997 Mutex::Autolock _l(mLock);
6998 mTracks.add(record);
6999}
7000
7001void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7002{
7003 Mutex::Autolock _l(mLock);
7004 destroyTrack_l(record);
7005}
7006
7007void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7008{
7009 ThreadBase::getAudioPortConfig(config);
7010 config->role = AUDIO_PORT_ROLE_SINK;
7011 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7012 config->ext.mix.usecase.source = mAudioSource;
7013}
Eric Laurent1c333e22014-05-20 10:48:17 -07007014
Glenn Kasten63238ef2015-03-02 15:50:29 -08007015} // namespace android