blob: 2c4d8014eac65b51ed3da80cf7929be50a0b948b [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
63#include "SchedulingPolicyService.h"
64
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Eric Laurent972a1732013-09-04 09:42:59 -0700132// Offloaded output thread standby delay: allows track transition without going to standby
133static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// Whether to use fast mixer
136static const enum {
137 FastMixer_Never, // never initialize or use: for debugging only
138 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
139 // normal mixer multiplier is 1
140 FastMixer_Static, // initialize if needed, then use all the time if initialized,
141 // multiplier is calculated based on min & max normal mixer buffer size
142 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
143 // multiplier is calculated based on min & max normal mixer buffer size
144 // FIXME for FastMixer_Dynamic:
145 // Supporting this option will require fixing HALs that can't handle large writes.
146 // For example, one HAL implementation returns an error from a large write,
147 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
148 // We could either fix the HAL implementations, or provide a wrapper that breaks
149 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
150} kUseFastMixer = FastMixer_Static;
151
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700152// Whether to use fast capture
153static const enum {
154 FastCapture_Never, // never initialize or use: for debugging only
155 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
156 FastCapture_Static, // initialize if needed, then use all the time if initialized
157} kUseFastCapture = FastCapture_Static;
158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Priorities for requestPriority
160static const int kPriorityAudioApp = 2;
161static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
165// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800166// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
167// So for now we just assume that client is double-buffered for fast tracks.
168// FIXME It would be better for client to tell AudioFlinger the value of N,
169// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800170// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700171
172// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasten03490092014-05-27 12:30:54 -0700175// The minimum and maximum allowed values
176static const int kFastTrackMultiplierMin = 1;
177static const int kFastTrackMultiplierMax = 2;
178
179// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
180static int sFastTrackMultiplier = kFastTrackMultiplier;
181
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182// See Thread::readOnlyHeap().
183// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
184// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
185// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700186static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// ----------------------------------------------------------------------------
189
Glenn Kasten03490092014-05-27 12:30:54 -0700190static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
191
192static void sFastTrackMultiplierInit()
193{
194 char value[PROPERTY_VALUE_MAX];
195 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
196 char *endptr;
197 unsigned long ul = strtoul(value, &endptr, 0);
198 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
199 sFastTrackMultiplier = (int) ul;
200 }
201 }
202}
203
204// ----------------------------------------------------------------------------
205
Eric Laurent81784c32012-11-19 14:55:58 -0800206#ifdef ADD_BATTERY_DATA
207// To collect the amplifier usage
208static void addBatteryData(uint32_t params) {
209 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
210 if (service == NULL) {
211 // it already logged
212 return;
213 }
214
215 service->addBatteryData(params);
216}
217#endif
218
219
220// ----------------------------------------------------------------------------
221// CPU Stats
222// ----------------------------------------------------------------------------
223
224class CpuStats {
225public:
226 CpuStats();
227 void sample(const String8 &title);
228#ifdef DEBUG_CPU_USAGE
229private:
230 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
231 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
232
233 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
234
235 int mCpuNum; // thread's current CPU number
236 int mCpukHz; // frequency of thread's current CPU in kHz
237#endif
238};
239
240CpuStats::CpuStats()
241#ifdef DEBUG_CPU_USAGE
242 : mCpuNum(-1), mCpukHz(-1)
243#endif
244{
245}
246
Glenn Kasten0f11b512014-01-31 16:18:54 -0800247void CpuStats::sample(const String8 &title
248#ifndef DEBUG_CPU_USAGE
249 __unused
250#endif
251 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800252#ifdef DEBUG_CPU_USAGE
253 // get current thread's delta CPU time in wall clock ns
254 double wcNs;
255 bool valid = mCpuUsage.sampleAndEnable(wcNs);
256
257 // record sample for wall clock statistics
258 if (valid) {
259 mWcStats.sample(wcNs);
260 }
261
262 // get the current CPU number
263 int cpuNum = sched_getcpu();
264
265 // get the current CPU frequency in kHz
266 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
267
268 // check if either CPU number or frequency changed
269 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
270 mCpuNum = cpuNum;
271 mCpukHz = cpukHz;
272 // ignore sample for purposes of cycles
273 valid = false;
274 }
275
276 // if no change in CPU number or frequency, then record sample for cycle statistics
277 if (valid && mCpukHz > 0) {
278 double cycles = wcNs * cpukHz * 0.000001;
279 mHzStats.sample(cycles);
280 }
281
282 unsigned n = mWcStats.n();
283 // mCpuUsage.elapsed() is expensive, so don't call it every loop
284 if ((n & 127) == 1) {
285 long long elapsed = mCpuUsage.elapsed();
286 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
287 double perLoop = elapsed / (double) n;
288 double perLoop100 = perLoop * 0.01;
289 double perLoop1k = perLoop * 0.001;
290 double mean = mWcStats.mean();
291 double stddev = mWcStats.stddev();
292 double minimum = mWcStats.minimum();
293 double maximum = mWcStats.maximum();
294 double meanCycles = mHzStats.mean();
295 double stddevCycles = mHzStats.stddev();
296 double minCycles = mHzStats.minimum();
297 double maxCycles = mHzStats.maximum();
298 mCpuUsage.resetElapsed();
299 mWcStats.reset();
300 mHzStats.reset();
301 ALOGD("CPU usage for %s over past %.1f secs\n"
302 " (%u mixer loops at %.1f mean ms per loop):\n"
303 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
304 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
305 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
306 title.string(),
307 elapsed * .000000001, n, perLoop * .000001,
308 mean * .001,
309 stddev * .001,
310 minimum * .001,
311 maximum * .001,
312 mean / perLoop100,
313 stddev / perLoop100,
314 minimum / perLoop100,
315 maximum / perLoop100,
316 meanCycles / perLoop1k,
317 stddevCycles / perLoop1k,
318 minCycles / perLoop1k,
319 maxCycles / perLoop1k);
320
321 }
322 }
323#endif
324};
325
326// ----------------------------------------------------------------------------
327// ThreadBase
328// ----------------------------------------------------------------------------
329
Glenn Kasten97b7b752014-09-28 13:04:24 -0700330// static
331const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
332{
333 switch (type) {
334 case MIXER:
335 return "MIXER";
336 case DIRECT:
337 return "DIRECT";
338 case DUPLICATING:
339 return "DUPLICATING";
340 case RECORD:
341 return "RECORD";
342 case OFFLOAD:
343 return "OFFLOAD";
344 default:
345 return "unknown";
346 }
347}
348
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800349String8 devicesToString(audio_devices_t devices)
350{
351 static const struct mapping {
352 audio_devices_t mDevices;
353 const char * mString;
354 } mappingsOut[] = {
355 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
356 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
357 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
358 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
359 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
360 AUDIO_DEVICE_NONE, "NONE", // must be last
361 }, mappingsIn[] = {
362 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
363 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
364 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
365 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
366 AUDIO_DEVICE_NONE, "NONE", // must be last
367 };
368 String8 result;
369 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
370 const mapping *entry;
371 if (devices & AUDIO_DEVICE_BIT_IN) {
372 devices &= ~AUDIO_DEVICE_BIT_IN;
373 entry = mappingsIn;
374 } else {
375 entry = mappingsOut;
376 }
377 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
378 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
379 if (devices & entry->mDevices) {
380 if (!result.isEmpty()) {
381 result.append("|");
382 }
383 result.append(entry->mString);
384 }
385 }
386 if (devices & ~allDevices) {
387 if (!result.isEmpty()) {
388 result.append("|");
389 }
390 result.appendFormat("0x%X", devices & ~allDevices);
391 }
392 if (result.isEmpty()) {
393 result.append(entry->mString);
394 }
395 return result;
396}
397
398String8 inputFlagsToString(audio_input_flags_t flags)
399{
400 static const struct mapping {
401 audio_input_flags_t mFlag;
402 const char * mString;
403 } mappings[] = {
404 AUDIO_INPUT_FLAG_FAST, "FAST",
405 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
406 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
407 };
408 String8 result;
409 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
410 const mapping *entry;
411 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
412 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
413 if (flags & entry->mFlag) {
414 if (!result.isEmpty()) {
415 result.append("|");
416 }
417 result.append(entry->mString);
418 }
419 }
420 if (flags & ~allFlags) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.appendFormat("0x%X", flags & ~allFlags);
425 }
426 if (result.isEmpty()) {
427 result.append(entry->mString);
428 }
429 return result;
430}
431
432String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700433{
434 static const struct mapping {
435 audio_output_flags_t mFlag;
436 const char * mString;
437 } mappings[] = {
438 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
439 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
440 AUDIO_OUTPUT_FLAG_FAST, "FAST",
441 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800442 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700443 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
444 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
445 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
446 };
447 String8 result;
448 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
449 const mapping *entry;
450 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
451 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
452 if (flags & entry->mFlag) {
453 if (!result.isEmpty()) {
454 result.append("|");
455 }
456 result.append(entry->mString);
457 }
458 }
459 if (flags & ~allFlags) {
460 if (!result.isEmpty()) {
461 result.append("|");
462 }
463 result.appendFormat("0x%X", flags & ~allFlags);
464 }
465 if (result.isEmpty()) {
466 result.append(entry->mString);
467 }
468 return result;
469}
470
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471const char *sourceToString(audio_source_t source)
472{
473 switch (source) {
474 case AUDIO_SOURCE_DEFAULT: return "default";
475 case AUDIO_SOURCE_MIC: return "mic";
476 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
477 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
478 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
479 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
480 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
481 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
482 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
483 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
484 case AUDIO_SOURCE_HOTWORD: return "hotword";
485 default: return "unknown";
486 }
487}
488
Eric Laurent81784c32012-11-19 14:55:58 -0800489AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
490 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
491 : Thread(false /*canCallJava*/),
492 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700493 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700494 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800495 // are set by PlaybackThread::readOutputParameters_l() or
496 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700497 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800498 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
499 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
500 // mName will be set by concrete (non-virtual) subclass
501 mDeathRecipient(new PMDeathRecipient(this))
502{
Eric Laurent296fb132015-05-01 11:38:42 -0700503 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800504}
505
506AudioFlinger::ThreadBase::~ThreadBase()
507{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700508 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700509 mConfigEvents.clear();
510
Eric Laurent81784c32012-11-19 14:55:58 -0800511 // do not lock the mutex in destructor
512 releaseWakeLock_l();
513 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800514 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800515 binder->unlinkToDeath(mDeathRecipient);
516 }
517}
518
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700519status_t AudioFlinger::ThreadBase::readyToRun()
520{
521 status_t status = initCheck();
522 if (status == NO_ERROR) {
523 ALOGI("AudioFlinger's thread %p ready to run", this);
524 } else {
525 ALOGE("No working audio driver found.");
526 }
527 return status;
528}
529
Eric Laurent81784c32012-11-19 14:55:58 -0800530void AudioFlinger::ThreadBase::exit()
531{
532 ALOGV("ThreadBase::exit");
533 // do any cleanup required for exit to succeed
534 preExit();
535 {
536 // This lock prevents the following race in thread (uniprocessor for illustration):
537 // if (!exitPending()) {
538 // // context switch from here to exit()
539 // // exit() calls requestExit(), what exitPending() observes
540 // // exit() calls signal(), which is dropped since no waiters
541 // // context switch back from exit() to here
542 // mWaitWorkCV.wait(...);
543 // // now thread is hung
544 // }
545 AutoMutex lock(mLock);
546 requestExit();
547 mWaitWorkCV.broadcast();
548 }
549 // When Thread::requestExitAndWait is made virtual and this method is renamed to
550 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
551 requestExitAndWait();
552}
553
554status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
555{
556 status_t status;
557
558 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
559 Mutex::Autolock _l(mLock);
560
Eric Laurent10351942014-05-08 18:49:52 -0700561 return sendSetParameterConfigEvent_l(keyValuePairs);
562}
563
564// sendConfigEvent_l() must be called with ThreadBase::mLock held
565// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
566status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
567{
568 status_t status = NO_ERROR;
569
570 mConfigEvents.add(event);
571 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800572 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700573 mLock.unlock();
574 {
575 Mutex::Autolock _l(event->mLock);
576 while (event->mWaitStatus) {
577 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
578 event->mStatus = TIMED_OUT;
579 event->mWaitStatus = false;
580 }
581 }
582 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800585 return status;
586}
587
Eric Laurent73e26b62015-04-27 16:55:58 -0700588void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800589{
590 Mutex::Autolock _l(mLock);
Eric Laurent73e26b62015-04-27 16:55:58 -0700591 sendIoConfigEvent_l(event);
Eric Laurent81784c32012-11-19 14:55:58 -0800592}
593
594// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent73e26b62015-04-27 16:55:58 -0700595void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event)
Eric Laurent81784c32012-11-19 14:55:58 -0800596{
Eric Laurent73e26b62015-04-27 16:55:58 -0700597 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event);
Eric Laurent10351942014-05-08 18:49:52 -0700598 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800599}
600
601// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
602void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
603{
Eric Laurent10351942014-05-08 18:49:52 -0700604 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
605 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
Eric Laurent10351942014-05-08 18:49:52 -0700608// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
609status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent10351942014-05-08 18:49:52 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
612 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700613}
614
Eric Laurent1c333e22014-05-20 10:48:17 -0700615status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
616 const struct audio_patch *patch,
617 audio_patch_handle_t *handle)
618{
619 Mutex::Autolock _l(mLock);
620 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
621 status_t status = sendConfigEvent_l(configEvent);
622 if (status == NO_ERROR) {
623 CreateAudioPatchConfigEventData *data =
624 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
625 *handle = data->mHandle;
626 }
627 return status;
628}
629
630status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
631 const audio_patch_handle_t handle)
632{
633 Mutex::Autolock _l(mLock);
634 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
635 return sendConfigEvent_l(configEvent);
636}
637
638
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700639// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700640void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700641{
Eric Laurent10351942014-05-08 18:49:52 -0700642 bool configChanged = false;
643
Eric Laurent81784c32012-11-19 14:55:58 -0800644 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700645 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
646 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800647 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700648 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700649 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700650 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
651 // FIXME Need to understand why this has to be done asynchronously
652 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700653 true /*asynchronous*/);
654 if (err != 0) {
655 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700656 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700657 }
658 } break;
659 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700660 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent73e26b62015-04-27 16:55:58 -0700661 ioConfigChanged(data->mEvent);
Eric Laurent10351942014-05-08 18:49:52 -0700662 } break;
663 case CFG_EVENT_SET_PARAMETER: {
664 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
665 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
666 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700667 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700668 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700669 case CFG_EVENT_CREATE_AUDIO_PATCH: {
670 CreateAudioPatchConfigEventData *data =
671 (CreateAudioPatchConfigEventData *)event->mData.get();
672 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
673 } break;
674 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
675 ReleaseAudioPatchConfigEventData *data =
676 (ReleaseAudioPatchConfigEventData *)event->mData.get();
677 event->mStatus = releaseAudioPatch_l(data->mHandle);
678 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700679 default:
Eric Laurent10351942014-05-08 18:49:52 -0700680 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800682 }
Eric Laurent10351942014-05-08 18:49:52 -0700683 {
684 Mutex::Autolock _l(event->mLock);
685 if (event->mWaitStatus) {
686 event->mWaitStatus = false;
687 event->mCond.signal();
688 }
689 }
690 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
691 }
692
693 if (configChanged) {
694 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800695 }
Eric Laurent81784c32012-11-19 14:55:58 -0800696}
697
Marco Nelissenb2208842014-02-07 14:00:50 -0800698String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
699 String8 s;
700 if (output) {
701 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
702 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
703 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
704 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
705 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
706 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
707 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
708 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
709 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
710 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
711 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
712 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
713 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
714 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
715 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
716 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
717 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
718 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
719 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
720 } else {
721 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
722 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
723 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
724 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
725 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
726 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
727 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
728 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
729 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
730 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
731 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
732 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
733 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
734 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
735 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
736 }
737 int len = s.length();
738 if (s.length() > 2) {
739 char *str = s.lockBuffer(len);
740 s.unlockBuffer(len - 2);
741 }
742 return s;
743}
744
Glenn Kasten0f11b512014-01-31 16:18:54 -0800745void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
747 const size_t SIZE = 256;
748 char buffer[SIZE];
749 String8 result;
750
751 bool locked = AudioFlinger::dumpTryLock(mLock);
752 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700753 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800754 }
755
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800756 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700757 dprintf(fd, " I/O handle: %d\n", mId);
758 dprintf(fd, " TID: %d\n", getTid());
759 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700760 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700761 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700762 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700763 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700764 dprintf(fd, " Channel count: %u\n", mChannelCount);
765 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800766 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700767 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
768 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700769 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800770 size_t numConfig = mConfigEvents.size();
771 if (numConfig) {
772 for (size_t i = 0; i < numConfig; i++) {
773 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700774 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800775 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700776 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800777 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700778 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800779 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800780 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
781 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
782 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800783
784 if (locked) {
785 mLock.unlock();
786 }
787}
788
789void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
790{
791 const size_t SIZE = 256;
792 char buffer[SIZE];
793 String8 result;
794
Marco Nelissenb2208842014-02-07 14:00:50 -0800795 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000796 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800797 write(fd, buffer, strlen(buffer));
798
Marco Nelissenb2208842014-02-07 14:00:50 -0800799 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800800 sp<EffectChain> chain = mEffectChains[i];
801 if (chain != 0) {
802 chain->dump(fd, args);
803 }
804 }
805}
806
Marco Nelissene14a5d62013-10-03 08:51:24 -0700807void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800808{
809 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700810 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800811}
812
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100813String16 AudioFlinger::ThreadBase::getWakeLockTag()
814{
815 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800816 case MIXER:
817 return String16("AudioMix");
818 case DIRECT:
819 return String16("AudioDirectOut");
820 case DUPLICATING:
821 return String16("AudioDup");
822 case RECORD:
823 return String16("AudioIn");
824 case OFFLOAD:
825 return String16("AudioOffload");
826 default:
827 ALOG_ASSERT(false);
828 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100829 }
830}
831
Marco Nelissene14a5d62013-10-03 08:51:24 -0700832void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800833{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800834 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800835 if (mPowerManager != 0) {
836 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700837 status_t status;
838 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700839 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700840 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100841 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700842 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700843 uid,
844 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700845 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700846 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700847 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100848 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700849 String16("media"),
850 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700851 }
Eric Laurent81784c32012-11-19 14:55:58 -0800852 if (status == NO_ERROR) {
853 mWakeLockToken = binder;
854 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800855 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800856 }
857}
858
859void AudioFlinger::ThreadBase::releaseWakeLock()
860{
861 Mutex::Autolock _l(mLock);
862 releaseWakeLock_l();
863}
864
865void AudioFlinger::ThreadBase::releaseWakeLock_l()
866{
867 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800868 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800869 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700870 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
871 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
873 mWakeLockToken.clear();
874 }
875}
876
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800877void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
878 Mutex::Autolock _l(mLock);
879 updateWakeLockUids_l(uids);
880}
881
882void AudioFlinger::ThreadBase::getPowerManager_l() {
883
884 if (mPowerManager == 0) {
885 // use checkService() to avoid blocking if power service is not up yet
886 sp<IBinder> binder =
887 defaultServiceManager()->checkService(String16("power"));
888 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800889 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800890 } else {
891 mPowerManager = interface_cast<IPowerManager>(binder);
892 binder->linkToDeath(mDeathRecipient);
893 }
894 }
895}
896
897void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
898
899 getPowerManager_l();
900 if (mWakeLockToken == NULL) {
901 ALOGE("no wake lock to update!");
902 return;
903 }
904 if (mPowerManager != 0) {
905 sp<IBinder> binder = new BBinder();
906 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700907 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
908 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800910 }
911}
912
Eric Laurent81784c32012-11-19 14:55:58 -0800913void AudioFlinger::ThreadBase::clearPowerManager()
914{
915 Mutex::Autolock _l(mLock);
916 releaseWakeLock_l();
917 mPowerManager.clear();
918}
919
Glenn Kasten0f11b512014-01-31 16:18:54 -0800920void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800921{
922 sp<ThreadBase> thread = mThread.promote();
923 if (thread != 0) {
924 thread->clearPowerManager();
925 }
926 ALOGW("power manager service died !!!");
927}
928
929void AudioFlinger::ThreadBase::setEffectSuspended(
930 const effect_uuid_t *type, bool suspend, int sessionId)
931{
932 Mutex::Autolock _l(mLock);
933 setEffectSuspended_l(type, suspend, sessionId);
934}
935
936void AudioFlinger::ThreadBase::setEffectSuspended_l(
937 const effect_uuid_t *type, bool suspend, int sessionId)
938{
939 sp<EffectChain> chain = getEffectChain_l(sessionId);
940 if (chain != 0) {
941 if (type != NULL) {
942 chain->setEffectSuspended_l(type, suspend);
943 } else {
944 chain->setEffectSuspendedAll_l(suspend);
945 }
946 }
947
948 updateSuspendedSessions_l(type, suspend, sessionId);
949}
950
951void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
952{
953 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
954 if (index < 0) {
955 return;
956 }
957
958 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
959 mSuspendedSessions.valueAt(index);
960
961 for (size_t i = 0; i < sessionEffects.size(); i++) {
962 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
963 for (int j = 0; j < desc->mRefCount; j++) {
964 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
965 chain->setEffectSuspendedAll_l(true);
966 } else {
967 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
968 desc->mType.timeLow);
969 chain->setEffectSuspended_l(&desc->mType, true);
970 }
971 }
972 }
973}
974
975void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
976 bool suspend,
977 int sessionId)
978{
979 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
980
981 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
982
983 if (suspend) {
984 if (index >= 0) {
985 sessionEffects = mSuspendedSessions.valueAt(index);
986 } else {
987 mSuspendedSessions.add(sessionId, sessionEffects);
988 }
989 } else {
990 if (index < 0) {
991 return;
992 }
993 sessionEffects = mSuspendedSessions.valueAt(index);
994 }
995
996
997 int key = EffectChain::kKeyForSuspendAll;
998 if (type != NULL) {
999 key = type->timeLow;
1000 }
1001 index = sessionEffects.indexOfKey(key);
1002
1003 sp<SuspendedSessionDesc> desc;
1004 if (suspend) {
1005 if (index >= 0) {
1006 desc = sessionEffects.valueAt(index);
1007 } else {
1008 desc = new SuspendedSessionDesc();
1009 if (type != NULL) {
1010 desc->mType = *type;
1011 }
1012 sessionEffects.add(key, desc);
1013 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1014 }
1015 desc->mRefCount++;
1016 } else {
1017 if (index < 0) {
1018 return;
1019 }
1020 desc = sessionEffects.valueAt(index);
1021 if (--desc->mRefCount == 0) {
1022 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1023 sessionEffects.removeItemsAt(index);
1024 if (sessionEffects.isEmpty()) {
1025 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1026 sessionId);
1027 mSuspendedSessions.removeItem(sessionId);
1028 }
1029 }
1030 }
1031 if (!sessionEffects.isEmpty()) {
1032 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1033 }
1034}
1035
1036void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1037 bool enabled,
1038 int sessionId)
1039{
1040 Mutex::Autolock _l(mLock);
1041 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1042}
1043
1044void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1045 bool enabled,
1046 int sessionId)
1047{
1048 if (mType != RECORD) {
1049 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1050 // another session. This gives the priority to well behaved effect control panels
1051 // and applications not using global effects.
1052 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1053 // global effects
1054 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1055 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1056 }
1057 }
1058
1059 sp<EffectChain> chain = getEffectChain_l(sessionId);
1060 if (chain != 0) {
1061 chain->checkSuspendOnEffectEnabled(effect, enabled);
1062 }
1063}
1064
1065// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1066sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1067 const sp<AudioFlinger::Client>& client,
1068 const sp<IEffectClient>& effectClient,
1069 int32_t priority,
1070 int sessionId,
1071 effect_descriptor_t *desc,
1072 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001073 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001074{
1075 sp<EffectModule> effect;
1076 sp<EffectHandle> handle;
1077 status_t lStatus;
1078 sp<EffectChain> chain;
1079 bool chainCreated = false;
1080 bool effectCreated = false;
1081 bool effectRegistered = false;
1082
1083 lStatus = initCheck();
1084 if (lStatus != NO_ERROR) {
1085 ALOGW("createEffect_l() Audio driver not initialized.");
1086 goto Exit;
1087 }
1088
Andy Hung98ef9782014-03-04 14:46:50 -08001089 // Reject any effect on Direct output threads for now, since the format of
1090 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1091 if (mType == DIRECT) {
1092 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001093 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001094 lStatus = BAD_VALUE;
1095 goto Exit;
1096 }
1097
Andy Hung389cfdb2014-08-07 17:49:53 -07001098 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001099 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001100 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1101 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1102 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001103 lStatus = BAD_VALUE;
1104 goto Exit;
1105 }
1106
Eric Laurent5baf2af2013-09-12 17:37:00 -07001107 // Allow global effects only on offloaded and mixer threads
1108 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1109 switch (mType) {
1110 case MIXER:
1111 case OFFLOAD:
1112 break;
1113 case DIRECT:
1114 case DUPLICATING:
1115 case RECORD:
1116 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001117 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1118 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001119 lStatus = BAD_VALUE;
1120 goto Exit;
1121 }
Eric Laurent81784c32012-11-19 14:55:58 -08001122 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001123
Eric Laurent81784c32012-11-19 14:55:58 -08001124 // Only Pre processor effects are allowed on input threads and only on input threads
1125 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1126 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1127 desc->name, desc->flags, mType);
1128 lStatus = BAD_VALUE;
1129 goto Exit;
1130 }
1131
1132 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1133
1134 { // scope for mLock
1135 Mutex::Autolock _l(mLock);
1136
1137 // check for existing effect chain with the requested audio session
1138 chain = getEffectChain_l(sessionId);
1139 if (chain == 0) {
1140 // create a new chain for this session
1141 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1142 chain = new EffectChain(this, sessionId);
1143 addEffectChain_l(chain);
1144 chain->setStrategy(getStrategyForSession_l(sessionId));
1145 chainCreated = true;
1146 } else {
1147 effect = chain->getEffectFromDesc_l(desc);
1148 }
1149
1150 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1151
1152 if (effect == 0) {
1153 int id = mAudioFlinger->nextUniqueId();
1154 // Check CPU and memory usage
1155 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1156 if (lStatus != NO_ERROR) {
1157 goto Exit;
1158 }
1159 effectRegistered = true;
1160 // create a new effect module if none present in the chain
1161 effect = new EffectModule(this, chain, desc, id, sessionId);
1162 lStatus = effect->status();
1163 if (lStatus != NO_ERROR) {
1164 goto Exit;
1165 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001166 effect->setOffloaded(mType == OFFLOAD, mId);
1167
Eric Laurent81784c32012-11-19 14:55:58 -08001168 lStatus = chain->addEffect_l(effect);
1169 if (lStatus != NO_ERROR) {
1170 goto Exit;
1171 }
1172 effectCreated = true;
1173
1174 effect->setDevice(mOutDevice);
1175 effect->setDevice(mInDevice);
1176 effect->setMode(mAudioFlinger->getMode());
1177 effect->setAudioSource(mAudioSource);
1178 }
1179 // create effect handle and connect it to effect module
1180 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001181 lStatus = handle->initCheck();
1182 if (lStatus == OK) {
1183 lStatus = effect->addHandle(handle.get());
1184 }
Eric Laurent81784c32012-11-19 14:55:58 -08001185 if (enabled != NULL) {
1186 *enabled = (int)effect->isEnabled();
1187 }
1188 }
1189
1190Exit:
1191 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1192 Mutex::Autolock _l(mLock);
1193 if (effectCreated) {
1194 chain->removeEffect_l(effect);
1195 }
1196 if (effectRegistered) {
1197 AudioSystem::unregisterEffect(effect->id());
1198 }
1199 if (chainCreated) {
1200 removeEffectChain_l(chain);
1201 }
1202 handle.clear();
1203 }
1204
Glenn Kasten9156ef32013-08-06 15:39:08 -07001205 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001206 return handle;
1207}
1208
1209sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1210{
1211 Mutex::Autolock _l(mLock);
1212 return getEffect_l(sessionId, effectId);
1213}
1214
1215sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1216{
1217 sp<EffectChain> chain = getEffectChain_l(sessionId);
1218 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1219}
1220
1221// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1222// PlaybackThread::mLock held
1223status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1224{
1225 // check for existing effect chain with the requested audio session
1226 int sessionId = effect->sessionId();
1227 sp<EffectChain> chain = getEffectChain_l(sessionId);
1228 bool chainCreated = false;
1229
Eric Laurent5baf2af2013-09-12 17:37:00 -07001230 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1231 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1232 this, effect->desc().name, effect->desc().flags);
1233
Eric Laurent81784c32012-11-19 14:55:58 -08001234 if (chain == 0) {
1235 // create a new chain for this session
1236 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1237 chain = new EffectChain(this, sessionId);
1238 addEffectChain_l(chain);
1239 chain->setStrategy(getStrategyForSession_l(sessionId));
1240 chainCreated = true;
1241 }
1242 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1243
1244 if (chain->getEffectFromId_l(effect->id()) != 0) {
1245 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1246 this, effect->desc().name, chain.get());
1247 return BAD_VALUE;
1248 }
1249
Eric Laurent5baf2af2013-09-12 17:37:00 -07001250 effect->setOffloaded(mType == OFFLOAD, mId);
1251
Eric Laurent81784c32012-11-19 14:55:58 -08001252 status_t status = chain->addEffect_l(effect);
1253 if (status != NO_ERROR) {
1254 if (chainCreated) {
1255 removeEffectChain_l(chain);
1256 }
1257 return status;
1258 }
1259
1260 effect->setDevice(mOutDevice);
1261 effect->setDevice(mInDevice);
1262 effect->setMode(mAudioFlinger->getMode());
1263 effect->setAudioSource(mAudioSource);
1264 return NO_ERROR;
1265}
1266
1267void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1268
1269 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1270 effect_descriptor_t desc = effect->desc();
1271 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1272 detachAuxEffect_l(effect->id());
1273 }
1274
1275 sp<EffectChain> chain = effect->chain().promote();
1276 if (chain != 0) {
1277 // remove effect chain if removing last effect
1278 if (chain->removeEffect_l(effect) == 0) {
1279 removeEffectChain_l(chain);
1280 }
1281 } else {
1282 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1283 }
1284}
1285
1286void AudioFlinger::ThreadBase::lockEffectChains_l(
1287 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1288{
1289 effectChains = mEffectChains;
1290 for (size_t i = 0; i < mEffectChains.size(); i++) {
1291 mEffectChains[i]->lock();
1292 }
1293}
1294
1295void AudioFlinger::ThreadBase::unlockEffectChains(
1296 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1297{
1298 for (size_t i = 0; i < effectChains.size(); i++) {
1299 effectChains[i]->unlock();
1300 }
1301}
1302
1303sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1304{
1305 Mutex::Autolock _l(mLock);
1306 return getEffectChain_l(sessionId);
1307}
1308
1309sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1310{
1311 size_t size = mEffectChains.size();
1312 for (size_t i = 0; i < size; i++) {
1313 if (mEffectChains[i]->sessionId() == sessionId) {
1314 return mEffectChains[i];
1315 }
1316 }
1317 return 0;
1318}
1319
1320void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1321{
1322 Mutex::Autolock _l(mLock);
1323 size_t size = mEffectChains.size();
1324 for (size_t i = 0; i < size; i++) {
1325 mEffectChains[i]->setMode_l(mode);
1326 }
1327}
1328
Eric Laurent83b88082014-06-20 18:31:16 -07001329void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1330{
1331 config->type = AUDIO_PORT_TYPE_MIX;
1332 config->ext.mix.handle = mId;
1333 config->sample_rate = mSampleRate;
1334 config->format = mFormat;
1335 config->channel_mask = mChannelMask;
1336 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1337 AUDIO_PORT_CONFIG_FORMAT;
1338}
1339
1340
Eric Laurent81784c32012-11-19 14:55:58 -08001341// ----------------------------------------------------------------------------
1342// Playback
1343// ----------------------------------------------------------------------------
1344
1345AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1346 AudioStreamOut* output,
1347 audio_io_handle_t id,
1348 audio_devices_t device,
1349 type_t type)
1350 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001351 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001352 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001353 mMixerBuffer(NULL),
1354 mMixerBufferSize(0),
1355 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1356 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001357 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001358 mEffectBuffer(NULL),
1359 mEffectBufferSize(0),
1360 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1361 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001362 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001363 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001364 // mStreamTypes[] initialized in constructor body
1365 mOutput(output),
1366 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1367 mMixerStatus(MIXER_IDLE),
1368 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1369 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001370 mBytesRemaining(0),
1371 mCurrentWriteLength(0),
1372 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001373 mWriteAckSequence(0),
1374 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001375 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001376 mScreenState(AudioFlinger::mScreenState),
1377 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001378 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001379 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001380 // mLatchD, mLatchQ,
1381 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001382{
Glenn Kastend7dca052015-03-05 16:05:54 -08001383 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1384 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001385
1386 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1387 // it would be safer to explicitly pass initial masterVolume/masterMute as
1388 // parameter.
1389 //
1390 // If the HAL we are using has support for master volume or master mute,
1391 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1392 // and the mute set to false).
1393 mMasterVolume = audioFlinger->masterVolume_l();
1394 mMasterMute = audioFlinger->masterMute_l();
1395 if (mOutput && mOutput->audioHwDev) {
1396 if (mOutput->audioHwDev->canSetMasterVolume()) {
1397 mMasterVolume = 1.0;
1398 }
1399
1400 if (mOutput->audioHwDev->canSetMasterMute()) {
1401 mMasterMute = false;
1402 }
1403 }
1404
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001405 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001406
Eric Laurent223fd5c2014-11-11 13:43:36 -08001407 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001408 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001409 stream = (audio_stream_type_t) (stream + 1)) {
1410 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1411 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1412 }
Eric Laurent81784c32012-11-19 14:55:58 -08001413}
1414
1415AudioFlinger::PlaybackThread::~PlaybackThread()
1416{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001417 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001418 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001419 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001420 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001421}
1422
1423void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1424{
1425 dumpInternals(fd, args);
1426 dumpTracks(fd, args);
1427 dumpEffectChains(fd, args);
1428}
1429
Glenn Kasten0f11b512014-01-31 16:18:54 -08001430void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001431{
1432 const size_t SIZE = 256;
1433 char buffer[SIZE];
1434 String8 result;
1435
Marco Nelissenb2208842014-02-07 14:00:50 -08001436 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001437 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1438 const stream_type_t *st = &mStreamTypes[i];
1439 if (i > 0) {
1440 result.appendFormat(", ");
1441 }
1442 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1443 if (st->mute) {
1444 result.append("M");
1445 }
1446 }
1447 result.append("\n");
1448 write(fd, result.string(), result.length());
1449 result.clear();
1450
Eric Laurent81784c32012-11-19 14:55:58 -08001451 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1452 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001453 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001454 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001455
1456 size_t numtracks = mTracks.size();
1457 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001458 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001459 size_t numactiveseen = 0;
1460 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001461 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001462 Track::appendDumpHeader(result);
1463 for (size_t i = 0; i < numtracks; ++i) {
1464 sp<Track> track = mTracks[i];
1465 if (track != 0) {
1466 bool active = mActiveTracks.indexOf(track) >= 0;
1467 if (active) {
1468 numactiveseen++;
1469 }
1470 track->dump(buffer, SIZE, active);
1471 result.append(buffer);
1472 }
1473 }
1474 } else {
1475 result.append("\n");
1476 }
1477 if (numactiveseen != numactive) {
1478 // some tracks in the active list were not in the tracks list
1479 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1480 " not in the track list\n");
1481 result.append(buffer);
1482 Track::appendDumpHeader(result);
1483 for (size_t i = 0; i < numactive; ++i) {
1484 sp<Track> track = mActiveTracks[i].promote();
1485 if (track != 0 && mTracks.indexOf(track) < 0) {
1486 track->dump(buffer, SIZE, true);
1487 result.append(buffer);
1488 }
1489 }
1490 }
1491
1492 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001493}
1494
1495void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1496{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001497 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001498
1499 dumpBase(fd, args);
1500
Elliott Hughes87cebad2014-05-22 10:14:43 -07001501 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1502 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1503 dprintf(fd, " Total writes: %d\n", mNumWrites);
1504 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1505 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1506 dprintf(fd, " Suspend count: %d\n", mSuspended);
1507 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1508 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1509 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1510 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001511 AudioStreamOut *output = mOutput;
1512 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1513 String8 flagsAsString = outputFlagsToString(flags);
1514 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001515}
1516
1517// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001518
1519void AudioFlinger::PlaybackThread::onFirstRef()
1520{
Glenn Kastend7dca052015-03-05 16:05:54 -08001521 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001522}
1523
1524// ThreadBase virtuals
1525void AudioFlinger::PlaybackThread::preExit()
1526{
1527 ALOGV(" preExit()");
1528 // FIXME this is using hard-coded strings but in the future, this functionality will be
1529 // converted to use audio HAL extensions required to support tunneling
1530 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1531}
1532
1533// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1534sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1535 const sp<AudioFlinger::Client>& client,
1536 audio_stream_type_t streamType,
1537 uint32_t sampleRate,
1538 audio_format_t format,
1539 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001540 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001541 const sp<IMemory>& sharedBuffer,
1542 int sessionId,
1543 IAudioFlinger::track_flags_t *flags,
1544 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001545 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001546 status_t *status)
1547{
Glenn Kasten74935e42013-12-19 08:56:45 -08001548 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001549 sp<Track> track;
1550 status_t lStatus;
1551
1552 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1553
1554 // client expresses a preference for FAST, but we get the final say
1555 if (*flags & IAudioFlinger::TRACK_FAST) {
1556 if (
1557 // not timed
1558 (!isTimed) &&
1559 // either of these use cases:
1560 (
1561 // use case 1: shared buffer with any frame count
1562 (
1563 (sharedBuffer != 0)
1564 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001565 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001566 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001567 // we formerly checked for a callback handler (non-0 tid),
1568 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001569 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001570 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001571 )
1572 ) &&
1573 // PCM data
1574 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001575 // identical channel mask to sink, or mono in and stereo sink
1576 (channelMask == mChannelMask ||
1577 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1578 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001579 // hardware sample rate
1580 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001581 // normal mixer has an associated fast mixer
1582 hasFastMixer() &&
1583 // there are sufficient fast track slots available
1584 (mFastTrackAvailMask != 0)
1585 // FIXME test that MixerThread for this fast track has a capable output HAL
1586 // FIXME add a permission test also?
1587 ) {
1588 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1589 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001590 // read the fast track multiplier property the first time it is needed
1591 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1592 if (ok != 0) {
1593 ALOGE("%s pthread_once failed: %d", __func__, ok);
1594 }
1595 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001596 }
1597 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1598 frameCount, mFrameCount);
1599 } else {
1600 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001601 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1602 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001603 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001604 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001605 audio_is_linear_pcm(format),
1606 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1607 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001608 }
1609 }
1610 // For normal PCM streaming tracks, update minimum frame count.
1611 // For compatibility with AudioTrack calculation, buffer depth is forced
1612 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1613 // This is probably too conservative, but legacy application code may depend on it.
1614 // If you change this calculation, also review the start threshold which is related.
1615 if (!(*flags & IAudioFlinger::TRACK_FAST)
1616 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001617 // this must match AudioTrack.cpp calculateMinFrameCount().
1618 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001619 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1620 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1621 if (minBufCount < 2) {
1622 minBufCount = 2;
1623 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001624 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1625 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001626 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001627 minBufCount * sourceFramesNeededWithTimestretch(
1628 sampleRate, mNormalFrameCount,
1629 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001630 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001631 frameCount = minFrameCount;
1632 }
Eric Laurent81784c32012-11-19 14:55:58 -08001633 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001634 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001635
Glenn Kastenc3df8382014-03-13 15:05:25 -07001636 switch (mType) {
1637
1638 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001639 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001640 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001641 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1642 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001643 sampleRate, format, channelMask, mOutput, mFormat);
1644 lStatus = BAD_VALUE;
1645 goto Exit;
1646 }
1647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001648 break;
1649
1650 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001651 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001652 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1653 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001654 sampleRate, format, channelMask, mOutput, mFormat);
1655 lStatus = BAD_VALUE;
1656 goto Exit;
1657 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001658 break;
1659
1660 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001661 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001662 ALOGE("createTrack_l() Bad parameter: format %#x \""
1663 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001664 format, mOutput, mFormat);
1665 lStatus = BAD_VALUE;
1666 goto Exit;
1667 }
Andy Hungcd044842014-08-07 11:04:34 -07001668 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001669 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1670 lStatus = BAD_VALUE;
1671 goto Exit;
1672 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001673 break;
1674
Eric Laurent81784c32012-11-19 14:55:58 -08001675 }
1676
1677 lStatus = initCheck();
1678 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001679 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001680 goto Exit;
1681 }
1682
1683 { // scope for mLock
1684 Mutex::Autolock _l(mLock);
1685
1686 // all tracks in same audio session must share the same routing strategy otherwise
1687 // conflicts will happen when tracks are moved from one output to another by audio policy
1688 // manager
1689 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1690 for (size_t i = 0; i < mTracks.size(); ++i) {
1691 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001692 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001693 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1694 if (sessionId == t->sessionId() && strategy != actual) {
1695 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1696 strategy, actual);
1697 lStatus = BAD_VALUE;
1698 goto Exit;
1699 }
1700 }
1701 }
1702
1703 if (!isTimed) {
1704 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001705 channelMask, frameCount, NULL, sharedBuffer,
1706 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001707 } else {
1708 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001709 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001710 }
Glenn Kasten03003332013-08-06 15:40:54 -07001711
1712 // new Track always returns non-NULL,
1713 // but TimedTrack::create() is a factory that could fail by returning NULL
1714 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1715 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001716 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001717 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001718 goto Exit;
1719 }
1720 mTracks.add(track);
1721
1722 sp<EffectChain> chain = getEffectChain_l(sessionId);
1723 if (chain != 0) {
1724 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1725 track->setMainBuffer(chain->inBuffer());
1726 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1727 chain->incTrackCnt();
1728 }
1729
1730 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1731 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1732 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1733 // so ask activity manager to do this on our behalf
1734 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1735 }
1736 }
1737
1738 lStatus = NO_ERROR;
1739
1740Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001741 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001742 return track;
1743}
1744
1745uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1746{
1747 return latency;
1748}
1749
1750uint32_t AudioFlinger::PlaybackThread::latency() const
1751{
1752 Mutex::Autolock _l(mLock);
1753 return latency_l();
1754}
1755uint32_t AudioFlinger::PlaybackThread::latency_l() const
1756{
1757 if (initCheck() == NO_ERROR) {
1758 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1759 } else {
1760 return 0;
1761 }
1762}
1763
1764void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1765{
1766 Mutex::Autolock _l(mLock);
1767 // Don't apply master volume in SW if our HAL can do it for us.
1768 if (mOutput && mOutput->audioHwDev &&
1769 mOutput->audioHwDev->canSetMasterVolume()) {
1770 mMasterVolume = 1.0;
1771 } else {
1772 mMasterVolume = value;
1773 }
1774}
1775
1776void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1777{
1778 Mutex::Autolock _l(mLock);
1779 // Don't apply master mute in SW if our HAL can do it for us.
1780 if (mOutput && mOutput->audioHwDev &&
1781 mOutput->audioHwDev->canSetMasterMute()) {
1782 mMasterMute = false;
1783 } else {
1784 mMasterMute = muted;
1785 }
1786}
1787
1788void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1789{
1790 Mutex::Autolock _l(mLock);
1791 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001792 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001793}
1794
1795void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1796{
1797 Mutex::Autolock _l(mLock);
1798 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001799 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001800}
1801
1802float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1803{
1804 Mutex::Autolock _l(mLock);
1805 return mStreamTypes[stream].volume;
1806}
1807
1808// addTrack_l() must be called with ThreadBase::mLock held
1809status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1810{
1811 status_t status = ALREADY_EXISTS;
1812
1813 // set retry count for buffer fill
1814 track->mRetryCount = kMaxTrackStartupRetries;
1815 if (mActiveTracks.indexOf(track) < 0) {
1816 // the track is newly added, make sure it fills up all its
1817 // buffers before playing. This is to ensure the client will
1818 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001819 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001820 TrackBase::track_state state = track->mState;
1821 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001822 status = AudioSystem::startOutput(mId, track->streamType(),
1823 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001824 mLock.lock();
1825 // abort track was stopped/paused while we released the lock
1826 if (state != track->mState) {
1827 if (status == NO_ERROR) {
1828 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001829 AudioSystem::stopOutput(mId, track->streamType(),
1830 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001831 mLock.lock();
1832 }
1833 return INVALID_OPERATION;
1834 }
1835 // abort if start is rejected by audio policy manager
1836 if (status != NO_ERROR) {
1837 return PERMISSION_DENIED;
1838 }
1839#ifdef ADD_BATTERY_DATA
1840 // to track the speaker usage
1841 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1842#endif
1843 }
1844
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001845 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001846 track->mResetDone = false;
1847 track->mPresentationCompleteFrames = 0;
1848 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001849 mWakeLockUids.add(track->uid());
1850 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001851 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001852 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1853 if (chain != 0) {
1854 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1855 track->sessionId());
1856 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001857 }
1858
1859 status = NO_ERROR;
1860 }
1861
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001862 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001863 return status;
1864}
1865
Eric Laurentbfb1b832013-01-07 09:53:42 -08001866bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001867{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001868 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001869 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001870 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1871 track->mState = TrackBase::STOPPED;
1872 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001873 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001874 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001875 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001876 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001877
1878 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001879}
1880
1881void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1882{
1883 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1884 mTracks.remove(track);
1885 deleteTrackName_l(track->name());
1886 // redundant as track is about to be destroyed, for dumpsys only
1887 track->mName = -1;
1888 if (track->isFastTrack()) {
1889 int index = track->mFastIndex;
1890 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1891 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1892 mFastTrackAvailMask |= 1 << index;
1893 // redundant as track is about to be destroyed, for dumpsys only
1894 track->mFastIndex = -1;
1895 }
1896 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1897 if (chain != 0) {
1898 chain->decTrackCnt();
1899 }
1900}
1901
Eric Laurentede6c3b2013-09-19 14:37:46 -07001902void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001903{
1904 // Thread could be blocked waiting for async
1905 // so signal it to handle state changes immediately
1906 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1907 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1908 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001909 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001910}
1911
Eric Laurent81784c32012-11-19 14:55:58 -08001912String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1913{
Eric Laurent81784c32012-11-19 14:55:58 -08001914 Mutex::Autolock _l(mLock);
1915 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001916 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001917 }
1918
Glenn Kastend8ea6992013-07-16 14:17:15 -07001919 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1920 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001921 free(s);
1922 return out_s8;
1923}
1924
Eric Laurent73e26b62015-04-27 16:55:58 -07001925void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event) {
1926 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
1927 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08001928
Eric Laurent73e26b62015-04-27 16:55:58 -07001929 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08001930
1931 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07001932 case AUDIO_OUTPUT_OPENED:
1933 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07001934 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07001935 desc->mChannelMask = mChannelMask;
1936 desc->mSamplingRate = mSampleRate;
1937 desc->mFormat = mFormat;
1938 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08001939 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07001940 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001941 break;
1942
Eric Laurent73e26b62015-04-27 16:55:58 -07001943 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08001944 default:
1945 break;
1946 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001947 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001948}
1949
Eric Laurentbfb1b832013-01-07 09:53:42 -08001950void AudioFlinger::PlaybackThread::writeCallback()
1951{
1952 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001953 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954}
1955
1956void AudioFlinger::PlaybackThread::drainCallback()
1957{
1958 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001959 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001960}
1961
Eric Laurent3b4529e2013-09-05 18:09:19 -07001962void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963{
1964 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001965 // reject out of sequence requests
1966 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1967 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001968 mWaitWorkCV.signal();
1969 }
1970}
1971
Eric Laurent3b4529e2013-09-05 18:09:19 -07001972void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973{
1974 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001975 // reject out of sequence requests
1976 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1977 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001978 mWaitWorkCV.signal();
1979 }
1980}
1981
1982// static
1983int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001984 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985 void *cookie)
1986{
1987 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1988 ALOGV("asyncCallback() event %d", event);
1989 switch (event) {
1990 case STREAM_CBK_EVENT_WRITE_READY:
1991 me->writeCallback();
1992 break;
1993 case STREAM_CBK_EVENT_DRAIN_READY:
1994 me->drainCallback();
1995 break;
1996 default:
1997 ALOGW("asyncCallback() unknown event %d", event);
1998 break;
1999 }
2000 return 0;
2001}
2002
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002003void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002004{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002005 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002006 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2007 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002008 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002009 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002010 }
Andy Hung9a592762014-07-21 21:56:01 -07002011 if ((mType == MIXER || mType == DUPLICATING)
2012 && !isValidPcmSinkChannelMask(mChannelMask)) {
2013 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2014 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002015 }
Andy Hunge5412692014-05-16 11:25:07 -07002016 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002017 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2018 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002019 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002020 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002021 }
Andy Hung6146c082014-03-18 11:56:15 -07002022 if ((mType == MIXER || mType == DUPLICATING)
2023 && !isValidPcmSinkFormat(mFormat)) {
2024 LOG_FATAL("HAL format %#x not supported for mixed output",
2025 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002026 }
Phil Burk062e67a2015-02-11 13:40:50 -08002027 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002028 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2029 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002030 if (mFrameCount & 15) {
2031 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2032 mFrameCount);
2033 }
2034
Eric Laurentbfb1b832013-01-07 09:53:42 -08002035 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2036 (mOutput->stream->set_callback != NULL)) {
2037 if (mOutput->stream->set_callback(mOutput->stream,
2038 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2039 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002040 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002041 }
2042 }
2043
Eric Laurentd1f69b02014-12-15 14:33:13 -08002044 mHwSupportsPause = false;
2045 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2046 if (mOutput->stream->pause != NULL) {
2047 if (mOutput->stream->resume != NULL) {
2048 mHwSupportsPause = true;
2049 } else {
2050 ALOGW("direct output implements pause but not resume");
2051 }
2052 } else if (mOutput->stream->resume != NULL) {
2053 ALOGW("direct output implements resume but not pause");
2054 }
2055 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002056 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2057 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2058 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002059
Andy Hungfbfc3952015-01-15 13:33:51 -08002060 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2061 // For best precision, we use float instead of the associated output
2062 // device format (typically PCM 16 bit).
2063
2064 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2065 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2066 mBufferSize = mFrameSize * mFrameCount;
2067
2068 // TODO: We currently use the associated output device channel mask and sample rate.
2069 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2070 // (if a valid mask) to avoid premature downmix.
2071 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2072 // instead of the output device sample rate to avoid loss of high frequency information.
2073 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2074 }
2075
Andy Hung09a50072014-02-27 14:30:47 -08002076 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002077 double multiplier = 1.0;
2078 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2079 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002080 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2081 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002082 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2083 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2084 maxNormalFrameCount = maxNormalFrameCount & ~15;
2085 if (maxNormalFrameCount < minNormalFrameCount) {
2086 maxNormalFrameCount = minNormalFrameCount;
2087 }
2088 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2089 if (multiplier <= 1.0) {
2090 multiplier = 1.0;
2091 } else if (multiplier <= 2.0) {
2092 if (2 * mFrameCount <= maxNormalFrameCount) {
2093 multiplier = 2.0;
2094 } else {
2095 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2096 }
2097 } else {
2098 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002099 // 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 -08002100 // track, but we sometimes have to do this to satisfy the maximum frame count
2101 // constraint)
2102 // FIXME this rounding up should not be done if no HAL SRC
2103 uint32_t truncMult = (uint32_t) multiplier;
2104 if ((truncMult & 1)) {
2105 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2106 ++truncMult;
2107 }
2108 }
2109 multiplier = (double) truncMult;
2110 }
2111 }
2112 mNormalFrameCount = multiplier * mFrameCount;
2113 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002114 if (mType == MIXER || mType == DUPLICATING) {
2115 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2116 }
Andy Hung09a50072014-02-27 14:30:47 -08002117 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002118 mNormalFrameCount);
2119
Andy Hung010a1a12014-03-13 13:57:33 -07002120 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2121 // Originally this was int16_t[] array, need to remove legacy implications.
2122 free(mSinkBuffer);
2123 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002124 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2125 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2126 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002127 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002128
Andy Hung69aed5f2014-02-25 17:24:40 -08002129 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2130 // drives the output.
2131 free(mMixerBuffer);
2132 mMixerBuffer = NULL;
2133 if (mMixerBufferEnabled) {
2134 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2135 mMixerBufferSize = mNormalFrameCount * mChannelCount
2136 * audio_bytes_per_sample(mMixerBufferFormat);
2137 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2138 }
Andy Hung98ef9782014-03-04 14:46:50 -08002139 free(mEffectBuffer);
2140 mEffectBuffer = NULL;
2141 if (mEffectBufferEnabled) {
2142 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2143 mEffectBufferSize = mNormalFrameCount * mChannelCount
2144 * audio_bytes_per_sample(mEffectBufferFormat);
2145 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2146 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002147
Eric Laurent81784c32012-11-19 14:55:58 -08002148 // force reconfiguration of effect chains and engines to take new buffer size and audio
2149 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002150 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002151 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2152 // matter.
2153 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2154 Vector< sp<EffectChain> > effectChains = mEffectChains;
2155 for (size_t i = 0; i < effectChains.size(); i ++) {
2156 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2157 }
2158}
2159
2160
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002161status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002162{
2163 if (halFrames == NULL || dspFrames == NULL) {
2164 return BAD_VALUE;
2165 }
2166 Mutex::Autolock _l(mLock);
2167 if (initCheck() != NO_ERROR) {
2168 return INVALID_OPERATION;
2169 }
2170 size_t framesWritten = mBytesWritten / mFrameSize;
2171 *halFrames = framesWritten;
2172
2173 if (isSuspended()) {
2174 // return an estimation of rendered frames when the output is suspended
2175 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2176 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2177 return NO_ERROR;
2178 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002179 status_t status;
2180 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002181 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002182 *dspFrames = (size_t)frames;
2183 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002184 }
2185}
2186
2187uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2188{
2189 Mutex::Autolock _l(mLock);
2190 uint32_t result = 0;
2191 if (getEffectChain_l(sessionId) != 0) {
2192 result = EFFECT_SESSION;
2193 }
2194
2195 for (size_t i = 0; i < mTracks.size(); ++i) {
2196 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002197 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002198 result |= TRACK_SESSION;
2199 break;
2200 }
2201 }
2202
2203 return result;
2204}
2205
2206uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2207{
2208 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2209 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2210 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2211 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2212 }
2213 for (size_t i = 0; i < mTracks.size(); i++) {
2214 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002215 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002216 return AudioSystem::getStrategyForStream(track->streamType());
2217 }
2218 }
2219 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2220}
2221
2222
Phil Burk062e67a2015-02-11 13:40:50 -08002223AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002224{
2225 Mutex::Autolock _l(mLock);
2226 return mOutput;
2227}
2228
Phil Burk062e67a2015-02-11 13:40:50 -08002229AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002230{
2231 Mutex::Autolock _l(mLock);
2232 AudioStreamOut *output = mOutput;
2233 mOutput = NULL;
2234 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2235 // must push a NULL and wait for ack
2236 mOutputSink.clear();
2237 mPipeSink.clear();
2238 mNormalSink.clear();
2239 return output;
2240}
2241
2242// this method must always be called either with ThreadBase mLock held or inside the thread loop
2243audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2244{
2245 if (mOutput == NULL) {
2246 return NULL;
2247 }
2248 return &mOutput->stream->common;
2249}
2250
2251uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2252{
2253 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2254}
2255
2256status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2257{
2258 if (!isValidSyncEvent(event)) {
2259 return BAD_VALUE;
2260 }
2261
2262 Mutex::Autolock _l(mLock);
2263
2264 for (size_t i = 0; i < mTracks.size(); ++i) {
2265 sp<Track> track = mTracks[i];
2266 if (event->triggerSession() == track->sessionId()) {
2267 (void) track->setSyncEvent(event);
2268 return NO_ERROR;
2269 }
2270 }
2271
2272 return NAME_NOT_FOUND;
2273}
2274
2275bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2276{
2277 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2278}
2279
2280void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2281 const Vector< sp<Track> >& tracksToRemove)
2282{
2283 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002284 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002285 for (size_t i = 0 ; i < count ; i++) {
2286 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002287 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002288 AudioSystem::stopOutput(mId, track->streamType(),
2289 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002290#ifdef ADD_BATTERY_DATA
2291 // to track the speaker usage
2292 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2293#endif
2294 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002295 AudioSystem::releaseOutput(mId, track->streamType(),
2296 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297 }
Eric Laurent81784c32012-11-19 14:55:58 -08002298 }
2299 }
2300 }
Eric Laurent81784c32012-11-19 14:55:58 -08002301}
2302
2303void AudioFlinger::PlaybackThread::checkSilentMode_l()
2304{
2305 if (!mMasterMute) {
2306 char value[PROPERTY_VALUE_MAX];
2307 if (property_get("ro.audio.silent", value, "0") > 0) {
2308 char *endptr;
2309 unsigned long ul = strtoul(value, &endptr, 0);
2310 if (*endptr == '\0' && ul != 0) {
2311 ALOGD("Silence is golden");
2312 // The setprop command will not allow a property to be changed after
2313 // the first time it is set, so we don't have to worry about un-muting.
2314 setMasterMute_l(true);
2315 }
2316 }
2317 }
2318}
2319
2320// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002321ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002322{
2323 // FIXME rewrite to reduce number of system calls
2324 mLastWriteTime = systemTime();
2325 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002327 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002328
2329 // If an NBAIO sink is present, use it to write the normal mixer's submix
2330 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002331
Andy Hung010a1a12014-03-13 13:57:33 -07002332 const size_t count = mBytesRemaining / mFrameSize;
2333
Simon Wilson2d590962012-11-29 15:18:50 -08002334 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002335 // update the setpoint when AudioFlinger::mScreenState changes
2336 uint32_t screenState = AudioFlinger::mScreenState;
2337 if (screenState != mScreenState) {
2338 mScreenState = screenState;
2339 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2340 if (pipe != NULL) {
2341 pipe->setAvgFrames((mScreenState & 1) ?
2342 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2343 }
2344 }
Andy Hung010a1a12014-03-13 13:57:33 -07002345 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002346 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002347 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002348 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002349 } else {
2350 bytesWritten = framesWritten;
2351 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002352 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002353 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002354 if (status == NO_ERROR) {
2355 size_t totalFramesWritten = mNormalSink->framesWritten();
2356 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2357 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002358 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002359 mLatchDValid = true;
2360 }
2361 }
Eric Laurent81784c32012-11-19 14:55:58 -08002362 // otherwise use the HAL / AudioStreamOut directly
2363 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002365
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002367 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2368 mWriteAckSequence += 2;
2369 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002371 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002373 // FIXME We should have an implementation of timestamps for direct output threads.
2374 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002375 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 if (mUseAsyncWrite &&
2377 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2378 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002379 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002381 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002382 }
Eric Laurent81784c32012-11-19 14:55:58 -08002383 }
2384
Eric Laurent81784c32012-11-19 14:55:58 -08002385 mNumWrites++;
2386 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002387 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388 return bytesWritten;
2389}
2390
2391void AudioFlinger::PlaybackThread::threadLoop_drain()
2392{
2393 if (mOutput->stream->drain) {
2394 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2395 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002396 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2397 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002398 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002399 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002400 }
2401 mOutput->stream->drain(mOutput->stream,
2402 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2403 : AUDIO_DRAIN_ALL);
2404 }
2405}
2406
2407void AudioFlinger::PlaybackThread::threadLoop_exit()
2408{
Eric Laurent275e8e92014-11-30 15:14:47 -08002409 {
2410 Mutex::Autolock _l(mLock);
2411 for (size_t i = 0; i < mTracks.size(); i++) {
2412 sp<Track> track = mTracks[i];
2413 track->invalidate();
2414 }
2415 }
Eric Laurent81784c32012-11-19 14:55:58 -08002416}
2417
2418/*
2419The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002420 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002421 - activeSleepTime from activeSleepTimeUs()
2422 - idleSleepTime from idleSleepTimeUs()
2423 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2424 - maxPeriod from frame count and sample rate (MIXER only)
2425
2426The parameters that affect these derived values are:
2427 - frame count
2428 - frame size
2429 - sample rate
2430 - device type: A2DP or not
2431 - device latency
2432 - format: PCM or not
2433 - active sleep time
2434 - idle sleep time
2435*/
2436
2437void AudioFlinger::PlaybackThread::cacheParameters_l()
2438{
Andy Hung25c2dac2014-02-27 14:56:00 -08002439 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002440 activeSleepTime = activeSleepTimeUs();
2441 idleSleepTime = idleSleepTimeUs();
2442}
2443
2444void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2445{
Glenn Kasten7c027242012-12-26 14:43:16 -08002446 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002447 this, streamType, mTracks.size());
2448 Mutex::Autolock _l(mLock);
2449
2450 size_t size = mTracks.size();
2451 for (size_t i = 0; i < size; i++) {
2452 sp<Track> t = mTracks[i];
2453 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002454 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002455 }
2456 }
2457}
2458
2459status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2460{
2461 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002462 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2463 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002464 bool ownsBuffer = false;
2465
2466 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2467 if (session > 0) {
2468 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002469 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002470 if (mType != DIRECT) {
2471 size_t numSamples = mNormalFrameCount * mChannelCount;
2472 buffer = new int16_t[numSamples];
2473 memset(buffer, 0, numSamples * sizeof(int16_t));
2474 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2475 ownsBuffer = true;
2476 }
2477
2478 // Attach all tracks with same session ID to this chain.
2479 for (size_t i = 0; i < mTracks.size(); ++i) {
2480 sp<Track> track = mTracks[i];
2481 if (session == track->sessionId()) {
2482 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2483 buffer);
2484 track->setMainBuffer(buffer);
2485 chain->incTrackCnt();
2486 }
2487 }
2488
2489 // indicate all active tracks in the chain
2490 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2491 sp<Track> track = mActiveTracks[i].promote();
2492 if (track == 0) {
2493 continue;
2494 }
2495 if (session == track->sessionId()) {
2496 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2497 chain->incActiveTrackCnt();
2498 }
2499 }
2500 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002501 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002502 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002503 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2504 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002505 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2506 // chains list in order to be processed last as it contains output stage effects
2507 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2508 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2509 // after track specific effects and before output stage
2510 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2511 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2512 // Effect chain for other sessions are inserted at beginning of effect
2513 // chains list to be processed before output mix effects. Relative order between other
2514 // sessions is not important
2515 size_t size = mEffectChains.size();
2516 size_t i = 0;
2517 for (i = 0; i < size; i++) {
2518 if (mEffectChains[i]->sessionId() < session) {
2519 break;
2520 }
2521 }
2522 mEffectChains.insertAt(chain, i);
2523 checkSuspendOnAddEffectChain_l(chain);
2524
2525 return NO_ERROR;
2526}
2527
2528size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2529{
2530 int session = chain->sessionId();
2531
2532 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2533
2534 for (size_t i = 0; i < mEffectChains.size(); i++) {
2535 if (chain == mEffectChains[i]) {
2536 mEffectChains.removeAt(i);
2537 // detach all active tracks from the chain
2538 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2539 sp<Track> track = mActiveTracks[i].promote();
2540 if (track == 0) {
2541 continue;
2542 }
2543 if (session == track->sessionId()) {
2544 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2545 chain.get(), session);
2546 chain->decActiveTrackCnt();
2547 }
2548 }
2549
2550 // detach all tracks with same session ID from this chain
2551 for (size_t i = 0; i < mTracks.size(); ++i) {
2552 sp<Track> track = mTracks[i];
2553 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002554 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002555 chain->decTrackCnt();
2556 }
2557 }
2558 break;
2559 }
2560 }
2561 return mEffectChains.size();
2562}
2563
2564status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2565 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2566{
2567 Mutex::Autolock _l(mLock);
2568 return attachAuxEffect_l(track, EffectId);
2569}
2570
2571status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2572 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2573{
2574 status_t status = NO_ERROR;
2575
2576 if (EffectId == 0) {
2577 track->setAuxBuffer(0, NULL);
2578 } else {
2579 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2580 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2581 if (effect != 0) {
2582 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2583 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2584 } else {
2585 status = INVALID_OPERATION;
2586 }
2587 } else {
2588 status = BAD_VALUE;
2589 }
2590 }
2591 return status;
2592}
2593
2594void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2595{
2596 for (size_t i = 0; i < mTracks.size(); ++i) {
2597 sp<Track> track = mTracks[i];
2598 if (track->auxEffectId() == effectId) {
2599 attachAuxEffect_l(track, 0);
2600 }
2601 }
2602}
2603
2604bool AudioFlinger::PlaybackThread::threadLoop()
2605{
2606 Vector< sp<Track> > tracksToRemove;
2607
2608 standbyTime = systemTime();
2609
2610 // MIXER
2611 nsecs_t lastWarning = 0;
2612
2613 // DUPLICATING
2614 // FIXME could this be made local to while loop?
2615 writeFrames = 0;
2616
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002617 int lastGeneration = 0;
2618
Eric Laurent81784c32012-11-19 14:55:58 -08002619 cacheParameters_l();
2620 sleepTime = idleSleepTime;
2621
2622 if (mType == MIXER) {
2623 sleepTimeShift = 0;
2624 }
2625
2626 CpuStats cpuStats;
2627 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2628
2629 acquireWakeLock();
2630
Glenn Kasten9e58b552013-01-18 15:09:48 -08002631 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2632 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2633 // and then that string will be logged at the next convenient opportunity.
2634 const char *logString = NULL;
2635
Eric Laurent664539d2013-09-23 18:24:31 -07002636 checkSilentMode_l();
2637
Eric Laurent81784c32012-11-19 14:55:58 -08002638 while (!exitPending())
2639 {
2640 cpuStats.sample(myName);
2641
2642 Vector< sp<EffectChain> > effectChains;
2643
Eric Laurent81784c32012-11-19 14:55:58 -08002644 { // scope for mLock
2645
2646 Mutex::Autolock _l(mLock);
2647
Eric Laurent021cf962014-05-13 10:18:14 -07002648 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002649
Glenn Kasten9e58b552013-01-18 15:09:48 -08002650 if (logString != NULL) {
2651 mNBLogWriter->logTimestamp();
2652 mNBLogWriter->log(logString);
2653 logString = NULL;
2654 }
2655
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002656 // Gather the framesReleased counters for all active tracks,
2657 // and latch them atomically with the timestamp.
2658 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2659 mLatchD.mFramesReleased.clear();
2660 size_t size = mActiveTracks.size();
2661 for (size_t i = 0; i < size; i++) {
2662 sp<Track> t = mActiveTracks[i].promote();
2663 if (t != 0) {
2664 mLatchD.mFramesReleased.add(t.get(),
2665 t->mAudioTrackServerProxy->framesReleased());
2666 }
2667 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002668 if (mLatchDValid) {
2669 mLatchQ = mLatchD;
2670 mLatchDValid = false;
2671 mLatchQValid = true;
2672 }
2673
Eric Laurent81784c32012-11-19 14:55:58 -08002674 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 if (mSignalPending) {
2676 // A signal was raised while we were unlocked
2677 mSignalPending = false;
2678 } else if (waitingAsyncCallback_l()) {
2679 if (exitPending()) {
2680 break;
2681 }
2682 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002683 mWakeLockUids.clear();
2684 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685 ALOGV("wait async completion");
2686 mWaitWorkCV.wait(mLock);
2687 ALOGV("async completion/wake");
2688 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002689 standbyTime = systemTime() + standbyDelay;
2690 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002691
2692 continue;
2693 }
2694 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002695 isSuspended()) {
2696 // put audio hardware into standby after short delay
2697 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002698
2699 threadLoop_standby();
2700
2701 mStandby = true;
2702 }
2703
2704 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2705 // we're about to wait, flush the binder command buffer
2706 IPCThreadState::self()->flushCommands();
2707
2708 clearOutputTracks();
2709
2710 if (exitPending()) {
2711 break;
2712 }
2713
2714 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002715 mWakeLockUids.clear();
2716 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002717 // wait until we have something to do...
2718 ALOGV("%s going to sleep", myName.string());
2719 mWaitWorkCV.wait(mLock);
2720 ALOGV("%s waking up", myName.string());
2721 acquireWakeLock_l();
2722
2723 mMixerStatus = MIXER_IDLE;
2724 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2725 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002726 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002727 checkSilentMode_l();
2728
2729 standbyTime = systemTime() + standbyDelay;
2730 sleepTime = idleSleepTime;
2731 if (mType == MIXER) {
2732 sleepTimeShift = 0;
2733 }
2734
2735 continue;
2736 }
2737 }
Eric Laurent81784c32012-11-19 14:55:58 -08002738 // mMixerStatusIgnoringFastTracks is also updated internally
2739 mMixerStatus = prepareTracks_l(&tracksToRemove);
2740
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002741 // compare with previously applied list
2742 if (lastGeneration != mActiveTracksGeneration) {
2743 // update wakelock
2744 updateWakeLockUids_l(mWakeLockUids);
2745 lastGeneration = mActiveTracksGeneration;
2746 }
2747
Eric Laurent81784c32012-11-19 14:55:58 -08002748 // prevent any changes in effect chain list and in each effect chain
2749 // during mixing and effect process as the audio buffers could be deleted
2750 // or modified if an effect is created or deleted
2751 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002752 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002753
Eric Laurentbfb1b832013-01-07 09:53:42 -08002754 if (mBytesRemaining == 0) {
2755 mCurrentWriteLength = 0;
2756 if (mMixerStatus == MIXER_TRACKS_READY) {
2757 // threadLoop_mix() sets mCurrentWriteLength
2758 threadLoop_mix();
2759 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2760 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2761 // threadLoop_sleepTime sets sleepTime to 0 if data
2762 // must be written to HAL
2763 threadLoop_sleepTime();
2764 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002765 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002766 }
2767 }
Andy Hung98ef9782014-03-04 14:46:50 -08002768 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2769 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2770 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2771 // or mSinkBuffer (if there are no effects).
2772 //
2773 // This is done pre-effects computation; if effects change to
2774 // support higher precision, this needs to move.
2775 //
2776 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2777 // TODO use sleepTime == 0 as an additional condition.
2778 if (mMixerBufferValid) {
2779 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2780 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2781
2782 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2783 mNormalFrameCount * mChannelCount);
2784 }
2785
Eric Laurentbfb1b832013-01-07 09:53:42 -08002786 mBytesRemaining = mCurrentWriteLength;
2787 if (isSuspended()) {
2788 sleepTime = suspendSleepTimeUs();
2789 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002790 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 mBytesRemaining = 0;
2792 }
Eric Laurent81784c32012-11-19 14:55:58 -08002793
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002795 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 for (size_t i = 0; i < effectChains.size(); i ++) {
2797 effectChains[i]->process_l();
2798 }
Eric Laurent81784c32012-11-19 14:55:58 -08002799 }
2800 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002801 // Process effect chains for offloaded thread even if no audio
2802 // was read from audio track: process only updates effect state
2803 // and thus does have to be synchronized with audio writes but may have
2804 // to be called while waiting for async write callback
2805 if (mType == OFFLOAD) {
2806 for (size_t i = 0; i < effectChains.size(); i ++) {
2807 effectChains[i]->process_l();
2808 }
2809 }
Eric Laurent81784c32012-11-19 14:55:58 -08002810
Andy Hung98ef9782014-03-04 14:46:50 -08002811 // Only if the Effects buffer is enabled and there is data in the
2812 // Effects buffer (buffer valid), we need to
2813 // copy into the sink buffer.
2814 // TODO use sleepTime == 0 as an additional condition.
2815 if (mEffectBufferValid) {
2816 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2817 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2818 mNormalFrameCount * mChannelCount);
2819 }
2820
Eric Laurent81784c32012-11-19 14:55:58 -08002821 // enable changes in effect chain
2822 unlockEffectChains(effectChains);
2823
Eric Laurentbfb1b832013-01-07 09:53:42 -08002824 if (!waitingAsyncCallback()) {
2825 // sleepTime == 0 means we must write to audio hardware
2826 if (sleepTime == 0) {
2827 if (mBytesRemaining) {
2828 ssize_t ret = threadLoop_write();
2829 if (ret < 0) {
2830 mBytesRemaining = 0;
2831 } else {
2832 mBytesWritten += ret;
2833 mBytesRemaining -= ret;
2834 }
2835 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2836 (mMixerStatus == MIXER_DRAIN_ALL)) {
2837 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002838 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002839 if (mType == MIXER) {
2840 // write blocked detection
2841 nsecs_t now = systemTime();
2842 nsecs_t delta = now - mLastWriteTime;
2843 if (!mStandby && delta > maxPeriod) {
2844 mNumDelayedWrites++;
2845 if ((now - lastWarning) > kWarningThrottleNs) {
2846 ATRACE_NAME("underrun");
2847 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2848 ns2ms(delta), mNumDelayedWrites, this);
2849 lastWarning = now;
2850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002851 }
2852 }
Eric Laurent81784c32012-11-19 14:55:58 -08002853
Eric Laurentbfb1b832013-01-07 09:53:42 -08002854 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002855 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002857 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 }
Eric Laurent81784c32012-11-19 14:55:58 -08002859 }
2860
2861 // Finally let go of removed track(s), without the lock held
2862 // since we can't guarantee the destructors won't acquire that
2863 // same lock. This will also mutate and push a new fast mixer state.
2864 threadLoop_removeTracks(tracksToRemove);
2865 tracksToRemove.clear();
2866
2867 // FIXME I don't understand the need for this here;
2868 // it was in the original code but maybe the
2869 // assignment in saveOutputTracks() makes this unnecessary?
2870 clearOutputTracks();
2871
2872 // Effect chains will be actually deleted here if they were removed from
2873 // mEffectChains list during mixing or effects processing
2874 effectChains.clear();
2875
2876 // FIXME Note that the above .clear() is no longer necessary since effectChains
2877 // is now local to this block, but will keep it for now (at least until merge done).
2878 }
2879
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 threadLoop_exit();
2881
Eric Laurentcf817a22014-08-04 20:36:31 -07002882 if (!mStandby) {
2883 threadLoop_standby();
2884 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002885 }
2886
2887 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002888 mWakeLockUids.clear();
2889 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002890
2891 ALOGV("Thread %p type %d exiting", this, mType);
2892 return false;
2893}
2894
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895// removeTracks_l() must be called with ThreadBase::mLock held
2896void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2897{
2898 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002899 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900 for (size_t i=0 ; i<count ; i++) {
2901 const sp<Track>& track = tracksToRemove.itemAt(i);
2902 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002903 mWakeLockUids.remove(track->uid());
2904 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2906 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2907 if (chain != 0) {
2908 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2909 track->sessionId());
2910 chain->decActiveTrackCnt();
2911 }
2912 if (track->isTerminated()) {
2913 removeTrack_l(track);
2914 }
2915 }
2916 }
2917
2918}
Eric Laurent81784c32012-11-19 14:55:58 -08002919
Eric Laurentaccc1472013-09-20 09:36:34 -07002920status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2921{
2922 if (mNormalSink != 0) {
2923 return mNormalSink->getTimestamp(timestamp);
2924 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002925 if ((mType == OFFLOAD || mType == DIRECT)
2926 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002927 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002928 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002929 if (ret == 0) {
2930 timestamp.mPosition = (uint32_t)position64;
2931 return NO_ERROR;
2932 }
2933 }
2934 return INVALID_OPERATION;
2935}
Eric Laurent1c333e22014-05-20 10:48:17 -07002936
Eric Laurent054d9d32015-04-24 08:48:48 -07002937status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
2938 audio_patch_handle_t *handle)
2939{
2940 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2941 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2942 if (mFastMixer != 0) {
2943 FastMixerStateQueue *sq = mFastMixer->sq();
2944 FastMixerState *state = sq->begin();
2945 if (!(state->mCommand & FastMixerState::IDLE)) {
2946 previousCommand = state->mCommand;
2947 state->mCommand = FastMixerState::HOT_IDLE;
2948 sq->end();
2949 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2950 } else {
2951 sq->end(false /*didModify*/);
2952 }
2953 }
2954 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
2955
2956 if (!(previousCommand & FastMixerState::IDLE)) {
2957 ALOG_ASSERT(mFastMixer != 0);
2958 FastMixerStateQueue *sq = mFastMixer->sq();
2959 FastMixerState *state = sq->begin();
2960 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
2961 state->mCommand = previousCommand;
2962 sq->end();
2963 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2964 }
2965
2966 return status;
2967}
2968
Eric Laurent1c333e22014-05-20 10:48:17 -07002969status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2970 audio_patch_handle_t *handle)
2971{
2972 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07002973
2974 // store new device and send to effects
2975 audio_devices_t type = AUDIO_DEVICE_NONE;
2976 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2977 type |= patch->sinks[i].ext.device.type;
2978 }
2979
2980#ifdef ADD_BATTERY_DATA
2981 // when changing the audio output device, call addBatteryData to notify
2982 // the change
2983 if (mOutDevice != type) {
2984 uint32_t params = 0;
2985 // check whether speaker is on
2986 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
2987 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07002988 }
2989
Eric Laurent054d9d32015-04-24 08:48:48 -07002990 audio_devices_t deviceWithoutSpeaker
2991 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
2992 // check if any other device (except speaker) is on
2993 if (type & deviceWithoutSpeaker) {
2994 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2995 }
2996
2997 if (params != 0) {
2998 addBatteryData(params);
2999 }
3000 }
3001#endif
3002
3003 for (size_t i = 0; i < mEffectChains.size(); i++) {
3004 mEffectChains[i]->setDevice_l(type);
3005 }
3006 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003007 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003008
3009 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003010 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3011 status = hwDevice->create_audio_patch(hwDevice,
3012 patch->num_sources,
3013 patch->sources,
3014 patch->num_sinks,
3015 patch->sinks,
3016 handle);
3017 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003018 char *address;
3019 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3020 //FIXME: we only support address on first sink with HAL version < 3.0
3021 address = audio_device_address_to_parameter(
3022 patch->sinks[0].ext.device.type,
3023 patch->sinks[0].ext.device.address);
3024 } else {
3025 address = (char *)calloc(1, 1);
3026 }
3027 AudioParameter param = AudioParameter(String8(address));
3028 free(address);
3029 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3030 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3031 param.toString().string());
3032 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003033 }
Eric Laurent296fb132015-05-01 11:38:42 -07003034 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003035 return status;
3036}
3037
Eric Laurent054d9d32015-04-24 08:48:48 -07003038status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3039{
3040 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3041 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3042 if (mFastMixer != 0) {
3043 FastMixerStateQueue *sq = mFastMixer->sq();
3044 FastMixerState *state = sq->begin();
3045 if (!(state->mCommand & FastMixerState::IDLE)) {
3046 previousCommand = state->mCommand;
3047 state->mCommand = FastMixerState::HOT_IDLE;
3048 sq->end();
3049 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3050 } else {
3051 sq->end(false /*didModify*/);
3052 }
3053 }
3054
3055 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3056
3057 if (!(previousCommand & FastMixerState::IDLE)) {
3058 ALOG_ASSERT(mFastMixer != 0);
3059 FastMixerStateQueue *sq = mFastMixer->sq();
3060 FastMixerState *state = sq->begin();
3061 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3062 state->mCommand = previousCommand;
3063 sq->end();
3064 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3065 }
3066
3067 return status;
3068}
3069
Eric Laurent1c333e22014-05-20 10:48:17 -07003070status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3071{
3072 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003073
3074 mOutDevice = AUDIO_DEVICE_NONE;
3075
Eric Laurent1c333e22014-05-20 10:48:17 -07003076 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3077 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3078 status = hwDevice->release_audio_patch(hwDevice, handle);
3079 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003080 AudioParameter param;
3081 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3082 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3083 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003084 }
3085 return status;
3086}
3087
Eric Laurent83b88082014-06-20 18:31:16 -07003088void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3089{
3090 Mutex::Autolock _l(mLock);
3091 mTracks.add(track);
3092}
3093
3094void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3095{
3096 Mutex::Autolock _l(mLock);
3097 destroyTrack_l(track);
3098}
3099
3100void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3101{
3102 ThreadBase::getAudioPortConfig(config);
3103 config->role = AUDIO_PORT_ROLE_SOURCE;
3104 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3105 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3106}
3107
Eric Laurent81784c32012-11-19 14:55:58 -08003108// ----------------------------------------------------------------------------
3109
3110AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
3111 audio_io_handle_t id, audio_devices_t device, type_t type)
3112 : PlaybackThread(audioFlinger, output, id, device, type),
3113 // mAudioMixer below
3114 // mFastMixer below
3115 mFastMixerFutex(0)
3116 // mOutputSink below
3117 // mPipeSink below
3118 // mNormalSink below
3119{
3120 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003121 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003122 "mFrameCount=%d, mNormalFrameCount=%d",
3123 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3124 mNormalFrameCount);
3125 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3126
Andy Hungfbfc3952015-01-15 13:33:51 -08003127 if (type == DUPLICATING) {
3128 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3129 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3130 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3131 return;
3132 }
Eric Laurent81784c32012-11-19 14:55:58 -08003133 // create an NBAIO sink for the HAL output stream, and negotiate
3134 mOutputSink = new AudioStreamOutSink(output->stream);
3135 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003136 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003137 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3138 ALOG_ASSERT(index == 0);
3139
3140 // initialize fast mixer depending on configuration
3141 bool initFastMixer;
3142 switch (kUseFastMixer) {
3143 case FastMixer_Never:
3144 initFastMixer = false;
3145 break;
3146 case FastMixer_Always:
3147 initFastMixer = true;
3148 break;
3149 case FastMixer_Static:
3150 case FastMixer_Dynamic:
3151 initFastMixer = mFrameCount < mNormalFrameCount;
3152 break;
3153 }
3154 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003155 audio_format_t fastMixerFormat;
3156 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3157 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3158 } else {
3159 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3160 }
3161 if (mFormat != fastMixerFormat) {
3162 // change our Sink format to accept our intermediate precision
3163 mFormat = fastMixerFormat;
3164 free(mSinkBuffer);
3165 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3166 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3167 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3168 }
Eric Laurent81784c32012-11-19 14:55:58 -08003169
3170 // create a MonoPipe to connect our submix to FastMixer
3171 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003172 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003173 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003174 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003175 format.mFormat = fastMixerFormat;
3176 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3177
Eric Laurent81784c32012-11-19 14:55:58 -08003178 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3179 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3180 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3181 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3182 const NBAIO_Format offers[1] = {format};
3183 size_t numCounterOffers = 0;
3184 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3185 ALOG_ASSERT(index == 0);
3186 monoPipe->setAvgFrames((mScreenState & 1) ?
3187 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3188 mPipeSink = monoPipe;
3189
Glenn Kasten46909e72013-02-26 09:20:22 -08003190#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003191 if (mTeeSinkOutputEnabled) {
3192 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003193 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3194 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003195 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003196 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003197 ALOG_ASSERT(index == 0);
3198 mTeeSink = teeSink;
3199 PipeReader *teeSource = new PipeReader(*teeSink);
3200 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003201 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003202 ALOG_ASSERT(index == 0);
3203 mTeeSource = teeSource;
3204 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003205#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003206
3207 // create fast mixer and configure it initially with just one fast track for our submix
3208 mFastMixer = new FastMixer();
3209 FastMixerStateQueue *sq = mFastMixer->sq();
3210#ifdef STATE_QUEUE_DUMP
3211 sq->setObserverDump(&mStateQueueObserverDump);
3212 sq->setMutatorDump(&mStateQueueMutatorDump);
3213#endif
3214 FastMixerState *state = sq->begin();
3215 FastTrack *fastTrack = &state->mFastTracks[0];
3216 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3217 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3218 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003219 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3220 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003221 fastTrack->mGeneration++;
3222 state->mFastTracksGen++;
3223 state->mTrackMask = 1;
3224 // fast mixer will use the HAL output sink
3225 state->mOutputSink = mOutputSink.get();
3226 state->mOutputSinkGen++;
3227 state->mFrameCount = mFrameCount;
3228 state->mCommand = FastMixerState::COLD_IDLE;
3229 // already done in constructor initialization list
3230 //mFastMixerFutex = 0;
3231 state->mColdFutexAddr = &mFastMixerFutex;
3232 state->mColdGen++;
3233 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003234#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003235 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003236#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003237 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3238 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003239 sq->end();
3240 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3241
3242 // start the fast mixer
3243 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3244 pid_t tid = mFastMixer->getTid();
3245 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3246 if (err != 0) {
3247 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3248 kPriorityFastMixer, getpid_cached, tid, err);
3249 }
3250
3251#ifdef AUDIO_WATCHDOG
3252 // create and start the watchdog
3253 mAudioWatchdog = new AudioWatchdog();
3254 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3255 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3256 tid = mAudioWatchdog->getTid();
3257 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3258 if (err != 0) {
3259 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3260 kPriorityFastMixer, getpid_cached, tid, err);
3261 }
3262#endif
3263
Eric Laurent81784c32012-11-19 14:55:58 -08003264 }
3265
3266 switch (kUseFastMixer) {
3267 case FastMixer_Never:
3268 case FastMixer_Dynamic:
3269 mNormalSink = mOutputSink;
3270 break;
3271 case FastMixer_Always:
3272 mNormalSink = mPipeSink;
3273 break;
3274 case FastMixer_Static:
3275 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3276 break;
3277 }
3278}
3279
3280AudioFlinger::MixerThread::~MixerThread()
3281{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003282 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003283 FastMixerStateQueue *sq = mFastMixer->sq();
3284 FastMixerState *state = sq->begin();
3285 if (state->mCommand == FastMixerState::COLD_IDLE) {
3286 int32_t old = android_atomic_inc(&mFastMixerFutex);
3287 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003288 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003289 }
3290 }
3291 state->mCommand = FastMixerState::EXIT;
3292 sq->end();
3293 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3294 mFastMixer->join();
3295 // Though the fast mixer thread has exited, it's state queue is still valid.
3296 // We'll use that extract the final state which contains one remaining fast track
3297 // corresponding to our sub-mix.
3298 state = sq->begin();
3299 ALOG_ASSERT(state->mTrackMask == 1);
3300 FastTrack *fastTrack = &state->mFastTracks[0];
3301 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3302 delete fastTrack->mBufferProvider;
3303 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003304 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003305#ifdef AUDIO_WATCHDOG
3306 if (mAudioWatchdog != 0) {
3307 mAudioWatchdog->requestExit();
3308 mAudioWatchdog->requestExitAndWait();
3309 mAudioWatchdog.clear();
3310 }
3311#endif
3312 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003313 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003314 delete mAudioMixer;
3315}
3316
3317
3318uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3319{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003320 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003321 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3322 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3323 }
3324 return latency;
3325}
3326
3327
3328void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3329{
3330 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3331}
3332
Eric Laurentbfb1b832013-01-07 09:53:42 -08003333ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003334{
3335 // FIXME we should only do one push per cycle; confirm this is true
3336 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003337 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003338 FastMixerStateQueue *sq = mFastMixer->sq();
3339 FastMixerState *state = sq->begin();
3340 if (state->mCommand != FastMixerState::MIX_WRITE &&
3341 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3342 if (state->mCommand == FastMixerState::COLD_IDLE) {
3343 int32_t old = android_atomic_inc(&mFastMixerFutex);
3344 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003345 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003346 }
3347#ifdef AUDIO_WATCHDOG
3348 if (mAudioWatchdog != 0) {
3349 mAudioWatchdog->resume();
3350 }
3351#endif
3352 }
3353 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003354#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003355 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003356 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003357#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003358 sq->end();
3359 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3360 if (kUseFastMixer == FastMixer_Dynamic) {
3361 mNormalSink = mPipeSink;
3362 }
3363 } else {
3364 sq->end(false /*didModify*/);
3365 }
3366 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003368}
3369
3370void AudioFlinger::MixerThread::threadLoop_standby()
3371{
3372 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003373 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003374 FastMixerStateQueue *sq = mFastMixer->sq();
3375 FastMixerState *state = sq->begin();
3376 if (!(state->mCommand & FastMixerState::IDLE)) {
3377 state->mCommand = FastMixerState::COLD_IDLE;
3378 state->mColdFutexAddr = &mFastMixerFutex;
3379 state->mColdGen++;
3380 mFastMixerFutex = 0;
3381 sq->end();
3382 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3383 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3384 if (kUseFastMixer == FastMixer_Dynamic) {
3385 mNormalSink = mOutputSink;
3386 }
3387#ifdef AUDIO_WATCHDOG
3388 if (mAudioWatchdog != 0) {
3389 mAudioWatchdog->pause();
3390 }
3391#endif
3392 } else {
3393 sq->end(false /*didModify*/);
3394 }
3395 }
3396 PlaybackThread::threadLoop_standby();
3397}
3398
Eric Laurentbfb1b832013-01-07 09:53:42 -08003399bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3400{
3401 return false;
3402}
3403
3404bool AudioFlinger::PlaybackThread::shouldStandby_l()
3405{
3406 return !mStandby;
3407}
3408
3409bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3410{
3411 Mutex::Autolock _l(mLock);
3412 return waitingAsyncCallback_l();
3413}
3414
Eric Laurent81784c32012-11-19 14:55:58 -08003415// shared by MIXER and DIRECT, overridden by DUPLICATING
3416void AudioFlinger::PlaybackThread::threadLoop_standby()
3417{
3418 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003419 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003420 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003421 // discard any pending drain or write ack by incrementing sequence
3422 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3423 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003424 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003425 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3426 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003427 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003428 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003429}
3430
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003431void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3432{
3433 ALOGV("signal playback thread");
3434 broadcast_l();
3435}
3436
Eric Laurent81784c32012-11-19 14:55:58 -08003437void AudioFlinger::MixerThread::threadLoop_mix()
3438{
3439 // obtain the presentation timestamp of the next output buffer
3440 int64_t pts;
3441 status_t status = INVALID_OPERATION;
3442
3443 if (mNormalSink != 0) {
3444 status = mNormalSink->getNextWriteTimestamp(&pts);
3445 } else {
3446 status = mOutputSink->getNextWriteTimestamp(&pts);
3447 }
3448
3449 if (status != NO_ERROR) {
3450 pts = AudioBufferProvider::kInvalidPTS;
3451 }
3452
3453 // mix buffers...
3454 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003455 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003456 // increase sleep time progressively when application underrun condition clears.
3457 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3458 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3459 // such that we would underrun the audio HAL.
3460 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3461 sleepTimeShift--;
3462 }
3463 sleepTime = 0;
3464 standbyTime = systemTime() + standbyDelay;
3465 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003466
Eric Laurent81784c32012-11-19 14:55:58 -08003467}
3468
3469void AudioFlinger::MixerThread::threadLoop_sleepTime()
3470{
3471 // If no tracks are ready, sleep once for the duration of an output
3472 // buffer size, then write 0s to the output
3473 if (sleepTime == 0) {
3474 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3475 sleepTime = activeSleepTime >> sleepTimeShift;
3476 if (sleepTime < kMinThreadSleepTimeUs) {
3477 sleepTime = kMinThreadSleepTimeUs;
3478 }
3479 // reduce sleep time in case of consecutive application underruns to avoid
3480 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3481 // duration we would end up writing less data than needed by the audio HAL if
3482 // the condition persists.
3483 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3484 sleepTimeShift++;
3485 }
3486 } else {
3487 sleepTime = idleSleepTime;
3488 }
3489 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003490 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3491 // before effects processing or output.
3492 if (mMixerBufferValid) {
3493 memset(mMixerBuffer, 0, mMixerBufferSize);
3494 } else {
3495 memset(mSinkBuffer, 0, mSinkBufferSize);
3496 }
Eric Laurent81784c32012-11-19 14:55:58 -08003497 sleepTime = 0;
3498 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3499 "anticipated start");
3500 }
3501 // TODO add standby time extension fct of effect tail
3502}
3503
3504// prepareTracks_l() must be called with ThreadBase::mLock held
3505AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3506 Vector< sp<Track> > *tracksToRemove)
3507{
3508
3509 mixer_state mixerStatus = MIXER_IDLE;
3510 // find out which tracks need to be processed
3511 size_t count = mActiveTracks.size();
3512 size_t mixedTracks = 0;
3513 size_t tracksWithEffect = 0;
3514 // counts only _active_ fast tracks
3515 size_t fastTracks = 0;
3516 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3517
3518 float masterVolume = mMasterVolume;
3519 bool masterMute = mMasterMute;
3520
3521 if (masterMute) {
3522 masterVolume = 0;
3523 }
3524 // Delegate master volume control to effect in output mix effect chain if needed
3525 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3526 if (chain != 0) {
3527 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3528 chain->setVolume_l(&v, &v);
3529 masterVolume = (float)((v + (1 << 23)) >> 24);
3530 chain.clear();
3531 }
3532
3533 // prepare a new state to push
3534 FastMixerStateQueue *sq = NULL;
3535 FastMixerState *state = NULL;
3536 bool didModify = false;
3537 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003538 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003539 sq = mFastMixer->sq();
3540 state = sq->begin();
3541 }
3542
Andy Hung69aed5f2014-02-25 17:24:40 -08003543 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003544 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003545
Eric Laurent81784c32012-11-19 14:55:58 -08003546 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003547 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003548 if (t == 0) {
3549 continue;
3550 }
3551
3552 // this const just means the local variable doesn't change
3553 Track* const track = t.get();
3554
3555 // process fast tracks
3556 if (track->isFastTrack()) {
3557
3558 // It's theoretically possible (though unlikely) for a fast track to be created
3559 // and then removed within the same normal mix cycle. This is not a problem, as
3560 // the track never becomes active so it's fast mixer slot is never touched.
3561 // The converse, of removing an (active) track and then creating a new track
3562 // at the identical fast mixer slot within the same normal mix cycle,
3563 // is impossible because the slot isn't marked available until the end of each cycle.
3564 int j = track->mFastIndex;
3565 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3566 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3567 FastTrack *fastTrack = &state->mFastTracks[j];
3568
3569 // Determine whether the track is currently in underrun condition,
3570 // and whether it had a recent underrun.
3571 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3572 FastTrackUnderruns underruns = ftDump->mUnderruns;
3573 uint32_t recentFull = (underruns.mBitFields.mFull -
3574 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3575 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3576 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3577 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3578 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3579 uint32_t recentUnderruns = recentPartial + recentEmpty;
3580 track->mObservedUnderruns = underruns;
3581 // don't count underruns that occur while stopping or pausing
3582 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003583 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3584 recentUnderruns > 0) {
3585 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3586 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003587 }
3588
3589 // This is similar to the state machine for normal tracks,
3590 // with a few modifications for fast tracks.
3591 bool isActive = true;
3592 switch (track->mState) {
3593 case TrackBase::STOPPING_1:
3594 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003596 track->mState = TrackBase::STOPPING_2;
3597 }
3598 break;
3599 case TrackBase::PAUSING:
3600 // ramp down is not yet implemented
3601 track->setPaused();
3602 break;
3603 case TrackBase::RESUMING:
3604 // ramp up is not yet implemented
3605 track->mState = TrackBase::ACTIVE;
3606 break;
3607 case TrackBase::ACTIVE:
3608 if (recentFull > 0 || recentPartial > 0) {
3609 // track has provided at least some frames recently: reset retry count
3610 track->mRetryCount = kMaxTrackRetries;
3611 }
3612 if (recentUnderruns == 0) {
3613 // no recent underruns: stay active
3614 break;
3615 }
3616 // there has recently been an underrun of some kind
3617 if (track->sharedBuffer() == 0) {
3618 // were any of the recent underruns "empty" (no frames available)?
3619 if (recentEmpty == 0) {
3620 // no, then ignore the partial underruns as they are allowed indefinitely
3621 break;
3622 }
3623 // there has recently been an "empty" underrun: decrement the retry counter
3624 if (--(track->mRetryCount) > 0) {
3625 break;
3626 }
3627 // indicate to client process that the track was disabled because of underrun;
3628 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003629 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003630 // remove from active list, but state remains ACTIVE [confusing but true]
3631 isActive = false;
3632 break;
3633 }
3634 // fall through
3635 case TrackBase::STOPPING_2:
3636 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003637 case TrackBase::STOPPED:
3638 case TrackBase::FLUSHED: // flush() while active
3639 // Check for presentation complete if track is inactive
3640 // We have consumed all the buffers of this track.
3641 // This would be incomplete if we auto-paused on underrun
3642 {
3643 size_t audioHALFrames =
3644 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3645 size_t framesWritten = mBytesWritten / mFrameSize;
3646 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3647 // track stays in active list until presentation is complete
3648 break;
3649 }
3650 }
3651 if (track->isStopping_2()) {
3652 track->mState = TrackBase::STOPPED;
3653 }
3654 if (track->isStopped()) {
3655 // Can't reset directly, as fast mixer is still polling this track
3656 // track->reset();
3657 // So instead mark this track as needing to be reset after push with ack
3658 resetMask |= 1 << i;
3659 }
3660 isActive = false;
3661 break;
3662 case TrackBase::IDLE:
3663 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003664 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003665 }
3666
3667 if (isActive) {
3668 // was it previously inactive?
3669 if (!(state->mTrackMask & (1 << j))) {
3670 ExtendedAudioBufferProvider *eabp = track;
3671 VolumeProvider *vp = track;
3672 fastTrack->mBufferProvider = eabp;
3673 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003674 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003675 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003676 fastTrack->mGeneration++;
3677 state->mTrackMask |= 1 << j;
3678 didModify = true;
3679 // no acknowledgement required for newly active tracks
3680 }
3681 // cache the combined master volume and stream type volume for fast mixer; this
3682 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003683 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003684 ++fastTracks;
3685 } else {
3686 // was it previously active?
3687 if (state->mTrackMask & (1 << j)) {
3688 fastTrack->mBufferProvider = NULL;
3689 fastTrack->mGeneration++;
3690 state->mTrackMask &= ~(1 << j);
3691 didModify = true;
3692 // If any fast tracks were removed, we must wait for acknowledgement
3693 // because we're about to decrement the last sp<> on those tracks.
3694 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3695 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003696 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003697 }
3698 tracksToRemove->add(track);
3699 // Avoids a misleading display in dumpsys
3700 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3701 }
3702 continue;
3703 }
3704
3705 { // local variable scope to avoid goto warning
3706
3707 audio_track_cblk_t* cblk = track->cblk();
3708
3709 // The first time a track is added we wait
3710 // for all its buffers to be filled before processing it
3711 int name = track->name();
3712 // make sure that we have enough frames to mix one full buffer.
3713 // enforce this condition only once to enable draining the buffer in case the client
3714 // app does not call stop() and relies on underrun to stop:
3715 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3716 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003717 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003718 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003719 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003720
3721 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003722 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003723 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3724 // add frames already consumed but not yet released by the resampler
3725 // because mAudioTrackServerProxy->framesReady() will include these frames
3726 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3727
Eric Laurent81784c32012-11-19 14:55:58 -08003728 uint32_t minFrames = 1;
3729 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3730 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003731 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003732 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003733
3734 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003735 if (ATRACE_ENABLED()) {
3736 // I wish we had formatted trace names
3737 char traceName[16];
3738 strcpy(traceName, "nRdy");
3739 int name = track->name();
3740 if (AudioMixer::TRACK0 <= name &&
3741 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3742 name -= AudioMixer::TRACK0;
3743 traceName[4] = (name / 10) + '0';
3744 traceName[5] = (name % 10) + '0';
3745 } else {
3746 traceName[4] = '?';
3747 traceName[5] = '?';
3748 }
3749 traceName[6] = '\0';
3750 ATRACE_INT(traceName, framesReady);
3751 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003752 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003753 !track->isPaused() && !track->isTerminated())
3754 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003755 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003756
3757 mixedTracks++;
3758
Andy Hung69aed5f2014-02-25 17:24:40 -08003759 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3760 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003761 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003762 if (track->mainBuffer() != mSinkBuffer &&
3763 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003764 if (mEffectBufferEnabled) {
3765 mEffectBufferValid = true; // Later can set directly.
3766 }
Eric Laurent81784c32012-11-19 14:55:58 -08003767 chain = getEffectChain_l(track->sessionId());
3768 // Delegate volume control to effect in track effect chain if needed
3769 if (chain != 0) {
3770 tracksWithEffect++;
3771 } else {
3772 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3773 "session %d",
3774 name, track->sessionId());
3775 }
3776 }
3777
3778
3779 int param = AudioMixer::VOLUME;
3780 if (track->mFillingUpStatus == Track::FS_FILLED) {
3781 // no ramp for the first volume setting
3782 track->mFillingUpStatus = Track::FS_ACTIVE;
3783 if (track->mState == TrackBase::RESUMING) {
3784 track->mState = TrackBase::ACTIVE;
3785 param = AudioMixer::RAMP_VOLUME;
3786 }
3787 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003788 // FIXME should not make a decision based on mServer
3789 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003790 // If the track is stopped before the first frame was mixed,
3791 // do not apply ramp
3792 param = AudioMixer::RAMP_VOLUME;
3793 }
3794
3795 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003796 uint32_t vl, vr; // in U8.24 integer format
3797 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003798 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003799 vl = vr = 0;
3800 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003801 if (track->isPausing()) {
3802 track->setPaused();
3803 }
3804 } else {
3805
3806 // read original volumes with volume control
3807 float typeVolume = mStreamTypes[track->streamType()].volume;
3808 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003809 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003810 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003811 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3812 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003813 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003814 if (vlf > GAIN_FLOAT_UNITY) {
3815 ALOGV("Track left volume out of range: %.3g", vlf);
3816 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003817 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003818 if (vrf > GAIN_FLOAT_UNITY) {
3819 ALOGV("Track right volume out of range: %.3g", vrf);
3820 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003821 }
3822 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003823 vlf *= v;
3824 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003825 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003826 // then derive vl and vr as U8.24 versions for the effect chain
3827 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3828 vl = (uint32_t) (scaleto8_24 * vlf);
3829 vr = (uint32_t) (scaleto8_24 * vrf);
3830 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003831 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003832 // send level comes from shared memory and so may be corrupt
3833 if (sendLevel > MAX_GAIN_INT) {
3834 ALOGV("Track send level out of range: %04X", sendLevel);
3835 sendLevel = MAX_GAIN_INT;
3836 }
Andy Hung6be49402014-05-30 10:42:03 -07003837 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3838 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003839 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840
Eric Laurent81784c32012-11-19 14:55:58 -08003841 // Delegate volume control to effect in track effect chain if needed
3842 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3843 // Do not ramp volume if volume is controlled by effect
3844 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003845 // Update remaining floating point volume levels
3846 vlf = (float)vl / (1 << 24);
3847 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003848 track->mHasVolumeController = true;
3849 } else {
3850 // force no volume ramp when volume controller was just disabled or removed
3851 // from effect chain to avoid volume spike
3852 if (track->mHasVolumeController) {
3853 param = AudioMixer::VOLUME;
3854 }
3855 track->mHasVolumeController = false;
3856 }
3857
Eric Laurent81784c32012-11-19 14:55:58 -08003858 // XXX: these things DON'T need to be done each time
3859 mAudioMixer->setBufferProvider(name, track);
3860 mAudioMixer->enable(name);
3861
Andy Hung6be49402014-05-30 10:42:03 -07003862 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3863 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3864 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003865 mAudioMixer->setParameter(
3866 name,
3867 AudioMixer::TRACK,
3868 AudioMixer::FORMAT, (void *)track->format());
3869 mAudioMixer->setParameter(
3870 name,
3871 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003872 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003873 mAudioMixer->setParameter(
3874 name,
3875 AudioMixer::TRACK,
3876 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003877 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003878 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003879 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003880 if (reqSampleRate == 0) {
3881 reqSampleRate = mSampleRate;
3882 } else if (reqSampleRate > maxSampleRate) {
3883 reqSampleRate = maxSampleRate;
3884 }
Eric Laurent81784c32012-11-19 14:55:58 -08003885 mAudioMixer->setParameter(
3886 name,
3887 AudioMixer::RESAMPLE,
3888 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003889 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003890
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003891 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003892 mAudioMixer->setParameter(
3893 name,
3894 AudioMixer::TIMESTRETCH,
3895 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003896 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003897
Andy Hung69aed5f2014-02-25 17:24:40 -08003898 /*
3899 * Select the appropriate output buffer for the track.
3900 *
Andy Hung98ef9782014-03-04 14:46:50 -08003901 * Tracks with effects go into their own effects chain buffer
3902 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003903 *
3904 * Other tracks can use mMixerBuffer for higher precision
3905 * channel accumulation. If this buffer is enabled
3906 * (mMixerBufferEnabled true), then selected tracks will accumulate
3907 * into it.
3908 *
3909 */
3910 if (mMixerBufferEnabled
3911 && (track->mainBuffer() == mSinkBuffer
3912 || track->mainBuffer() == mMixerBuffer)) {
3913 mAudioMixer->setParameter(
3914 name,
3915 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003916 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003917 mAudioMixer->setParameter(
3918 name,
3919 AudioMixer::TRACK,
3920 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3921 // TODO: override track->mainBuffer()?
3922 mMixerBufferValid = true;
3923 } else {
3924 mAudioMixer->setParameter(
3925 name,
3926 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003927 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003928 mAudioMixer->setParameter(
3929 name,
3930 AudioMixer::TRACK,
3931 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3932 }
Eric Laurent81784c32012-11-19 14:55:58 -08003933 mAudioMixer->setParameter(
3934 name,
3935 AudioMixer::TRACK,
3936 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3937
3938 // reset retry count
3939 track->mRetryCount = kMaxTrackRetries;
3940
3941 // If one track is ready, set the mixer ready if:
3942 // - the mixer was not ready during previous round OR
3943 // - no other track is not ready
3944 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3945 mixerStatus != MIXER_TRACKS_ENABLED) {
3946 mixerStatus = MIXER_TRACKS_READY;
3947 }
3948 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003949 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003950 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003951 }
Eric Laurent81784c32012-11-19 14:55:58 -08003952 // clear effect chain input buffer if an active track underruns to avoid sending
3953 // previous audio buffer again to effects
3954 chain = getEffectChain_l(track->sessionId());
3955 if (chain != 0) {
3956 chain->clearInputBuffer();
3957 }
3958
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003959 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003960 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3961 track->isStopped() || track->isPaused()) {
3962 // We have consumed all the buffers of this track.
3963 // Remove it from the list of active tracks.
3964 // TODO: use actual buffer filling status instead of latency when available from
3965 // audio HAL
3966 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3967 size_t framesWritten = mBytesWritten / mFrameSize;
3968 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3969 if (track->isStopped()) {
3970 track->reset();
3971 }
3972 tracksToRemove->add(track);
3973 }
3974 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003975 // No buffers for this track. Give it a few chances to
3976 // fill a buffer, then remove it from active list.
3977 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003978 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003979 tracksToRemove->add(track);
3980 // indicate to client process that the track was disabled because of underrun;
3981 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003982 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003983 // If one track is not ready, mark the mixer also not ready if:
3984 // - the mixer was ready during previous round OR
3985 // - no other track is ready
3986 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3987 mixerStatus != MIXER_TRACKS_READY) {
3988 mixerStatus = MIXER_TRACKS_ENABLED;
3989 }
3990 }
3991 mAudioMixer->disable(name);
3992 }
3993
3994 } // local variable scope to avoid goto warning
3995track_is_ready: ;
3996
3997 }
3998
3999 // Push the new FastMixer state if necessary
4000 bool pauseAudioWatchdog = false;
4001 if (didModify) {
4002 state->mFastTracksGen++;
4003 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4004 if (kUseFastMixer == FastMixer_Dynamic &&
4005 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4006 state->mCommand = FastMixerState::COLD_IDLE;
4007 state->mColdFutexAddr = &mFastMixerFutex;
4008 state->mColdGen++;
4009 mFastMixerFutex = 0;
4010 if (kUseFastMixer == FastMixer_Dynamic) {
4011 mNormalSink = mOutputSink;
4012 }
4013 // If we go into cold idle, need to wait for acknowledgement
4014 // so that fast mixer stops doing I/O.
4015 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4016 pauseAudioWatchdog = true;
4017 }
Eric Laurent81784c32012-11-19 14:55:58 -08004018 }
4019 if (sq != NULL) {
4020 sq->end(didModify);
4021 sq->push(block);
4022 }
4023#ifdef AUDIO_WATCHDOG
4024 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4025 mAudioWatchdog->pause();
4026 }
4027#endif
4028
4029 // Now perform the deferred reset on fast tracks that have stopped
4030 while (resetMask != 0) {
4031 size_t i = __builtin_ctz(resetMask);
4032 ALOG_ASSERT(i < count);
4033 resetMask &= ~(1 << i);
4034 sp<Track> t = mActiveTracks[i].promote();
4035 if (t == 0) {
4036 continue;
4037 }
4038 Track* track = t.get();
4039 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4040 track->reset();
4041 }
4042
4043 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004044 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004045
Eric Laurent97d547d2014-09-02 14:45:53 -07004046 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4047 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004048 }
4049
4050 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004051 // as long as there are effects we should clear the effects buffer, to avoid
4052 // passing a non-clean buffer to the effect chain
4053 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004054 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004055 // sink or mix buffer must be cleared if all tracks are connected to an
4056 // effect chain as in this case the mixer will not write to the sink or mix buffer
4057 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004058 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4059 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004060 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004061 if (mMixerBufferValid) {
4062 memset(mMixerBuffer, 0, mMixerBufferSize);
4063 // TODO: In testing, mSinkBuffer below need not be cleared because
4064 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4065 // after mixing.
4066 //
4067 // To enforce this guarantee:
4068 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4069 // (mixedTracks == 0 && fastTracks > 0))
4070 // must imply MIXER_TRACKS_READY.
4071 // Later, we may clear buffers regardless, and skip much of this logic.
4072 }
Andy Hung98ef9782014-03-04 14:46:50 -08004073 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004074 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004075 }
4076
4077 // if any fast tracks, then status is ready
4078 mMixerStatusIgnoringFastTracks = mixerStatus;
4079 if (fastTracks > 0) {
4080 mixerStatus = MIXER_TRACKS_READY;
4081 }
4082 return mixerStatus;
4083}
4084
4085// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004086int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4087 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004088{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004089 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004090}
4091
4092// deleteTrackName_l() must be called with ThreadBase::mLock held
4093void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4094{
4095 ALOGV("remove track (%d) and delete from mixer", name);
4096 mAudioMixer->deleteTrackName(name);
4097}
4098
Eric Laurent10351942014-05-08 18:49:52 -07004099// checkForNewParameter_l() must be called with ThreadBase::mLock held
4100bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4101 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004102{
Eric Laurent81784c32012-11-19 14:55:58 -08004103 bool reconfig = false;
4104
Eric Laurent10351942014-05-08 18:49:52 -07004105 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004106
Eric Laurent10351942014-05-08 18:49:52 -07004107 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4108 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004109 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004110 FastMixerStateQueue *sq = mFastMixer->sq();
4111 FastMixerState *state = sq->begin();
4112 if (!(state->mCommand & FastMixerState::IDLE)) {
4113 previousCommand = state->mCommand;
4114 state->mCommand = FastMixerState::HOT_IDLE;
4115 sq->end();
4116 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4117 } else {
4118 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004119 }
Eric Laurent10351942014-05-08 18:49:52 -07004120 }
Eric Laurent81784c32012-11-19 14:55:58 -08004121
Eric Laurent10351942014-05-08 18:49:52 -07004122 AudioParameter param = AudioParameter(keyValuePair);
4123 int value;
4124 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4125 reconfig = true;
4126 }
4127 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004128 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004129 status = BAD_VALUE;
4130 } else {
4131 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004132 reconfig = true;
4133 }
Eric Laurent10351942014-05-08 18:49:52 -07004134 }
4135 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004136 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004137 status = BAD_VALUE;
4138 } else {
4139 // no need to save value, since it's constant
4140 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004141 }
Eric Laurent10351942014-05-08 18:49:52 -07004142 }
4143 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4144 // do not accept frame count changes if tracks are open as the track buffer
4145 // size depends on frame count and correct behavior would not be guaranteed
4146 // if frame count is changed after track creation
4147 if (!mTracks.isEmpty()) {
4148 status = INVALID_OPERATION;
4149 } else {
4150 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004151 }
Eric Laurent10351942014-05-08 18:49:52 -07004152 }
4153 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004154#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004155 // when changing the audio output device, call addBatteryData to notify
4156 // the change
4157 if (mOutDevice != value) {
4158 uint32_t params = 0;
4159 // check whether speaker is on
4160 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4161 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004162 }
Eric Laurent10351942014-05-08 18:49:52 -07004163
4164 audio_devices_t deviceWithoutSpeaker
4165 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4166 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004167 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004168 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4169 }
4170
4171 if (params != 0) {
4172 addBatteryData(params);
4173 }
4174 }
Eric Laurent81784c32012-11-19 14:55:58 -08004175#endif
4176
Eric Laurent10351942014-05-08 18:49:52 -07004177 // forward device change to effects that have requested to be
4178 // aware of attached audio device.
4179 if (value != AUDIO_DEVICE_NONE) {
4180 mOutDevice = value;
4181 for (size_t i = 0; i < mEffectChains.size(); i++) {
4182 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004183 }
4184 }
Eric Laurent10351942014-05-08 18:49:52 -07004185 }
Eric Laurent81784c32012-11-19 14:55:58 -08004186
Eric Laurent10351942014-05-08 18:49:52 -07004187 if (status == NO_ERROR) {
4188 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4189 keyValuePair.string());
4190 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004191 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004192 mStandby = true;
4193 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004194 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004195 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004196 }
Eric Laurent10351942014-05-08 18:49:52 -07004197 if (status == NO_ERROR && reconfig) {
4198 readOutputParameters_l();
4199 delete mAudioMixer;
4200 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4201 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004202 int name = getTrackName_l(mTracks[i]->mChannelMask,
4203 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004204 if (name < 0) {
4205 break;
4206 }
4207 mTracks[i]->mName = name;
4208 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004209 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004210 }
Eric Laurent81784c32012-11-19 14:55:58 -08004211 }
4212
4213 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004214 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004215 FastMixerStateQueue *sq = mFastMixer->sq();
4216 FastMixerState *state = sq->begin();
4217 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4218 state->mCommand = previousCommand;
4219 sq->end();
4220 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4221 }
4222
4223 return reconfig;
4224}
4225
4226
4227void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4228{
4229 const size_t SIZE = 256;
4230 char buffer[SIZE];
4231 String8 result;
4232
4233 PlaybackThread::dumpInternals(fd, args);
4234
Elliott Hughes87cebad2014-05-22 10:14:43 -07004235 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004236
4237 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004238 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004239 copy.dump(fd);
4240
4241#ifdef STATE_QUEUE_DUMP
4242 // Similar for state queue
4243 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4244 observerCopy.dump(fd);
4245 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4246 mutatorCopy.dump(fd);
4247#endif
4248
Glenn Kasten46909e72013-02-26 09:20:22 -08004249#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004250 // Write the tee output to a .wav file
4251 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004252#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004253
4254#ifdef AUDIO_WATCHDOG
4255 if (mAudioWatchdog != 0) {
4256 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4257 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4258 wdCopy.dump(fd);
4259 }
4260#endif
4261}
4262
4263uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4264{
4265 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4266}
4267
4268uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4269{
4270 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4271}
4272
4273void AudioFlinger::MixerThread::cacheParameters_l()
4274{
4275 PlaybackThread::cacheParameters_l();
4276
4277 // FIXME: Relaxed timing because of a certain device that can't meet latency
4278 // Should be reduced to 2x after the vendor fixes the driver issue
4279 // increase threshold again due to low power audio mode. The way this warning
4280 // threshold is calculated and its usefulness should be reconsidered anyway.
4281 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4282}
4283
4284// ----------------------------------------------------------------------------
4285
4286AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4287 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4288 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4289 // mLeftVolFloat, mRightVolFloat
4290{
4291}
4292
Eric Laurentbfb1b832013-01-07 09:53:42 -08004293AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4294 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4295 ThreadBase::type_t type)
4296 : PlaybackThread(audioFlinger, output, id, device, type)
4297 // mLeftVolFloat, mRightVolFloat
4298{
4299}
4300
Eric Laurent81784c32012-11-19 14:55:58 -08004301AudioFlinger::DirectOutputThread::~DirectOutputThread()
4302{
4303}
4304
Eric Laurentbfb1b832013-01-07 09:53:42 -08004305void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4306{
4307 audio_track_cblk_t* cblk = track->cblk();
4308 float left, right;
4309
4310 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4311 left = right = 0;
4312 } else {
4313 float typeVolume = mStreamTypes[track->streamType()].volume;
4314 float v = mMasterVolume * typeVolume;
4315 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004316 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4317 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4318 if (left > GAIN_FLOAT_UNITY) {
4319 left = GAIN_FLOAT_UNITY;
4320 }
4321 left *= v;
4322 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4323 if (right > GAIN_FLOAT_UNITY) {
4324 right = GAIN_FLOAT_UNITY;
4325 }
4326 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327 }
4328
4329 if (lastTrack) {
4330 if (left != mLeftVolFloat || right != mRightVolFloat) {
4331 mLeftVolFloat = left;
4332 mRightVolFloat = right;
4333
4334 // Convert volumes from float to 8.24
4335 uint32_t vl = (uint32_t)(left * (1 << 24));
4336 uint32_t vr = (uint32_t)(right * (1 << 24));
4337
4338 // Delegate volume control to effect in track effect chain if needed
4339 // only one effect chain can be present on DirectOutputThread, so if
4340 // there is one, the track is connected to it
4341 if (!mEffectChains.isEmpty()) {
4342 mEffectChains[0]->setVolume_l(&vl, &vr);
4343 left = (float)vl / (1 << 24);
4344 right = (float)vr / (1 << 24);
4345 }
4346 if (mOutput->stream->set_volume) {
4347 mOutput->stream->set_volume(mOutput->stream, left, right);
4348 }
4349 }
4350 }
4351}
4352
4353
Eric Laurent81784c32012-11-19 14:55:58 -08004354AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4355 Vector< sp<Track> > *tracksToRemove
4356)
4357{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004358 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004359 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004360 bool doHwPause = false;
4361 bool doHwResume = false;
4362 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004363
4364 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004365 for (size_t i = 0; i < count; i++) {
4366 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004367 // The track died recently
4368 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004369 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004370 }
4371
4372 Track* const track = t.get();
4373 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004374 // Only consider last track started for volume and mixer state control.
4375 // In theory an older track could underrun and restart after the new one starts
4376 // but as we only care about the transition phase between two tracks on a
4377 // direct output, it is not a problem to ignore the underrun case.
4378 sp<Track> l = mLatestActiveTrack.promote();
4379 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004380
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004381 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004382 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004383 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004384 doHwPause = true;
4385 mHwPaused = true;
4386 }
4387 tracksToRemove->add(track);
4388 } else if (track->isFlushPending()) {
4389 track->flushAck();
4390 if (last) {
4391 flushPending = true;
4392 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004393 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004394 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004395 if (last && mHwPaused) {
4396 doHwResume = true;
4397 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004398 }
4399 }
4400
Eric Laurent81784c32012-11-19 14:55:58 -08004401 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004402 // for all its buffers to be filled before processing it.
4403 // Allow draining the buffer in case the client
4404 // app does not call stop() and relies on underrun to stop:
4405 // hence the test on (track->mRetryCount > 1).
4406 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004407 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004408 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4409 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004410 minFrames = mNormalFrameCount;
4411 } else {
4412 minFrames = 1;
4413 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004414
Eric Laurentab5cdba2014-06-09 17:22:27 -07004415 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4416 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004417 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004418 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004419
4420 if (track->mFillingUpStatus == Track::FS_FILLED) {
4421 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004422 // make sure processVolume_l() will apply new volume even if 0
4423 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004424 if (!mHwSupportsPause) {
4425 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004426 }
4427 }
4428
4429 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004430 processVolume_l(track, last);
4431 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004432 // reset retry count
4433 track->mRetryCount = kMaxTrackRetriesDirect;
4434 mActiveTrack = t;
4435 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004436 if (usesHwAvSync() && mHwPaused) {
4437 doHwResume = true;
4438 mHwPaused = false;
4439 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004440 }
Eric Laurent81784c32012-11-19 14:55:58 -08004441 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004442 // clear effect chain input buffer if the last active track started underruns
4443 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004444 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004445 mEffectChains[0]->clearInputBuffer();
4446 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004447 if (track->isStopping_1()) {
4448 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004449 if (last && mHwPaused) {
4450 doHwResume = true;
4451 mHwPaused = false;
4452 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004453 }
4454 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4455 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004456 // We have consumed all the buffers of this track.
4457 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004458 size_t audioHALFrames;
4459 if (audio_is_linear_pcm(mFormat)) {
4460 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4461 } else {
4462 audioHALFrames = 0;
4463 }
4464
Eric Laurent81784c32012-11-19 14:55:58 -08004465 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004466 if (mStandby || !last ||
4467 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004468 if (track->isStopping_2()) {
4469 track->mState = TrackBase::STOPPED;
4470 }
Eric Laurent81784c32012-11-19 14:55:58 -08004471 if (track->isStopped()) {
4472 track->reset();
4473 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004474 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004475 }
4476 } else {
4477 // No buffers for this track. Give it a few chances to
4478 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004479 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004480 if (--(track->mRetryCount) <= 0) {
4481 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004482 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004483 // indicate to client process that the track was disabled because of underrun;
4484 // it will then automatically call start() when data is available
4485 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004486 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004487 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004488 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4489 doHwPause = true;
4490 mHwPaused = true;
4491 }
Eric Laurent81784c32012-11-19 14:55:58 -08004492 }
4493 }
4494 }
4495 }
4496
Eric Laurentd1f69b02014-12-15 14:33:13 -08004497 // if an active track did not command a flush, check for pending flush on stopped tracks
4498 if (!flushPending) {
4499 for (size_t i = 0; i < mTracks.size(); i++) {
4500 if (mTracks[i]->isFlushPending()) {
4501 mTracks[i]->flushAck();
4502 flushPending = true;
4503 }
4504 }
4505 }
4506
4507 // make sure the pause/flush/resume sequence is executed in the right order.
4508 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4509 // before flush and then resume HW. This can happen in case of pause/flush/resume
4510 // if resume is received before pause is executed.
4511 if (mHwSupportsPause && !mStandby &&
4512 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4513 mOutput->stream->pause(mOutput->stream);
4514 }
4515 if (flushPending) {
4516 flushHw_l();
4517 }
4518 if (mHwSupportsPause && !mStandby && doHwResume) {
4519 mOutput->stream->resume(mOutput->stream);
4520 }
Eric Laurent81784c32012-11-19 14:55:58 -08004521 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004523
4524 return mixerStatus;
4525}
4526
4527void AudioFlinger::DirectOutputThread::threadLoop_mix()
4528{
Eric Laurent81784c32012-11-19 14:55:58 -08004529 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004530 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004531 // output audio to hardware
4532 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004533 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004534 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004535 status_t status = mActiveTrack->getNextBuffer(&buffer);
4536 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004537 memset(curBuf, 0, frameCount * mFrameSize);
4538 break;
4539 }
4540 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4541 frameCount -= buffer.frameCount;
4542 curBuf += buffer.frameCount * mFrameSize;
4543 mActiveTrack->releaseBuffer(&buffer);
4544 }
Andy Hung2098f272014-02-27 14:00:06 -08004545 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004546 sleepTime = 0;
4547 standbyTime = systemTime() + standbyDelay;
4548 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004549}
4550
4551void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4552{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004553 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004554 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004555 sleepTime = idleSleepTime;
4556 return;
4557 }
Eric Laurent81784c32012-11-19 14:55:58 -08004558 if (sleepTime == 0) {
4559 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4560 sleepTime = activeSleepTime;
4561 } else {
4562 sleepTime = idleSleepTime;
4563 }
4564 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004565 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004566 sleepTime = 0;
4567 }
4568}
4569
Eric Laurentd1f69b02014-12-15 14:33:13 -08004570void AudioFlinger::DirectOutputThread::threadLoop_exit()
4571{
4572 {
4573 Mutex::Autolock _l(mLock);
4574 bool flushPending = false;
4575 for (size_t i = 0; i < mTracks.size(); i++) {
4576 if (mTracks[i]->isFlushPending()) {
4577 mTracks[i]->flushAck();
4578 flushPending = true;
4579 }
4580 }
4581 if (flushPending) {
4582 flushHw_l();
4583 }
4584 }
4585 PlaybackThread::threadLoop_exit();
4586}
4587
4588// must be called with thread mutex locked
4589bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4590{
4591 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004592 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004593
4594 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4595 // after a timeout and we will enter standby then.
4596 if (mTracks.size() > 0) {
4597 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004598 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4599 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004600 }
4601
Eric Laurentb369caf2015-03-30 20:51:47 -07004602 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004603}
4604
Eric Laurent81784c32012-11-19 14:55:58 -08004605// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004606int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004607 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004608{
4609 return 0;
4610}
4611
4612// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004613void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004614{
4615}
4616
Eric Laurent10351942014-05-08 18:49:52 -07004617// checkForNewParameter_l() must be called with ThreadBase::mLock held
4618bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4619 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004620{
4621 bool reconfig = false;
4622
Eric Laurent10351942014-05-08 18:49:52 -07004623 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004624
Eric Laurent10351942014-05-08 18:49:52 -07004625 AudioParameter param = AudioParameter(keyValuePair);
4626 int value;
4627 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4628 // forward device change to effects that have requested to be
4629 // aware of attached audio device.
4630 if (value != AUDIO_DEVICE_NONE) {
4631 mOutDevice = value;
4632 for (size_t i = 0; i < mEffectChains.size(); i++) {
4633 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004634 }
4635 }
Eric Laurent81784c32012-11-19 14:55:58 -08004636 }
Eric Laurent10351942014-05-08 18:49:52 -07004637 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4638 // do not accept frame count changes if tracks are open as the track buffer
4639 // size depends on frame count and correct behavior would not be garantied
4640 // if frame count is changed after track creation
4641 if (!mTracks.isEmpty()) {
4642 status = INVALID_OPERATION;
4643 } else {
4644 reconfig = true;
4645 }
4646 }
4647 if (status == NO_ERROR) {
4648 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4649 keyValuePair.string());
4650 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004651 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004652 mStandby = true;
4653 mBytesWritten = 0;
4654 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4655 keyValuePair.string());
4656 }
4657 if (status == NO_ERROR && reconfig) {
4658 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004659 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004660 }
4661 }
4662
Eric Laurent81784c32012-11-19 14:55:58 -08004663 return reconfig;
4664}
4665
4666uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4667{
4668 uint32_t time;
4669 if (audio_is_linear_pcm(mFormat)) {
4670 time = PlaybackThread::activeSleepTimeUs();
4671 } else {
4672 time = 10000;
4673 }
4674 return time;
4675}
4676
4677uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4678{
4679 uint32_t time;
4680 if (audio_is_linear_pcm(mFormat)) {
4681 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4682 } else {
4683 time = 10000;
4684 }
4685 return time;
4686}
4687
4688uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4689{
4690 uint32_t time;
4691 if (audio_is_linear_pcm(mFormat)) {
4692 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4693 } else {
4694 time = 10000;
4695 }
4696 return time;
4697}
4698
4699void AudioFlinger::DirectOutputThread::cacheParameters_l()
4700{
4701 PlaybackThread::cacheParameters_l();
4702
4703 // use shorter standby delay as on normal output to release
4704 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004705 // no delay on outputs with HW A/V sync
4706 if (usesHwAvSync()) {
4707 standbyDelay = 0;
4708 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004709 standbyDelay = microseconds(activeSleepTime*2);
4710 } else {
4711 standbyDelay = kOffloadStandbyDelayNs;
4712 }
Eric Laurent81784c32012-11-19 14:55:58 -08004713}
4714
Eric Laurente659ef42014-09-29 13:06:46 -07004715void AudioFlinger::DirectOutputThread::flushHw_l()
4716{
Phil Burk062e67a2015-02-11 13:40:50 -08004717 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004718 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004719}
4720
Eric Laurent81784c32012-11-19 14:55:58 -08004721// ----------------------------------------------------------------------------
4722
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004724 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004725 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004726 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004727 mWriteAckSequence(0),
4728 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004729{
4730}
4731
4732AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4733{
4734}
4735
4736void AudioFlinger::AsyncCallbackThread::onFirstRef()
4737{
4738 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4739}
4740
4741bool AudioFlinger::AsyncCallbackThread::threadLoop()
4742{
4743 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004744 uint32_t writeAckSequence;
4745 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004746
4747 {
4748 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004749 while (!((mWriteAckSequence & 1) ||
4750 (mDrainSequence & 1) ||
4751 exitPending())) {
4752 mWaitWorkCV.wait(mLock);
4753 }
4754
Eric Laurentbfb1b832013-01-07 09:53:42 -08004755 if (exitPending()) {
4756 break;
4757 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004758 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4759 mWriteAckSequence, mDrainSequence);
4760 writeAckSequence = mWriteAckSequence;
4761 mWriteAckSequence &= ~1;
4762 drainSequence = mDrainSequence;
4763 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004764 }
4765 {
Eric Laurent4de95592013-09-26 15:28:21 -07004766 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4767 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004768 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004769 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004770 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004771 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004772 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004773 }
4774 }
4775 }
4776 }
4777 return false;
4778}
4779
4780void AudioFlinger::AsyncCallbackThread::exit()
4781{
4782 ALOGV("AsyncCallbackThread::exit");
4783 Mutex::Autolock _l(mLock);
4784 requestExit();
4785 mWaitWorkCV.broadcast();
4786}
4787
Eric Laurent3b4529e2013-09-05 18:09:19 -07004788void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004789{
4790 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004791 // bit 0 is cleared
4792 mWriteAckSequence = sequence << 1;
4793}
4794
4795void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4796{
4797 Mutex::Autolock _l(mLock);
4798 // ignore unexpected callbacks
4799 if (mWriteAckSequence & 2) {
4800 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004801 mWaitWorkCV.signal();
4802 }
4803}
4804
Eric Laurent3b4529e2013-09-05 18:09:19 -07004805void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806{
4807 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004808 // bit 0 is cleared
4809 mDrainSequence = sequence << 1;
4810}
4811
4812void AudioFlinger::AsyncCallbackThread::resetDraining()
4813{
4814 Mutex::Autolock _l(mLock);
4815 // ignore unexpected callbacks
4816 if (mDrainSequence & 2) {
4817 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004818 mWaitWorkCV.signal();
4819 }
4820}
4821
4822
4823// ----------------------------------------------------------------------------
4824AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4825 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4826 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004827 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004828{
Eric Laurentfd477972013-10-25 18:10:40 -07004829 //FIXME: mStandby should be set to true by ThreadBase constructor
4830 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831}
4832
Eric Laurentbfb1b832013-01-07 09:53:42 -08004833void AudioFlinger::OffloadThread::threadLoop_exit()
4834{
4835 if (mFlushPending || mHwPaused) {
4836 // If a flush is pending or track was paused, just discard buffered data
4837 flushHw_l();
4838 } else {
4839 mMixerStatus = MIXER_DRAIN_ALL;
4840 threadLoop_drain();
4841 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004842 if (mUseAsyncWrite) {
4843 ALOG_ASSERT(mCallbackThread != 0);
4844 mCallbackThread->exit();
4845 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004846 PlaybackThread::threadLoop_exit();
4847}
4848
4849AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4850 Vector< sp<Track> > *tracksToRemove
4851)
4852{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004853 size_t count = mActiveTracks.size();
4854
4855 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004856 bool doHwPause = false;
4857 bool doHwResume = false;
4858
Eric Laurentede6c3b2013-09-19 14:37:46 -07004859 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4860
Eric Laurentbfb1b832013-01-07 09:53:42 -08004861 // find out which tracks need to be processed
4862 for (size_t i = 0; i < count; i++) {
4863 sp<Track> t = mActiveTracks[i].promote();
4864 // The track died recently
4865 if (t == 0) {
4866 continue;
4867 }
4868 Track* const track = t.get();
4869 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004870 // Only consider last track started for volume and mixer state control.
4871 // In theory an older track could underrun and restart after the new one starts
4872 // but as we only care about the transition phase between two tracks on a
4873 // direct output, it is not a problem to ignore the underrun case.
4874 sp<Track> l = mLatestActiveTrack.promote();
4875 bool last = l.get() == track;
4876
Haynes Mathew George7844f672014-01-15 12:32:55 -08004877 if (track->isInvalid()) {
4878 ALOGW("An invalidated track shouldn't be in active list");
4879 tracksToRemove->add(track);
4880 continue;
4881 }
4882
4883 if (track->mState == TrackBase::IDLE) {
4884 ALOGW("An idle track shouldn't be in active list");
4885 continue;
4886 }
4887
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888 if (track->isPausing()) {
4889 track->setPaused();
4890 if (last) {
4891 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004892 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004893 mHwPaused = true;
4894 }
4895 // If we were part way through writing the mixbuffer to
4896 // the HAL we must save this until we resume
4897 // BUG - this will be wrong if a different track is made active,
4898 // in that case we want to discard the pending data in the
4899 // mixbuffer and tell the client to present it again when the
4900 // track is resumed
4901 mPausedWriteLength = mCurrentWriteLength;
4902 mPausedBytesRemaining = mBytesRemaining;
4903 mBytesRemaining = 0; // stop writing
4904 }
4905 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004906 } else if (track->isFlushPending()) {
4907 track->flushAck();
4908 if (last) {
4909 mFlushPending = true;
4910 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004911 } else if (track->isResumePending()){
4912 track->resumeAck();
4913 if (last) {
4914 if (mPausedBytesRemaining) {
4915 // Need to continue write that was interrupted
4916 mCurrentWriteLength = mPausedWriteLength;
4917 mBytesRemaining = mPausedBytesRemaining;
4918 mPausedBytesRemaining = 0;
4919 }
4920 if (mHwPaused) {
4921 doHwResume = true;
4922 mHwPaused = false;
4923 // threadLoop_mix() will handle the case that we need to
4924 // resume an interrupted write
4925 }
4926 // enable write to audio HAL
4927 sleepTime = 0;
4928
4929 // Do not handle new data in this iteration even if track->framesReady()
4930 mixerStatus = MIXER_TRACKS_ENABLED;
4931 }
4932 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004933 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004934 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935 if (track->mFillingUpStatus == Track::FS_FILLED) {
4936 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004937 // make sure processVolume_l() will apply new volume even if 0
4938 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004939 }
4940
4941 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004942 sp<Track> previousTrack = mPreviousTrack.promote();
4943 if (previousTrack != 0) {
4944 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004945 // Flush any data still being written from last track
4946 mBytesRemaining = 0;
4947 if (mPausedBytesRemaining) {
4948 // Last track was paused so we also need to flush saved
4949 // mixbuffer state and invalidate track so that it will
4950 // re-submit that unwritten data when it is next resumed
4951 mPausedBytesRemaining = 0;
4952 // Invalidate is a bit drastic - would be more efficient
4953 // to have a flag to tell client that some of the
4954 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004955 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004956 }
4957 // flush data already sent to the DSP if changing audio session as audio
4958 // comes from a different source. Also invalidate previous track to force a
4959 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004960 if (previousTrack->sessionId() != track->sessionId()) {
4961 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004962 }
4963 }
4964 }
4965 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004966 // reset retry count
4967 track->mRetryCount = kMaxTrackRetriesOffload;
4968 mActiveTrack = t;
4969 mixerStatus = MIXER_TRACKS_READY;
4970 }
4971 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004972 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004973 if (track->isStopping_1()) {
4974 // Hardware buffer can hold a large amount of audio so we must
4975 // wait for all current track's data to drain before we say
4976 // that the track is stopped.
4977 if (mBytesRemaining == 0) {
4978 // Only start draining when all data in mixbuffer
4979 // has been written
4980 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4981 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004982 // do not drain if no data was ever sent to HAL (mStandby == true)
4983 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004984 // do not modify drain sequence if we are already draining. This happens
4985 // when resuming from pause after drain.
4986 if ((mDrainSequence & 1) == 0) {
4987 sleepTime = 0;
4988 standbyTime = systemTime() + standbyDelay;
4989 mixerStatus = MIXER_DRAIN_TRACK;
4990 mDrainSequence += 2;
4991 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004992 if (mHwPaused) {
4993 // It is possible to move from PAUSED to STOPPING_1 without
4994 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004995 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004996 mHwPaused = false;
4997 }
4998 }
4999 }
5000 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005001 // Drain has completed or we are in standby, signal presentation complete
5002 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005003 track->mState = TrackBase::STOPPED;
5004 size_t audioHALFrames =
5005 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5006 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005007 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005008 track->presentationComplete(framesWritten, audioHALFrames);
5009 track->reset();
5010 tracksToRemove->add(track);
5011 }
5012 } else {
5013 // No buffers for this track. Give it a few chances to
5014 // fill a buffer, then remove it from active list.
5015 if (--(track->mRetryCount) <= 0) {
5016 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5017 track->name());
5018 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005019 // indicate to client process that the track was disabled because of underrun;
5020 // it will then automatically call start() when data is available
5021 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005022 } else if (last){
5023 mixerStatus = MIXER_TRACKS_ENABLED;
5024 }
5025 }
5026 }
5027 // compute volume for this track
5028 processVolume_l(track, last);
5029 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005030
Eric Laurentea0fade2013-10-04 16:23:48 -07005031 // make sure the pause/flush/resume sequence is executed in the right order.
5032 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5033 // before flush and then resume HW. This can happen in case of pause/flush/resume
5034 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005035 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005036 mOutput->stream->pause(mOutput->stream);
5037 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005038 if (mFlushPending) {
5039 flushHw_l();
5040 mFlushPending = false;
5041 }
Eric Laurentfd477972013-10-25 18:10:40 -07005042 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005043 mOutput->stream->resume(mOutput->stream);
5044 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005045
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046 // remove all the tracks that need to be...
5047 removeTracks_l(*tracksToRemove);
5048
5049 return mixerStatus;
5050}
5051
Eric Laurentbfb1b832013-01-07 09:53:42 -08005052// must be called with thread mutex locked
5053bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5054{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005055 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5056 mWriteAckSequence, mDrainSequence);
5057 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005058 return true;
5059 }
5060 return false;
5061}
5062
Eric Laurentbfb1b832013-01-07 09:53:42 -08005063bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5064{
5065 Mutex::Autolock _l(mLock);
5066 return waitingAsyncCallback_l();
5067}
5068
5069void AudioFlinger::OffloadThread::flushHw_l()
5070{
Eric Laurente659ef42014-09-29 13:06:46 -07005071 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005072 // Flush anything still waiting in the mixbuffer
5073 mCurrentWriteLength = 0;
5074 mBytesRemaining = 0;
5075 mPausedWriteLength = 0;
5076 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005077
Eric Laurentbfb1b832013-01-07 09:53:42 -08005078 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005079 // discard any pending drain or write ack by incrementing sequence
5080 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5081 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005082 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005083 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5084 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005085 }
5086}
5087
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005088void AudioFlinger::OffloadThread::onAddNewTrack_l()
5089{
5090 sp<Track> previousTrack = mPreviousTrack.promote();
5091 sp<Track> latestTrack = mLatestActiveTrack.promote();
5092
5093 if (previousTrack != 0 && latestTrack != 0 &&
5094 (previousTrack->sessionId() != latestTrack->sessionId())) {
5095 mFlushPending = true;
5096 }
5097 PlaybackThread::onAddNewTrack_l();
5098}
5099
Eric Laurentbfb1b832013-01-07 09:53:42 -08005100// ----------------------------------------------------------------------------
5101
Eric Laurent81784c32012-11-19 14:55:58 -08005102AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5103 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
5104 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5105 DUPLICATING),
5106 mWaitTimeMs(UINT_MAX)
5107{
5108 addOutputTrack(mainThread);
5109}
5110
5111AudioFlinger::DuplicatingThread::~DuplicatingThread()
5112{
5113 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5114 mOutputTracks[i]->destroy();
5115 }
5116}
5117
5118void AudioFlinger::DuplicatingThread::threadLoop_mix()
5119{
5120 // mix buffers...
5121 if (outputsReady(outputTracks)) {
5122 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5123 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005124 if (mMixerBufferValid) {
5125 memset(mMixerBuffer, 0, mMixerBufferSize);
5126 } else {
5127 memset(mSinkBuffer, 0, mSinkBufferSize);
5128 }
Eric Laurent81784c32012-11-19 14:55:58 -08005129 }
5130 sleepTime = 0;
5131 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005132 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005133 standbyTime = systemTime() + standbyDelay;
5134}
5135
5136void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5137{
5138 if (sleepTime == 0) {
5139 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5140 sleepTime = activeSleepTime;
5141 } else {
5142 sleepTime = idleSleepTime;
5143 }
5144 } else if (mBytesWritten != 0) {
5145 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5146 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005147 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005148 } else {
5149 // flush remaining overflow buffers in output tracks
5150 writeFrames = 0;
5151 }
5152 sleepTime = 0;
5153 }
5154}
5155
Eric Laurentbfb1b832013-01-07 09:53:42 -08005156ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005157{
5158 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005159 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005160 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005161 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005162 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005163}
5164
5165void AudioFlinger::DuplicatingThread::threadLoop_standby()
5166{
5167 // DuplicatingThread implements standby by stopping all tracks
5168 for (size_t i = 0; i < outputTracks.size(); i++) {
5169 outputTracks[i]->stop();
5170 }
5171}
5172
5173void AudioFlinger::DuplicatingThread::saveOutputTracks()
5174{
5175 outputTracks = mOutputTracks;
5176}
5177
5178void AudioFlinger::DuplicatingThread::clearOutputTracks()
5179{
5180 outputTracks.clear();
5181}
5182
5183void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5184{
5185 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005186 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5187 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5188 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5189 const size_t frameCount =
5190 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5191 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5192 // from different OutputTracks and their associated MixerThreads (e.g. one may
5193 // nearly empty and the other may be dropping data).
5194
5195 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005196 this,
5197 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005198 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005199 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005200 frameCount,
5201 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005202 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005203 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005204 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005205 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005206 updateWaitTime_l();
5207 }
5208}
5209
5210void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5211{
5212 Mutex::Autolock _l(mLock);
5213 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5214 if (mOutputTracks[i]->thread() == thread) {
5215 mOutputTracks[i]->destroy();
5216 mOutputTracks.removeAt(i);
5217 updateWaitTime_l();
5218 return;
5219 }
5220 }
5221 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5222}
5223
5224// caller must hold mLock
5225void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5226{
5227 mWaitTimeMs = UINT_MAX;
5228 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5229 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5230 if (strong != 0) {
5231 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5232 if (waitTimeMs < mWaitTimeMs) {
5233 mWaitTimeMs = waitTimeMs;
5234 }
5235 }
5236 }
5237}
5238
5239
5240bool AudioFlinger::DuplicatingThread::outputsReady(
5241 const SortedVector< sp<OutputTrack> > &outputTracks)
5242{
5243 for (size_t i = 0; i < outputTracks.size(); i++) {
5244 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5245 if (thread == 0) {
5246 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5247 outputTracks[i].get());
5248 return false;
5249 }
5250 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5251 // see note at standby() declaration
5252 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5253 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5254 thread.get());
5255 return false;
5256 }
5257 }
5258 return true;
5259}
5260
5261uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5262{
5263 return (mWaitTimeMs * 1000) / 2;
5264}
5265
5266void AudioFlinger::DuplicatingThread::cacheParameters_l()
5267{
5268 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5269 updateWaitTime_l();
5270
5271 MixerThread::cacheParameters_l();
5272}
5273
5274// ----------------------------------------------------------------------------
5275// Record
5276// ----------------------------------------------------------------------------
5277
5278AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5279 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005280 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005281 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005282 audio_devices_t inDevice
5283#ifdef TEE_SINK
5284 , const sp<NBAIO_Sink>& teeSink
5285#endif
5286 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005287 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005288 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005289 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005290 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005291#ifdef TEE_SINK
5292 , mTeeSink(teeSink)
5293#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005294 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5295 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005296 // mFastCapture below
5297 , mFastCaptureFutex(0)
5298 // mInputSource
5299 // mPipeSink
5300 // mPipeSource
5301 , mPipeFramesP2(0)
5302 // mPipeMemory
5303 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005304 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005305{
Glenn Kastend7dca052015-03-05 16:05:54 -08005306 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5307 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005308
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005309 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005310
5311 // create an NBAIO source for the HAL input stream, and negotiate
5312 mInputSource = new AudioStreamInSource(input->stream);
5313 size_t numCounterOffers = 0;
5314 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5315 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5316 ALOG_ASSERT(index == 0);
5317
5318 // initialize fast capture depending on configuration
5319 bool initFastCapture;
5320 switch (kUseFastCapture) {
5321 case FastCapture_Never:
5322 initFastCapture = false;
5323 break;
5324 case FastCapture_Always:
5325 initFastCapture = true;
5326 break;
5327 case FastCapture_Static:
5328 uint32_t primaryOutputSampleRate;
5329 {
5330 AutoMutex _l(audioFlinger->mHardwareLock);
5331 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5332 }
5333 initFastCapture =
5334 // either capture sample rate is same as (a reasonable) primary output sample rate
5335 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5336 (mSampleRate == primaryOutputSampleRate)) ||
5337 // or primary output sample rate is unknown, and capture sample rate is reasonable
5338 ((primaryOutputSampleRate == 0) &&
5339 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005340 // and the buffer size is < 12 ms
5341 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005342 break;
5343 // case FastCapture_Dynamic:
5344 }
5345
5346 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005347 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005348 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005349 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005350 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5351 void *pipeBuffer;
5352 const sp<MemoryDealer> roHeap(readOnlyHeap());
5353 sp<IMemory> pipeMemory;
5354 if ((roHeap == 0) ||
5355 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5356 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5357 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5358 goto failed;
5359 }
5360 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5361 memset(pipeBuffer, 0, pipeSize);
5362 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5363 const NBAIO_Format offers[1] = {format};
5364 size_t numCounterOffers = 0;
5365 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5366 ALOG_ASSERT(index == 0);
5367 mPipeSink = pipe;
5368 PipeReader *pipeReader = new PipeReader(*pipe);
5369 numCounterOffers = 0;
5370 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5371 ALOG_ASSERT(index == 0);
5372 mPipeSource = pipeReader;
5373 mPipeFramesP2 = pipeFramesP2;
5374 mPipeMemory = pipeMemory;
5375
5376 // create fast capture
5377 mFastCapture = new FastCapture();
5378 FastCaptureStateQueue *sq = mFastCapture->sq();
5379#ifdef STATE_QUEUE_DUMP
5380 // FIXME
5381#endif
5382 FastCaptureState *state = sq->begin();
5383 state->mCblk = NULL;
5384 state->mInputSource = mInputSource.get();
5385 state->mInputSourceGen++;
5386 state->mPipeSink = pipe;
5387 state->mPipeSinkGen++;
5388 state->mFrameCount = mFrameCount;
5389 state->mCommand = FastCaptureState::COLD_IDLE;
5390 // already done in constructor initialization list
5391 //mFastCaptureFutex = 0;
5392 state->mColdFutexAddr = &mFastCaptureFutex;
5393 state->mColdGen++;
5394 state->mDumpState = &mFastCaptureDumpState;
5395#ifdef TEE_SINK
5396 // FIXME
5397#endif
5398 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5399 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5400 sq->end();
5401 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5402
5403 // start the fast capture
5404 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5405 pid_t tid = mFastCapture->getTid();
5406 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5407 if (err != 0) {
5408 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5409 kPriorityFastCapture, getpid_cached, tid, err);
5410 }
5411
5412#ifdef AUDIO_WATCHDOG
5413 // FIXME
5414#endif
5415
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005416 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005417 }
5418failed: ;
5419
5420 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005421}
5422
Eric Laurent81784c32012-11-19 14:55:58 -08005423AudioFlinger::RecordThread::~RecordThread()
5424{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005425 if (mFastCapture != 0) {
5426 FastCaptureStateQueue *sq = mFastCapture->sq();
5427 FastCaptureState *state = sq->begin();
5428 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5429 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5430 if (old == -1) {
5431 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5432 }
5433 }
5434 state->mCommand = FastCaptureState::EXIT;
5435 sq->end();
5436 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5437 mFastCapture->join();
5438 mFastCapture.clear();
5439 }
5440 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005441 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005442 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005443}
5444
5445void AudioFlinger::RecordThread::onFirstRef()
5446{
Glenn Kastend7dca052015-03-05 16:05:54 -08005447 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005448}
5449
Eric Laurent81784c32012-11-19 14:55:58 -08005450bool AudioFlinger::RecordThread::threadLoop()
5451{
Eric Laurent81784c32012-11-19 14:55:58 -08005452 nsecs_t lastWarning = 0;
5453
5454 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005455
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005456reacquire_wakelock:
5457 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005458 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005459 {
5460 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005461 size_t size = mActiveTracks.size();
5462 activeTracksGen = mActiveTracksGen;
5463 if (size > 0) {
5464 // FIXME an arbitrary choice
5465 activeTrack = mActiveTracks[0];
5466 acquireWakeLock_l(activeTrack->uid());
5467 if (size > 1) {
5468 SortedVector<int> tmp;
5469 for (size_t i = 0; i < size; i++) {
5470 tmp.add(mActiveTracks[i]->uid());
5471 }
5472 updateWakeLockUids_l(tmp);
5473 }
5474 } else {
5475 acquireWakeLock_l(-1);
5476 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005477 }
5478
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005479 // used to request a deferred sleep, to be executed later while mutex is unlocked
5480 uint32_t sleepUs = 0;
5481
5482 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005483 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005484 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005485
Glenn Kasten5edadd42013-08-14 16:30:49 -07005486 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005487 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005488 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005489 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005490 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005491 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005492 }
5493
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005494 // activeTracks accumulates a copy of a subset of mActiveTracks
5495 Vector< sp<RecordTrack> > activeTracks;
5496
Glenn Kasten735f45f2014-08-18 15:51:59 -07005497 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005498 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005499
Glenn Kasten735f45f2014-08-18 15:51:59 -07005500 // reference to a fast track which is about to be removed
5501 sp<RecordTrack> fastTrackToRemove;
5502
Eric Laurent81784c32012-11-19 14:55:58 -08005503 { // scope for mLock
5504 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005505
Eric Laurent021cf962014-05-13 10:18:14 -07005506 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005507
Eric Laurent000a4192014-01-29 15:17:32 -08005508 // check exitPending here because checkForNewParameters_l() and
5509 // checkForNewParameters_l() can temporarily release mLock
5510 if (exitPending()) {
5511 break;
5512 }
5513
Glenn Kasten2b806402013-11-20 16:37:38 -08005514 // if no active track(s), then standby and release wakelock
5515 size_t size = mActiveTracks.size();
5516 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005517 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005518 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005519 releaseWakeLock_l();
5520 ALOGV("RecordThread: loop stopping");
5521 // go to sleep
5522 mWaitWorkCV.wait(mLock);
5523 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005524 goto reacquire_wakelock;
5525 }
5526
Glenn Kasten2b806402013-11-20 16:37:38 -08005527 if (mActiveTracksGen != activeTracksGen) {
5528 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005529 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005530 for (size_t i = 0; i < size; i++) {
5531 tmp.add(mActiveTracks[i]->uid());
5532 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005533 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005534 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005535
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005536 bool doBroadcast = false;
5537 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005538
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005539 activeTrack = mActiveTracks[i];
5540 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005541 if (activeTrack->isFastTrack()) {
5542 ALOG_ASSERT(fastTrackToRemove == 0);
5543 fastTrackToRemove = activeTrack;
5544 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005545 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005546 mActiveTracks.remove(activeTrack);
5547 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005548 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005549 continue;
5550 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005551
5552 TrackBase::track_state activeTrackState = activeTrack->mState;
5553 switch (activeTrackState) {
5554
5555 case TrackBase::PAUSING:
5556 mActiveTracks.remove(activeTrack);
5557 mActiveTracksGen++;
5558 doBroadcast = true;
5559 size--;
5560 continue;
5561
5562 case TrackBase::STARTING_1:
5563 sleepUs = 10000;
5564 i++;
5565 continue;
5566
5567 case TrackBase::STARTING_2:
5568 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005569 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005570 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005571 break;
5572
5573 case TrackBase::ACTIVE:
5574 break;
5575
5576 case TrackBase::IDLE:
5577 i++;
5578 continue;
5579
5580 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005581 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005582 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005583
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005584 activeTracks.add(activeTrack);
5585 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005586
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005587 if (activeTrack->isFastTrack()) {
5588 ALOG_ASSERT(!mFastTrackAvail);
5589 ALOG_ASSERT(fastTrack == 0);
5590 fastTrack = activeTrack;
5591 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005592 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005593 if (doBroadcast) {
5594 mStartStopCond.broadcast();
5595 }
5596
5597 // sleep if there are no active tracks to process
5598 if (activeTracks.size() == 0) {
5599 if (sleepUs == 0) {
5600 sleepUs = kRecordThreadSleepUs;
5601 }
5602 continue;
5603 }
5604 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005605
Eric Laurent81784c32012-11-19 14:55:58 -08005606 lockEffectChains_l(effectChains);
5607 }
5608
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005609 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005610
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005611 size_t size = effectChains.size();
5612 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005613 // thread mutex is not locked, but effect chain is locked
5614 effectChains[i]->process_l();
5615 }
5616
Glenn Kasten735f45f2014-08-18 15:51:59 -07005617 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005618 if (mFastCapture != 0) {
5619 FastCaptureStateQueue *sq = mFastCapture->sq();
5620 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005621 bool didModify = false;
5622 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005623 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5624 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5625 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5626 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5627 if (old == -1) {
5628 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5629 }
5630 }
5631 state->mCommand = FastCaptureState::READ_WRITE;
5632#if 0 // FIXME
5633 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005634 FastThreadDumpState::kSamplingNforLowRamDevice :
5635 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005636#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005637 didModify = true;
5638 }
5639 audio_track_cblk_t *cblkOld = state->mCblk;
5640 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5641 if (cblkNew != cblkOld) {
5642 state->mCblk = cblkNew;
5643 // block until acked if removing a fast track
5644 if (cblkOld != NULL) {
5645 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5646 }
5647 didModify = true;
5648 }
5649 sq->end(didModify);
5650 if (didModify) {
5651 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005652#if 0
5653 if (kUseFastCapture == FastCapture_Dynamic) {
5654 mNormalSource = mPipeSource;
5655 }
5656#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005657 }
5658 }
5659
Glenn Kasten735f45f2014-08-18 15:51:59 -07005660 // now run the fast track destructor with thread mutex unlocked
5661 fastTrackToRemove.clear();
5662
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005663 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5664 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5665 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5666 // If destination is non-contiguous, first read past the nominal end of buffer, then
5667 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005668
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005669 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005670 ssize_t framesRead;
5671
5672 // If an NBAIO source is present, use it to read the normal capture's data
5673 if (mPipeSource != 0) {
5674 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005675 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005676 framesToRead, AudioBufferProvider::kInvalidPTS);
5677 if (framesRead == 0) {
5678 // since pipe is non-blocking, simulate blocking input
5679 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5680 }
5681 // otherwise use the HAL / AudioStreamIn directly
5682 } else {
5683 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005684 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005685 if (bytesRead < 0) {
5686 framesRead = bytesRead;
5687 } else {
5688 framesRead = bytesRead / mFrameSize;
5689 }
5690 }
5691
5692 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5693 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005694 // Force input into standby so that it tries to recover at next read attempt
5695 inputStandBy();
5696 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005697 }
5698 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005699 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005700 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005701 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005702
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005703 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005704 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005705 }
5706 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005707 {
5708 size_t part1 = mRsmpInFramesP2 - rear;
5709 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005710 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005711 (framesRead - part1) * mFrameSize);
5712 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005713 }
5714 rear = mRsmpInRear += framesRead;
5715
5716 size = activeTracks.size();
5717 // loop over each active track
5718 for (size_t i = 0; i < size; i++) {
5719 activeTrack = activeTracks[i];
5720
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005721 // skip fast tracks, as those are handled directly by FastCapture
5722 if (activeTrack->isFastTrack()) {
5723 continue;
5724 }
5725
Andy Hung73c02e42015-03-29 01:13:58 -07005726 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005727 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5728
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005729 enum {
5730 OVERRUN_UNKNOWN,
5731 OVERRUN_TRUE,
5732 OVERRUN_FALSE
5733 } overrun = OVERRUN_UNKNOWN;
5734
5735 // loop over getNextBuffer to handle circular sink
5736 for (;;) {
5737
5738 activeTrack->mSink.frameCount = ~0;
5739 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5740 size_t framesOut = activeTrack->mSink.frameCount;
5741 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5742
Andy Hung73c02e42015-03-29 01:13:58 -07005743 // check available frames and handle overrun conditions
5744 // if the record track isn't draining fast enough.
5745 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005746 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005747 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5748 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005749 overrun = OVERRUN_TRUE;
5750 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005751 if (framesOut == 0 || framesIn == 0) {
5752 break;
5753 }
5754
Andy Hung6770c6f2015-04-07 13:43:36 -07005755 // Don't allow framesOut to be larger than what is possible with resampling
5756 // from framesIn.
5757 // This isn't strictly necessary but helps limit buffer resizing in
5758 // RecordBufferConverter. TODO: remove when no longer needed.
5759 framesOut = min(framesOut,
5760 destinationFramesPossible(
5761 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005762 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5763 framesOut = activeTrack->mRecordBufferConverter->convert(
5764 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005765
5766 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5767 overrun = OVERRUN_FALSE;
5768 }
5769
5770 if (activeTrack->mFramesToDrop == 0) {
5771 if (framesOut > 0) {
5772 activeTrack->mSink.frameCount = framesOut;
5773 activeTrack->releaseBuffer(&activeTrack->mSink);
5774 }
5775 } else {
5776 // FIXME could do a partial drop of framesOut
5777 if (activeTrack->mFramesToDrop > 0) {
5778 activeTrack->mFramesToDrop -= framesOut;
5779 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005780 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005781 }
5782 } else {
5783 activeTrack->mFramesToDrop += framesOut;
5784 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5785 activeTrack->mSyncStartEvent->isCancelled()) {
5786 ALOGW("Synced record %s, session %d, trigger session %d",
5787 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5788 activeTrack->sessionId(),
5789 (activeTrack->mSyncStartEvent != 0) ?
5790 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005791 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005792 }
5793 }
5794 }
5795
5796 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005797 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005798 }
5799 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005800
5801 switch (overrun) {
5802 case OVERRUN_TRUE:
5803 // client isn't retrieving buffers fast enough
5804 if (!activeTrack->setOverflow()) {
5805 nsecs_t now = systemTime();
5806 // FIXME should lastWarning per track?
5807 if ((now - lastWarning) > kWarningThrottleNs) {
5808 ALOGW("RecordThread: buffer overflow");
5809 lastWarning = now;
5810 }
5811 }
5812 break;
5813 case OVERRUN_FALSE:
5814 activeTrack->clearOverflow();
5815 break;
5816 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005817 break;
5818 }
5819
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005820 }
5821
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005822unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005823 // enable changes in effect chain
5824 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005825 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005826 }
5827
Glenn Kasten93e471f2013-08-19 08:40:07 -07005828 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005829
5830 {
5831 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005832 for (size_t i = 0; i < mTracks.size(); i++) {
5833 sp<RecordTrack> track = mTracks[i];
5834 track->invalidate();
5835 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005836 mActiveTracks.clear();
5837 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005838 mStartStopCond.broadcast();
5839 }
5840
5841 releaseWakeLock();
5842
5843 ALOGV("RecordThread %p exiting", this);
5844 return false;
5845}
5846
Glenn Kasten93e471f2013-08-19 08:40:07 -07005847void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005848{
5849 if (!mStandby) {
5850 inputStandBy();
5851 mStandby = true;
5852 }
5853}
5854
5855void AudioFlinger::RecordThread::inputStandBy()
5856{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005857 // Idle the fast capture if it's currently running
5858 if (mFastCapture != 0) {
5859 FastCaptureStateQueue *sq = mFastCapture->sq();
5860 FastCaptureState *state = sq->begin();
5861 if (!(state->mCommand & FastCaptureState::IDLE)) {
5862 state->mCommand = FastCaptureState::COLD_IDLE;
5863 state->mColdFutexAddr = &mFastCaptureFutex;
5864 state->mColdGen++;
5865 mFastCaptureFutex = 0;
5866 sq->end();
5867 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5868 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5869#if 0
5870 if (kUseFastCapture == FastCapture_Dynamic) {
5871 // FIXME
5872 }
5873#endif
5874#ifdef AUDIO_WATCHDOG
5875 // FIXME
5876#endif
5877 } else {
5878 sq->end(false /*didModify*/);
5879 }
5880 }
Eric Laurent81784c32012-11-19 14:55:58 -08005881 mInput->stream->common.standby(&mInput->stream->common);
5882}
5883
Glenn Kasten05997e22014-03-13 15:08:33 -07005884// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005885sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005886 const sp<AudioFlinger::Client>& client,
5887 uint32_t sampleRate,
5888 audio_format_t format,
5889 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005890 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005891 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005892 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005893 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005894 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005895 pid_t tid,
5896 status_t *status)
5897{
Glenn Kasten74935e42013-12-19 08:56:45 -08005898 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005899 sp<RecordTrack> track;
5900 status_t lStatus;
5901
Glenn Kasten90e58b12013-07-31 16:16:02 -07005902 // client expresses a preference for FAST, but we get the final say
5903 if (*flags & IAudioFlinger::TRACK_FAST) {
5904 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005905 // we formerly checked for a callback handler (non-0 tid),
5906 // but that is no longer required for TRANSFER_OBTAIN mode
5907 //
Glenn Kasten74105912014-07-03 12:28:53 -07005908 // frame count is not specified, or is exactly the pipe depth
5909 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005910 // PCM data
5911 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005912 // native format
5913 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005914 // native channel mask
5915 (channelMask == mChannelMask) &&
5916 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005917 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005918 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005919 hasFastCapture() &&
5920 // there are sufficient fast track slots available
5921 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005922 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005923 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005924 frameCount, mFrameCount);
5925 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005926 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5927 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005928 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005929 frameCount, mFrameCount, mPipeFramesP2,
5930 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5931 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005932 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005933 }
5934 }
5935
5936 // compute track buffer size in frames, and suggest the notification frame count
5937 if (*flags & IAudioFlinger::TRACK_FAST) {
5938 // fast track: frame count is exactly the pipe depth
5939 frameCount = mPipeFramesP2;
5940 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5941 *notificationFrames = mFrameCount;
5942 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005943 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5944 // or 20 ms if there is a fast capture
5945 // TODO This could be a roundupRatio inline, and const
5946 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5947 * sampleRate + mSampleRate - 1) / mSampleRate;
5948 // minimum number of notification periods is at least kMinNotifications,
5949 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5950 static const size_t kMinNotifications = 3;
5951 static const uint32_t kMinMs = 30;
5952 // TODO This could be a roundupRatio inline
5953 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5954 // TODO This could be a roundupRatio inline
5955 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5956 maxNotificationFrames;
5957 const size_t minFrameCount = maxNotificationFrames *
5958 max(kMinNotifications, minNotificationsByMs);
5959 frameCount = max(frameCount, minFrameCount);
5960 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5961 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005962 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005963 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005964 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005965
Glenn Kasten15e57982013-09-24 11:52:37 -07005966 lStatus = initCheck();
5967 if (lStatus != NO_ERROR) {
5968 ALOGE("createRecordTrack_l() audio driver not initialized");
5969 goto Exit;
5970 }
Eric Laurent81784c32012-11-19 14:55:58 -08005971
5972 { // scope for mLock
5973 Mutex::Autolock _l(mLock);
5974
5975 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005976 format, channelMask, frameCount, NULL, sessionId, uid,
5977 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005978
Glenn Kasten03003332013-08-06 15:40:54 -07005979 lStatus = track->initCheck();
5980 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005981 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005982 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005983 goto Exit;
5984 }
5985 mTracks.add(track);
5986
5987 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5988 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5989 mAudioFlinger->btNrecIsOff();
5990 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5991 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005992
5993 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5994 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5995 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5996 // so ask activity manager to do this on our behalf
5997 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5998 }
Eric Laurent81784c32012-11-19 14:55:58 -08005999 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006000
Eric Laurent81784c32012-11-19 14:55:58 -08006001 lStatus = NO_ERROR;
6002
6003Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006004 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006005 return track;
6006}
6007
6008status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6009 AudioSystem::sync_event_t event,
6010 int triggerSession)
6011{
6012 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6013 sp<ThreadBase> strongMe = this;
6014 status_t status = NO_ERROR;
6015
6016 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006017 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006018 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006019 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006020 triggerSession,
6021 recordTrack->sessionId(),
6022 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006023 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006024 // Sync event can be cancelled by the trigger session if the track is not in a
6025 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006027 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006028 } else {
6029 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006030 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006031 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006032 }
6033 }
6034
6035 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006036 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006037 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6039 if (recordTrack->mState == TrackBase::PAUSING) {
6040 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006041 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006042 } else {
6043 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006044 }
6045 return status;
6046 }
6047
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006048 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6049 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6050 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006051 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006052 mActiveTracks.add(recordTrack);
6053 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006054 status_t status = NO_ERROR;
6055 if (recordTrack->isExternalTrack()) {
6056 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006057 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006058 mLock.lock();
6059 // FIXME should verify that recordTrack is still in mActiveTracks
6060 if (status != NO_ERROR) {
6061 mActiveTracks.remove(recordTrack);
6062 mActiveTracksGen++;
6063 recordTrack->clearSyncStartEvent();
6064 ALOGV("RecordThread::start error %d", status);
6065 return status;
6066 }
Eric Laurent81784c32012-11-19 14:55:58 -08006067 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006068 // Catch up with current buffer indices if thread is already running.
6069 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6070 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6071 // see previously buffered data before it called start(), but with greater risk of overrun.
6072
Andy Hung73c02e42015-03-29 01:13:58 -07006073 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006074 // clear any converter state as new data will be discontinuous
6075 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006076 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006077 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006078 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006079 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006080 ALOGV("Record failed to start");
6081 status = BAD_VALUE;
6082 goto startError;
6083 }
Eric Laurent81784c32012-11-19 14:55:58 -08006084 return status;
6085 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006086
Eric Laurent81784c32012-11-19 14:55:58 -08006087startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006088 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006089 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006090 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006091 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006092 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006093 return status;
6094}
6095
Eric Laurent81784c32012-11-19 14:55:58 -08006096void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6097{
6098 sp<SyncEvent> strongEvent = event.promote();
6099
6100 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006101 sp<RefBase> ptr = strongEvent->cookie().promote();
6102 if (ptr != 0) {
6103 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6104 recordTrack->handleSyncStartEvent(strongEvent);
6105 }
Eric Laurent81784c32012-11-19 14:55:58 -08006106 }
6107}
6108
Glenn Kastena8356f62013-07-25 14:37:52 -07006109bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006110 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006111 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006112 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006113 return false;
6114 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006115 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006116 recordTrack->mState = TrackBase::PAUSING;
6117 // do not wait for mStartStopCond if exiting
6118 if (exitPending()) {
6119 return true;
6120 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006121 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006122 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006123 // if we have been restarted, recordTrack is in mActiveTracks here
6124 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006125 ALOGV("Record stopped OK");
6126 return true;
6127 }
6128 return false;
6129}
6130
Glenn Kasten0f11b512014-01-31 16:18:54 -08006131bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006132{
6133 return false;
6134}
6135
Glenn Kasten0f11b512014-01-31 16:18:54 -08006136status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006137{
6138#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6139 if (!isValidSyncEvent(event)) {
6140 return BAD_VALUE;
6141 }
6142
6143 int eventSession = event->triggerSession();
6144 status_t ret = NAME_NOT_FOUND;
6145
6146 Mutex::Autolock _l(mLock);
6147
6148 for (size_t i = 0; i < mTracks.size(); i++) {
6149 sp<RecordTrack> track = mTracks[i];
6150 if (eventSession == track->sessionId()) {
6151 (void) track->setSyncEvent(event);
6152 ret = NO_ERROR;
6153 }
6154 }
6155 return ret;
6156#else
6157 return BAD_VALUE;
6158#endif
6159}
6160
6161// destroyTrack_l() must be called with ThreadBase::mLock held
6162void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6163{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006164 track->terminate();
6165 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006166 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006167 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006168 removeTrack_l(track);
6169 }
6170}
6171
6172void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6173{
6174 mTracks.remove(track);
6175 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006176 if (track->isFastTrack()) {
6177 ALOG_ASSERT(!mFastTrackAvail);
6178 mFastTrackAvail = true;
6179 }
Eric Laurent81784c32012-11-19 14:55:58 -08006180}
6181
6182void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6183{
6184 dumpInternals(fd, args);
6185 dumpTracks(fd, args);
6186 dumpEffectChains(fd, args);
6187}
6188
6189void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6190{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006191 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006192
Glenn Kasten44182c22015-03-05 17:12:23 -08006193 dumpBase(fd, args);
6194
6195 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006196 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006197 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006198 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006199 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006200
6201 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6202 const FastCaptureDumpState copy(mFastCaptureDumpState);
6203 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006204}
6205
Glenn Kasten0f11b512014-01-31 16:18:54 -08006206void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006207{
6208 const size_t SIZE = 256;
6209 char buffer[SIZE];
6210 String8 result;
6211
Marco Nelissenb2208842014-02-07 14:00:50 -08006212 size_t numtracks = mTracks.size();
6213 size_t numactive = mActiveTracks.size();
6214 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006215 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006216 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006217 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006218 RecordTrack::appendDumpHeader(result);
6219 for (size_t i = 0; i < numtracks ; ++i) {
6220 sp<RecordTrack> track = mTracks[i];
6221 if (track != 0) {
6222 bool active = mActiveTracks.indexOf(track) >= 0;
6223 if (active) {
6224 numactiveseen++;
6225 }
6226 track->dump(buffer, SIZE, active);
6227 result.append(buffer);
6228 }
Eric Laurent81784c32012-11-19 14:55:58 -08006229 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006230 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006231 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006232 }
6233
Marco Nelissenb2208842014-02-07 14:00:50 -08006234 if (numactiveseen != numactive) {
6235 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6236 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006237 result.append(buffer);
6238 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006239 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006240 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006241 if (mTracks.indexOf(track) < 0) {
6242 track->dump(buffer, SIZE, true);
6243 result.append(buffer);
6244 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006245 }
Eric Laurent81784c32012-11-19 14:55:58 -08006246
6247 }
6248 write(fd, result.string(), result.size());
6249}
6250
Andy Hung73c02e42015-03-29 01:13:58 -07006251
6252void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6253{
6254 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6255 RecordThread *recordThread = (RecordThread *) threadBase.get();
6256 mRsmpInFront = recordThread->mRsmpInRear;
6257 mRsmpInUnrel = 0;
6258}
6259
6260void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6261 size_t *framesAvailable, bool *hasOverrun)
6262{
6263 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6264 RecordThread *recordThread = (RecordThread *) threadBase.get();
6265 const int32_t rear = recordThread->mRsmpInRear;
6266 const int32_t front = mRsmpInFront;
6267 const ssize_t filled = rear - front;
6268
6269 size_t framesIn;
6270 bool overrun = false;
6271 if (filled < 0) {
6272 // should not happen, but treat like a massive overrun and re-sync
6273 framesIn = 0;
6274 mRsmpInFront = rear;
6275 overrun = true;
6276 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6277 framesIn = (size_t) filled;
6278 } else {
6279 // client is not keeping up with server, but give it latest data
6280 framesIn = recordThread->mRsmpInFrames;
6281 mRsmpInFront = /* front = */ rear - framesIn;
6282 overrun = true;
6283 }
6284 if (framesAvailable != NULL) {
6285 *framesAvailable = framesIn;
6286 }
6287 if (hasOverrun != NULL) {
6288 *hasOverrun = overrun;
6289 }
6290}
6291
Eric Laurent81784c32012-11-19 14:55:58 -08006292// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006293status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6294 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006295{
Andy Hung73c02e42015-03-29 01:13:58 -07006296 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006297 if (threadBase == 0) {
6298 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006299 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006300 return NOT_ENOUGH_DATA;
6301 }
6302 RecordThread *recordThread = (RecordThread *) threadBase.get();
6303 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006304 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006305 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006306 // FIXME should not be P2 (don't want to increase latency)
6307 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006308 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006309 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006310 front &= recordThread->mRsmpInFramesP2 - 1;
6311 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006312 if (part1 > (size_t) filled) {
6313 part1 = filled;
6314 }
6315 size_t ask = buffer->frameCount;
6316 ALOG_ASSERT(ask > 0);
6317 if (part1 > ask) {
6318 part1 = ask;
6319 }
6320 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006321 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006322 buffer->raw = NULL;
6323 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006324 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006325 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006326 }
6327
Andy Hung57446612015-04-19 23:56:46 -07006328 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006329 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006330 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006331 return NO_ERROR;
6332}
6333
6334// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006335void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6336 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006337{
Glenn Kasten85948432013-08-19 12:09:05 -07006338 size_t stepCount = buffer->frameCount;
6339 if (stepCount == 0) {
6340 return;
6341 }
Andy Hung73c02e42015-03-29 01:13:58 -07006342 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6343 mRsmpInUnrel -= stepCount;
6344 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006345 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006346 buffer->frameCount = 0;
6347}
6348
Andy Hung97a893e2015-03-29 01:03:07 -07006349AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6350 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6351 uint32_t srcSampleRate,
6352 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6353 uint32_t dstSampleRate) :
6354 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6355 // mSrcFormat
6356 // mSrcSampleRate
6357 // mDstChannelMask
6358 // mDstFormat
6359 // mDstSampleRate
6360 // mSrcChannelCount
6361 // mDstChannelCount
6362 // mDstFrameSize
6363 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006364 mResampler(NULL),
6365 mIsLegacyDownmix(false),
6366 mIsLegacyUpmix(false),
6367 mRequiresFloat(false),
6368 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006369{
6370 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6371 dstChannelMask, dstFormat, dstSampleRate);
6372}
6373
6374AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6375 free(mBuf);
6376 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006377 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006378}
6379
6380size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6381 AudioBufferProvider *provider, size_t frames)
6382{
Andy Hungd330ee42015-04-20 13:23:41 -07006383 if (mInputConverterProvider != NULL) {
6384 mInputConverterProvider->setBufferProvider(provider);
6385 provider = mInputConverterProvider;
6386 }
6387
6388 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006389 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6390 mSrcSampleRate, mSrcFormat, mDstFormat);
6391
6392 AudioBufferProvider::Buffer buffer;
6393 for (size_t i = frames; i > 0; ) {
6394 buffer.frameCount = i;
6395 status_t status = provider->getNextBuffer(&buffer, 0);
6396 if (status != OK || buffer.frameCount == 0) {
6397 frames -= i; // cannot fill request.
6398 break;
6399 }
Andy Hungd330ee42015-04-20 13:23:41 -07006400 // format convert to destination buffer
6401 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006402
6403 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6404 i -= buffer.frameCount;
6405 provider->releaseBuffer(&buffer);
6406 }
6407 } else {
6408 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6409 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6410
Andy Hungd330ee42015-04-20 13:23:41 -07006411 // reallocate buffer if needed
6412 if (mBufFrameSize != 0 && mBufFrames < frames) {
6413 free(mBuf);
6414 mBufFrames = frames;
6415 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6416 }
Andy Hung97a893e2015-03-29 01:03:07 -07006417 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006418 memset(mBuf, 0, frames * mBufFrameSize);
6419 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6420 // format convert to destination buffer
6421 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006422 }
6423 return frames;
6424}
6425
6426status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6427 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6428 uint32_t srcSampleRate,
6429 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6430 uint32_t dstSampleRate)
6431{
6432 // quick evaluation if there is any change.
6433 if (mSrcFormat == srcFormat
6434 && mSrcChannelMask == srcChannelMask
6435 && mSrcSampleRate == srcSampleRate
6436 && mDstFormat == dstFormat
6437 && mDstChannelMask == dstChannelMask
6438 && mDstSampleRate == dstSampleRate) {
6439 return NO_ERROR;
6440 }
6441
6442 const bool valid =
6443 audio_is_input_channel(srcChannelMask)
6444 && audio_is_input_channel(dstChannelMask)
6445 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6446 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6447 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6448 ; // no upsampling checks for now
6449 if (!valid) {
6450 return BAD_VALUE;
6451 }
6452
6453 mSrcFormat = srcFormat;
6454 mSrcChannelMask = srcChannelMask;
6455 mSrcSampleRate = srcSampleRate;
6456 mDstFormat = dstFormat;
6457 mDstChannelMask = dstChannelMask;
6458 mDstSampleRate = dstSampleRate;
6459
6460 // compute derived parameters
6461 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6462 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6463 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6464
Andy Hungd330ee42015-04-20 13:23:41 -07006465 // do we need to resample?
6466 delete mResampler;
6467 mResampler = NULL;
6468 if (mSrcSampleRate != mDstSampleRate) {
6469 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6470 mSrcChannelCount, mDstSampleRate);
6471 mResampler->setSampleRate(mSrcSampleRate);
6472 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6473 }
6474
6475 // are we running legacy channel conversion modes?
6476 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6477 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6478 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6479 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6480 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6481 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6482
6483 // do we need to process in float?
6484 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6485
6486 // do we need a staging buffer to convert for destination (we can still optimize this)?
6487 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6488 if (mResampler != NULL) {
6489 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6490 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6491 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6492 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6493 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006494 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6495 } else {
6496 mBufFrameSize = 0;
6497 }
6498 mBufFrames = 0; // force the buffer to be resized.
6499
Andy Hungd330ee42015-04-20 13:23:41 -07006500 // do we need an input converter buffer provider to give us float?
6501 delete mInputConverterProvider;
6502 mInputConverterProvider = NULL;
6503 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6504 mInputConverterProvider = new ReformatBufferProvider(
6505 audio_channel_count_from_in_mask(mSrcChannelMask),
6506 mSrcFormat,
6507 AUDIO_FORMAT_PCM_FLOAT,
6508 256 /* provider buffer frame count */);
6509 }
6510
6511 // do we need a remixer to do channel mask conversion
6512 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6513 (void) memcpy_by_index_array_initialization_from_channel_mask(
6514 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006515 }
6516 return NO_ERROR;
6517}
6518
Andy Hungd330ee42015-04-20 13:23:41 -07006519void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6520 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006521{
Andy Hungd330ee42015-04-20 13:23:41 -07006522 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006523 if (mBufFrameSize != 0 && mBufFrames < frames) {
6524 free(mBuf);
6525 mBufFrames = frames;
6526 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6527 }
Andy Hungd330ee42015-04-20 13:23:41 -07006528 // do we need to do legacy upmix and downmix?
6529 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006530 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006531 if (mIsLegacyUpmix) {
6532 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6533 (const float *)src, frames);
6534 } else /*mIsLegacyDownmix */ {
6535 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6536 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006537 }
Andy Hungd330ee42015-04-20 13:23:41 -07006538 if (mBuf != NULL) {
6539 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6540 frames * mDstChannelCount);
6541 }
6542 return;
6543 }
6544 // do we need to do channel mask conversion?
6545 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006546 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006547 memcpy_by_index_array(dstBuf, mDstChannelCount,
6548 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6549 if (dstBuf == dst) {
6550 return; // format is the same
6551 }
6552 }
6553 // convert to destination buffer
6554 const void *convertBuf = mBuf != NULL ? mBuf : src;
6555 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6556 frames * mDstChannelCount);
6557}
6558
6559void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6560 void *dst, /*not-a-const*/ void *src, size_t frames)
6561{
6562 // src buffer format is ALWAYS float when entering this routine
6563 if (mIsLegacyUpmix) {
6564 ; // mono to stereo already handled by resampler
6565 } else if (mIsLegacyDownmix
6566 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6567 // the resampler outputs stereo for mono input channel (a feature?)
6568 // must convert to mono
6569 downmix_to_mono_float_from_stereo_float((float *)src,
6570 (const float *)src, frames);
6571 } else if (mSrcChannelMask != mDstChannelMask) {
6572 // convert to mono channel again for channel mask conversion (could be skipped
6573 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006574 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006575 downmix_to_mono_float_from_stereo_float((float *)src,
6576 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006577 }
Andy Hungd330ee42015-04-20 13:23:41 -07006578 // convert to destination format (in place, OK as float is larger than other types)
6579 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6580 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6581 frames * mSrcChannelCount);
6582 }
6583 // channel convert and save to dst
6584 memcpy_by_index_array(dst, mDstChannelCount,
6585 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6586 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006587 }
Andy Hungd330ee42015-04-20 13:23:41 -07006588 // convert to destination format and save to dst
6589 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6590 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006591}
6592
Eric Laurent10351942014-05-08 18:49:52 -07006593bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6594 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006595{
6596 bool reconfig = false;
6597
Eric Laurent10351942014-05-08 18:49:52 -07006598 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006599
Eric Laurent10351942014-05-08 18:49:52 -07006600 audio_format_t reqFormat = mFormat;
6601 uint32_t samplingRate = mSampleRate;
6602 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006603 // possible that we are > 2 channels, use channel index mask
6604 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6605 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6606 }
Eric Laurent10351942014-05-08 18:49:52 -07006607
6608 AudioParameter param = AudioParameter(keyValuePair);
6609 int value;
6610 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6611 // channel count change can be requested. Do we mandate the first client defines the
6612 // HAL sampling rate and channel count or do we allow changes on the fly?
6613 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6614 samplingRate = value;
6615 reconfig = true;
6616 }
6617 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006618 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006619 status = BAD_VALUE;
6620 } else {
6621 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006622 reconfig = true;
6623 }
Eric Laurent10351942014-05-08 18:49:52 -07006624 }
6625 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6626 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006627 if (!audio_is_input_channel(mask) ||
6628 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006629 status = BAD_VALUE;
6630 } else {
6631 channelMask = mask;
6632 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006633 }
Eric Laurent10351942014-05-08 18:49:52 -07006634 }
6635 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6636 // do not accept frame count changes if tracks are open as the track buffer
6637 // size depends on frame count and correct behavior would not be guaranteed
6638 // if frame count is changed after track creation
6639 if (mActiveTracks.size() > 0) {
6640 status = INVALID_OPERATION;
6641 } else {
6642 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006643 }
Eric Laurent10351942014-05-08 18:49:52 -07006644 }
6645 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6646 // forward device change to effects that have requested to be
6647 // aware of attached audio device.
6648 for (size_t i = 0; i < mEffectChains.size(); i++) {
6649 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006650 }
Eric Laurent81784c32012-11-19 14:55:58 -08006651
Eric Laurent10351942014-05-08 18:49:52 -07006652 // store input device and output device but do not forward output device to audio HAL.
6653 // Note that status is ignored by the caller for output device
6654 // (see AudioFlinger::setParameters()
6655 if (audio_is_output_devices(value)) {
6656 mOutDevice = value;
6657 status = BAD_VALUE;
6658 } else {
6659 mInDevice = value;
6660 // disable AEC and NS if the device is a BT SCO headset supporting those
6661 // pre processings
6662 if (mTracks.size() > 0) {
6663 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6664 mAudioFlinger->btNrecIsOff();
6665 for (size_t i = 0; i < mTracks.size(); i++) {
6666 sp<RecordTrack> track = mTracks[i];
6667 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6668 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006669 }
6670 }
6671 }
Eric Laurent10351942014-05-08 18:49:52 -07006672 }
6673 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6674 mAudioSource != (audio_source_t)value) {
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]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006679 }
Eric Laurent10351942014-05-08 18:49:52 -07006680 mAudioSource = (audio_source_t)value;
6681 }
Glenn Kastene198c362013-08-13 09:13:36 -07006682
Eric Laurent10351942014-05-08 18:49:52 -07006683 if (status == NO_ERROR) {
6684 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6685 keyValuePair.string());
6686 if (status == INVALID_OPERATION) {
6687 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006688 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6689 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006690 }
6691 if (reconfig) {
6692 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006693 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6694 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006695 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006696 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006697 audio_channel_count_from_in_mask(
6698 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006699 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6700 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6701 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006702 }
Eric Laurent10351942014-05-08 18:49:52 -07006703 if (status == NO_ERROR) {
6704 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006705 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006706 }
6707 }
Eric Laurent81784c32012-11-19 14:55:58 -08006708 }
Eric Laurent10351942014-05-08 18:49:52 -07006709
Eric Laurent81784c32012-11-19 14:55:58 -08006710 return reconfig;
6711}
6712
6713String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6714{
Eric Laurent81784c32012-11-19 14:55:58 -08006715 Mutex::Autolock _l(mLock);
6716 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006717 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006718 }
6719
Glenn Kastend8ea6992013-07-16 14:17:15 -07006720 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6721 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006722 free(s);
6723 return out_s8;
6724}
6725
Eric Laurent73e26b62015-04-27 16:55:58 -07006726void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6727 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6728
6729 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006730
6731 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006732 case AUDIO_INPUT_OPENED:
6733 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006734 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006735 desc->mChannelMask = mChannelMask;
6736 desc->mSamplingRate = mSampleRate;
6737 desc->mFormat = mFormat;
6738 desc->mFrameCount = mFrameCount;
6739 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006740 break;
6741
Eric Laurent73e26b62015-04-27 16:55:58 -07006742 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006743 default:
6744 break;
6745 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006746 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006747}
6748
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006749void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006750{
Eric Laurent81784c32012-11-19 14:55:58 -08006751 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6752 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006753 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006754 if (mChannelCount > FCC_8) {
6755 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6756 }
Andy Hung463be252014-07-10 16:56:07 -07006757 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6758 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006759 if (!audio_is_linear_pcm(mFormat)) {
6760 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006761 }
Eric Laurent665470b2014-07-03 16:37:08 -07006762 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006763 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6764 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006765 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006766 // 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 -07006767 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006768 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006769 // A larger value should allow more old data to be read after a track calls start(),
6770 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006771 //
6772 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006773 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006774 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006775 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006776
6777 // TODO optimize audio capture buffer sizes ...
6778 // Here we calculate the size of the sliding buffer used as a source
6779 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6780 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6781 // be better to have it derived from the pipe depth in the long term.
6782 // The current value is higher than necessary. However it should not add to latency.
6783
Glenn Kasten85948432013-08-19 12:09:05 -07006784 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006785 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006786
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006787 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6788 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006789}
6790
Glenn Kasten5f972c02014-01-13 09:59:31 -08006791uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006792{
6793 Mutex::Autolock _l(mLock);
6794 if (initCheck() != NO_ERROR) {
6795 return 0;
6796 }
6797
6798 return mInput->stream->get_input_frames_lost(mInput->stream);
6799}
6800
6801uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6802{
6803 Mutex::Autolock _l(mLock);
6804 uint32_t result = 0;
6805 if (getEffectChain_l(sessionId) != 0) {
6806 result = EFFECT_SESSION;
6807 }
6808
6809 for (size_t i = 0; i < mTracks.size(); ++i) {
6810 if (sessionId == mTracks[i]->sessionId()) {
6811 result |= TRACK_SESSION;
6812 break;
6813 }
6814 }
6815
6816 return result;
6817}
6818
6819KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6820{
6821 KeyedVector<int, bool> ids;
6822 Mutex::Autolock _l(mLock);
6823 for (size_t j = 0; j < mTracks.size(); ++j) {
6824 sp<RecordThread::RecordTrack> track = mTracks[j];
6825 int sessionId = track->sessionId();
6826 if (ids.indexOfKey(sessionId) < 0) {
6827 ids.add(sessionId, true);
6828 }
6829 }
6830 return ids;
6831}
6832
6833AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6834{
6835 Mutex::Autolock _l(mLock);
6836 AudioStreamIn *input = mInput;
6837 mInput = NULL;
6838 return input;
6839}
6840
6841// this method must always be called either with ThreadBase mLock held or inside the thread loop
6842audio_stream_t* AudioFlinger::RecordThread::stream() const
6843{
6844 if (mInput == NULL) {
6845 return NULL;
6846 }
6847 return &mInput->stream->common;
6848}
6849
6850status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6851{
6852 // only one chain per input thread
6853 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006854 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006855 return INVALID_OPERATION;
6856 }
6857 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006858 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006859 chain->setInBuffer(NULL);
6860 chain->setOutBuffer(NULL);
6861
6862 checkSuspendOnAddEffectChain_l(chain);
6863
Eric Laurent1b928682014-10-02 19:41:47 -07006864 // make sure enabled pre processing effects state is communicated to the HAL as we
6865 // just moved them to a new input stream.
6866 chain->syncHalEffectsState();
6867
Eric Laurent81784c32012-11-19 14:55:58 -08006868 mEffectChains.add(chain);
6869
6870 return NO_ERROR;
6871}
6872
6873size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6874{
6875 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6876 ALOGW_IF(mEffectChains.size() != 1,
6877 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6878 chain.get(), mEffectChains.size(), this);
6879 if (mEffectChains.size() == 1) {
6880 mEffectChains.removeAt(0);
6881 }
6882 return 0;
6883}
6884
Eric Laurent1c333e22014-05-20 10:48:17 -07006885status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6886 audio_patch_handle_t *handle)
6887{
6888 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006889
6890 // store new device and send to effects
6891 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07006892 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07006893 for (size_t i = 0; i < mEffectChains.size(); i++) {
6894 mEffectChains[i]->setDevice_l(mInDevice);
6895 }
6896
6897 // disable AEC and NS if the device is a BT SCO headset supporting those
6898 // pre processings
6899 if (mTracks.size() > 0) {
6900 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6901 mAudioFlinger->btNrecIsOff();
6902 for (size_t i = 0; i < mTracks.size(); i++) {
6903 sp<RecordTrack> track = mTracks[i];
6904 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6905 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6906 }
6907 }
6908
6909 // store new source and send to effects
6910 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6911 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07006912 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07006913 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07006914 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006915 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006916
Eric Laurent054d9d32015-04-24 08:48:48 -07006917 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006918 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6919 status = hwDevice->create_audio_patch(hwDevice,
6920 patch->num_sources,
6921 patch->sources,
6922 patch->num_sinks,
6923 patch->sinks,
6924 handle);
6925 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006926 char *address;
6927 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
6928 address = audio_device_address_to_parameter(
6929 patch->sources[0].ext.device.type,
6930 patch->sources[0].ext.device.address);
6931 } else {
6932 address = (char *)calloc(1, 1);
6933 }
6934 AudioParameter param = AudioParameter(String8(address));
6935 free(address);
6936 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
6937 (int)patch->sources[0].ext.device.type);
6938 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
6939 (int)patch->sinks[0].ext.mix.usecase.source);
6940 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6941 param.toString().string());
6942 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07006943 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006944
Eric Laurent296fb132015-05-01 11:38:42 -07006945 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
6946
Eric Laurent1c333e22014-05-20 10:48:17 -07006947 return status;
6948}
6949
6950status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6951{
6952 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006953
6954 mInDevice = AUDIO_DEVICE_NONE;
6955
Eric Laurent1c333e22014-05-20 10:48:17 -07006956 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6957 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6958 status = hwDevice->release_audio_patch(hwDevice, handle);
6959 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006960 AudioParameter param;
6961 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
6962 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6963 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07006964 }
6965 return status;
6966}
6967
Eric Laurent83b88082014-06-20 18:31:16 -07006968void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6969{
6970 Mutex::Autolock _l(mLock);
6971 mTracks.add(record);
6972}
6973
6974void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6975{
6976 Mutex::Autolock _l(mLock);
6977 destroyTrack_l(record);
6978}
6979
6980void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6981{
6982 ThreadBase::getAudioPortConfig(config);
6983 config->role = AUDIO_PORT_ROLE_SINK;
6984 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6985 config->ext.mix.usecase.source = mAudioSource;
6986}
Eric Laurent1c333e22014-05-20 10:48:17 -07006987
Glenn Kasten63238ef2015-03-02 15:50:29 -08006988} // namespace android