blob: e02c79fb6be95bdc55d25b9be1a8c4bda7021e5c [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 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002682 bool released = false;
2683 // The following works around a bug in the offload driver. Ideally we would release
2684 // the wake lock every time, but that causes the last offload buffer(s) to be
2685 // dropped while the device is on battery, so we need to hold a wake lock during
2686 // the drain phase.
2687 if (mBytesRemaining && !(mDrainSequence & 1)) {
2688 releaseWakeLock_l();
2689 released = true;
2690 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002691 mWakeLockUids.clear();
2692 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002693 ALOGV("wait async completion");
2694 mWaitWorkCV.wait(mLock);
2695 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002696 if (released) {
2697 acquireWakeLock_l();
2698 }
Eric Laurent972a1732013-09-04 09:42:59 -07002699 standbyTime = systemTime() + standbyDelay;
2700 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002701
2702 continue;
2703 }
2704 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002705 isSuspended()) {
2706 // put audio hardware into standby after short delay
2707 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002708
2709 threadLoop_standby();
2710
2711 mStandby = true;
2712 }
2713
2714 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2715 // we're about to wait, flush the binder command buffer
2716 IPCThreadState::self()->flushCommands();
2717
2718 clearOutputTracks();
2719
2720 if (exitPending()) {
2721 break;
2722 }
2723
2724 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002725 mWakeLockUids.clear();
2726 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002727 // wait until we have something to do...
2728 ALOGV("%s going to sleep", myName.string());
2729 mWaitWorkCV.wait(mLock);
2730 ALOGV("%s waking up", myName.string());
2731 acquireWakeLock_l();
2732
2733 mMixerStatus = MIXER_IDLE;
2734 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2735 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002737 checkSilentMode_l();
2738
2739 standbyTime = systemTime() + standbyDelay;
2740 sleepTime = idleSleepTime;
2741 if (mType == MIXER) {
2742 sleepTimeShift = 0;
2743 }
2744
2745 continue;
2746 }
2747 }
Eric Laurent81784c32012-11-19 14:55:58 -08002748 // mMixerStatusIgnoringFastTracks is also updated internally
2749 mMixerStatus = prepareTracks_l(&tracksToRemove);
2750
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002751 // compare with previously applied list
2752 if (lastGeneration != mActiveTracksGeneration) {
2753 // update wakelock
2754 updateWakeLockUids_l(mWakeLockUids);
2755 lastGeneration = mActiveTracksGeneration;
2756 }
2757
Eric Laurent81784c32012-11-19 14:55:58 -08002758 // prevent any changes in effect chain list and in each effect chain
2759 // during mixing and effect process as the audio buffers could be deleted
2760 // or modified if an effect is created or deleted
2761 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002762 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002763
Eric Laurentbfb1b832013-01-07 09:53:42 -08002764 if (mBytesRemaining == 0) {
2765 mCurrentWriteLength = 0;
2766 if (mMixerStatus == MIXER_TRACKS_READY) {
2767 // threadLoop_mix() sets mCurrentWriteLength
2768 threadLoop_mix();
2769 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2770 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2771 // threadLoop_sleepTime sets sleepTime to 0 if data
2772 // must be written to HAL
2773 threadLoop_sleepTime();
2774 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002775 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 }
2777 }
Andy Hung98ef9782014-03-04 14:46:50 -08002778 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2779 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2780 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2781 // or mSinkBuffer (if there are no effects).
2782 //
2783 // This is done pre-effects computation; if effects change to
2784 // support higher precision, this needs to move.
2785 //
2786 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2787 // TODO use sleepTime == 0 as an additional condition.
2788 if (mMixerBufferValid) {
2789 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2790 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2791
2792 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2793 mNormalFrameCount * mChannelCount);
2794 }
2795
Eric Laurentbfb1b832013-01-07 09:53:42 -08002796 mBytesRemaining = mCurrentWriteLength;
2797 if (isSuspended()) {
2798 sleepTime = suspendSleepTimeUs();
2799 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002800 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 mBytesRemaining = 0;
2802 }
Eric Laurent81784c32012-11-19 14:55:58 -08002803
Eric Laurentbfb1b832013-01-07 09:53:42 -08002804 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002805 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002806 for (size_t i = 0; i < effectChains.size(); i ++) {
2807 effectChains[i]->process_l();
2808 }
Eric Laurent81784c32012-11-19 14:55:58 -08002809 }
2810 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002811 // Process effect chains for offloaded thread even if no audio
2812 // was read from audio track: process only updates effect state
2813 // and thus does have to be synchronized with audio writes but may have
2814 // to be called while waiting for async write callback
2815 if (mType == OFFLOAD) {
2816 for (size_t i = 0; i < effectChains.size(); i ++) {
2817 effectChains[i]->process_l();
2818 }
2819 }
Eric Laurent81784c32012-11-19 14:55:58 -08002820
Andy Hung98ef9782014-03-04 14:46:50 -08002821 // Only if the Effects buffer is enabled and there is data in the
2822 // Effects buffer (buffer valid), we need to
2823 // copy into the sink buffer.
2824 // TODO use sleepTime == 0 as an additional condition.
2825 if (mEffectBufferValid) {
2826 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2827 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2828 mNormalFrameCount * mChannelCount);
2829 }
2830
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // enable changes in effect chain
2832 unlockEffectChains(effectChains);
2833
Eric Laurentbfb1b832013-01-07 09:53:42 -08002834 if (!waitingAsyncCallback()) {
2835 // sleepTime == 0 means we must write to audio hardware
2836 if (sleepTime == 0) {
2837 if (mBytesRemaining) {
2838 ssize_t ret = threadLoop_write();
2839 if (ret < 0) {
2840 mBytesRemaining = 0;
2841 } else {
2842 mBytesWritten += ret;
2843 mBytesRemaining -= ret;
2844 }
2845 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2846 (mMixerStatus == MIXER_DRAIN_ALL)) {
2847 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002848 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002849 if (mType == MIXER) {
2850 // write blocked detection
2851 nsecs_t now = systemTime();
2852 nsecs_t delta = now - mLastWriteTime;
2853 if (!mStandby && delta > maxPeriod) {
2854 mNumDelayedWrites++;
2855 if ((now - lastWarning) > kWarningThrottleNs) {
2856 ATRACE_NAME("underrun");
2857 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2858 ns2ms(delta), mNumDelayedWrites, this);
2859 lastWarning = now;
2860 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861 }
2862 }
Eric Laurent81784c32012-11-19 14:55:58 -08002863
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002865 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002867 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 }
Eric Laurent81784c32012-11-19 14:55:58 -08002869 }
2870
2871 // Finally let go of removed track(s), without the lock held
2872 // since we can't guarantee the destructors won't acquire that
2873 // same lock. This will also mutate and push a new fast mixer state.
2874 threadLoop_removeTracks(tracksToRemove);
2875 tracksToRemove.clear();
2876
2877 // FIXME I don't understand the need for this here;
2878 // it was in the original code but maybe the
2879 // assignment in saveOutputTracks() makes this unnecessary?
2880 clearOutputTracks();
2881
2882 // Effect chains will be actually deleted here if they were removed from
2883 // mEffectChains list during mixing or effects processing
2884 effectChains.clear();
2885
2886 // FIXME Note that the above .clear() is no longer necessary since effectChains
2887 // is now local to this block, but will keep it for now (at least until merge done).
2888 }
2889
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 threadLoop_exit();
2891
Eric Laurentcf817a22014-08-04 20:36:31 -07002892 if (!mStandby) {
2893 threadLoop_standby();
2894 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002895 }
2896
2897 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002898 mWakeLockUids.clear();
2899 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002900
2901 ALOGV("Thread %p type %d exiting", this, mType);
2902 return false;
2903}
2904
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905// removeTracks_l() must be called with ThreadBase::mLock held
2906void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2907{
2908 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002909 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910 for (size_t i=0 ; i<count ; i++) {
2911 const sp<Track>& track = tracksToRemove.itemAt(i);
2912 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002913 mWakeLockUids.remove(track->uid());
2914 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2916 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2917 if (chain != 0) {
2918 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2919 track->sessionId());
2920 chain->decActiveTrackCnt();
2921 }
2922 if (track->isTerminated()) {
2923 removeTrack_l(track);
2924 }
2925 }
2926 }
2927
2928}
Eric Laurent81784c32012-11-19 14:55:58 -08002929
Eric Laurentaccc1472013-09-20 09:36:34 -07002930status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2931{
2932 if (mNormalSink != 0) {
2933 return mNormalSink->getTimestamp(timestamp);
2934 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002935 if ((mType == OFFLOAD || mType == DIRECT)
2936 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002937 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002938 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002939 if (ret == 0) {
2940 timestamp.mPosition = (uint32_t)position64;
2941 return NO_ERROR;
2942 }
2943 }
2944 return INVALID_OPERATION;
2945}
Eric Laurent1c333e22014-05-20 10:48:17 -07002946
Eric Laurent054d9d32015-04-24 08:48:48 -07002947status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
2948 audio_patch_handle_t *handle)
2949{
2950 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
2951 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
2952 if (mFastMixer != 0) {
2953 FastMixerStateQueue *sq = mFastMixer->sq();
2954 FastMixerState *state = sq->begin();
2955 if (!(state->mCommand & FastMixerState::IDLE)) {
2956 previousCommand = state->mCommand;
2957 state->mCommand = FastMixerState::HOT_IDLE;
2958 sq->end();
2959 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2960 } else {
2961 sq->end(false /*didModify*/);
2962 }
2963 }
2964 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
2965
2966 if (!(previousCommand & FastMixerState::IDLE)) {
2967 ALOG_ASSERT(mFastMixer != 0);
2968 FastMixerStateQueue *sq = mFastMixer->sq();
2969 FastMixerState *state = sq->begin();
2970 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
2971 state->mCommand = previousCommand;
2972 sq->end();
2973 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2974 }
2975
2976 return status;
2977}
2978
Eric Laurent1c333e22014-05-20 10:48:17 -07002979status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2980 audio_patch_handle_t *handle)
2981{
2982 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07002983
2984 // store new device and send to effects
2985 audio_devices_t type = AUDIO_DEVICE_NONE;
2986 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2987 type |= patch->sinks[i].ext.device.type;
2988 }
2989
2990#ifdef ADD_BATTERY_DATA
2991 // when changing the audio output device, call addBatteryData to notify
2992 // the change
2993 if (mOutDevice != type) {
2994 uint32_t params = 0;
2995 // check whether speaker is on
2996 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
2997 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07002998 }
2999
Eric Laurent054d9d32015-04-24 08:48:48 -07003000 audio_devices_t deviceWithoutSpeaker
3001 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3002 // check if any other device (except speaker) is on
3003 if (type & deviceWithoutSpeaker) {
3004 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3005 }
3006
3007 if (params != 0) {
3008 addBatteryData(params);
3009 }
3010 }
3011#endif
3012
3013 for (size_t i = 0; i < mEffectChains.size(); i++) {
3014 mEffectChains[i]->setDevice_l(type);
3015 }
3016 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003017 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003018
3019 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003020 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3021 status = hwDevice->create_audio_patch(hwDevice,
3022 patch->num_sources,
3023 patch->sources,
3024 patch->num_sinks,
3025 patch->sinks,
3026 handle);
3027 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003028 char *address;
3029 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3030 //FIXME: we only support address on first sink with HAL version < 3.0
3031 address = audio_device_address_to_parameter(
3032 patch->sinks[0].ext.device.type,
3033 patch->sinks[0].ext.device.address);
3034 } else {
3035 address = (char *)calloc(1, 1);
3036 }
3037 AudioParameter param = AudioParameter(String8(address));
3038 free(address);
3039 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3040 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3041 param.toString().string());
3042 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003043 }
Eric Laurent296fb132015-05-01 11:38:42 -07003044 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent1c333e22014-05-20 10:48:17 -07003045 return status;
3046}
3047
Eric Laurent054d9d32015-04-24 08:48:48 -07003048status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3049{
3050 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3051 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3052 if (mFastMixer != 0) {
3053 FastMixerStateQueue *sq = mFastMixer->sq();
3054 FastMixerState *state = sq->begin();
3055 if (!(state->mCommand & FastMixerState::IDLE)) {
3056 previousCommand = state->mCommand;
3057 state->mCommand = FastMixerState::HOT_IDLE;
3058 sq->end();
3059 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3060 } else {
3061 sq->end(false /*didModify*/);
3062 }
3063 }
3064
3065 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3066
3067 if (!(previousCommand & FastMixerState::IDLE)) {
3068 ALOG_ASSERT(mFastMixer != 0);
3069 FastMixerStateQueue *sq = mFastMixer->sq();
3070 FastMixerState *state = sq->begin();
3071 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3072 state->mCommand = previousCommand;
3073 sq->end();
3074 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3075 }
3076
3077 return status;
3078}
3079
Eric Laurent1c333e22014-05-20 10:48:17 -07003080status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3081{
3082 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003083
3084 mOutDevice = AUDIO_DEVICE_NONE;
3085
Eric Laurent1c333e22014-05-20 10:48:17 -07003086 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3087 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3088 status = hwDevice->release_audio_patch(hwDevice, handle);
3089 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003090 AudioParameter param;
3091 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3092 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3093 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003094 }
3095 return status;
3096}
3097
Eric Laurent83b88082014-06-20 18:31:16 -07003098void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3099{
3100 Mutex::Autolock _l(mLock);
3101 mTracks.add(track);
3102}
3103
3104void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3105{
3106 Mutex::Autolock _l(mLock);
3107 destroyTrack_l(track);
3108}
3109
3110void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3111{
3112 ThreadBase::getAudioPortConfig(config);
3113 config->role = AUDIO_PORT_ROLE_SOURCE;
3114 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3115 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3116}
3117
Eric Laurent81784c32012-11-19 14:55:58 -08003118// ----------------------------------------------------------------------------
3119
3120AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
3121 audio_io_handle_t id, audio_devices_t device, type_t type)
3122 : PlaybackThread(audioFlinger, output, id, device, type),
3123 // mAudioMixer below
3124 // mFastMixer below
3125 mFastMixerFutex(0)
3126 // mOutputSink below
3127 // mPipeSink below
3128 // mNormalSink below
3129{
3130 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003131 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003132 "mFrameCount=%d, mNormalFrameCount=%d",
3133 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3134 mNormalFrameCount);
3135 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3136
Andy Hungfbfc3952015-01-15 13:33:51 -08003137 if (type == DUPLICATING) {
3138 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3139 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3140 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3141 return;
3142 }
Eric Laurent81784c32012-11-19 14:55:58 -08003143 // create an NBAIO sink for the HAL output stream, and negotiate
3144 mOutputSink = new AudioStreamOutSink(output->stream);
3145 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003146 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003147 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3148 ALOG_ASSERT(index == 0);
3149
3150 // initialize fast mixer depending on configuration
3151 bool initFastMixer;
3152 switch (kUseFastMixer) {
3153 case FastMixer_Never:
3154 initFastMixer = false;
3155 break;
3156 case FastMixer_Always:
3157 initFastMixer = true;
3158 break;
3159 case FastMixer_Static:
3160 case FastMixer_Dynamic:
3161 initFastMixer = mFrameCount < mNormalFrameCount;
3162 break;
3163 }
3164 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003165 audio_format_t fastMixerFormat;
3166 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3167 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3168 } else {
3169 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3170 }
3171 if (mFormat != fastMixerFormat) {
3172 // change our Sink format to accept our intermediate precision
3173 mFormat = fastMixerFormat;
3174 free(mSinkBuffer);
3175 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3176 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3177 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3178 }
Eric Laurent81784c32012-11-19 14:55:58 -08003179
3180 // create a MonoPipe to connect our submix to FastMixer
3181 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003182 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003183 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003184 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003185 format.mFormat = fastMixerFormat;
3186 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3187
Eric Laurent81784c32012-11-19 14:55:58 -08003188 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3189 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3190 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3191 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3192 const NBAIO_Format offers[1] = {format};
3193 size_t numCounterOffers = 0;
3194 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3195 ALOG_ASSERT(index == 0);
3196 monoPipe->setAvgFrames((mScreenState & 1) ?
3197 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3198 mPipeSink = monoPipe;
3199
Glenn Kasten46909e72013-02-26 09:20:22 -08003200#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003201 if (mTeeSinkOutputEnabled) {
3202 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003203 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3204 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003205 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003206 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003207 ALOG_ASSERT(index == 0);
3208 mTeeSink = teeSink;
3209 PipeReader *teeSource = new PipeReader(*teeSink);
3210 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003211 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003212 ALOG_ASSERT(index == 0);
3213 mTeeSource = teeSource;
3214 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003215#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003216
3217 // create fast mixer and configure it initially with just one fast track for our submix
3218 mFastMixer = new FastMixer();
3219 FastMixerStateQueue *sq = mFastMixer->sq();
3220#ifdef STATE_QUEUE_DUMP
3221 sq->setObserverDump(&mStateQueueObserverDump);
3222 sq->setMutatorDump(&mStateQueueMutatorDump);
3223#endif
3224 FastMixerState *state = sq->begin();
3225 FastTrack *fastTrack = &state->mFastTracks[0];
3226 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3227 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3228 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003229 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3230 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003231 fastTrack->mGeneration++;
3232 state->mFastTracksGen++;
3233 state->mTrackMask = 1;
3234 // fast mixer will use the HAL output sink
3235 state->mOutputSink = mOutputSink.get();
3236 state->mOutputSinkGen++;
3237 state->mFrameCount = mFrameCount;
3238 state->mCommand = FastMixerState::COLD_IDLE;
3239 // already done in constructor initialization list
3240 //mFastMixerFutex = 0;
3241 state->mColdFutexAddr = &mFastMixerFutex;
3242 state->mColdGen++;
3243 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003244#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003245 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003246#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003247 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3248 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003249 sq->end();
3250 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3251
3252 // start the fast mixer
3253 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3254 pid_t tid = mFastMixer->getTid();
3255 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3256 if (err != 0) {
3257 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3258 kPriorityFastMixer, getpid_cached, tid, err);
3259 }
3260
3261#ifdef AUDIO_WATCHDOG
3262 // create and start the watchdog
3263 mAudioWatchdog = new AudioWatchdog();
3264 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3265 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3266 tid = mAudioWatchdog->getTid();
3267 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3268 if (err != 0) {
3269 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3270 kPriorityFastMixer, getpid_cached, tid, err);
3271 }
3272#endif
3273
Eric Laurent81784c32012-11-19 14:55:58 -08003274 }
3275
3276 switch (kUseFastMixer) {
3277 case FastMixer_Never:
3278 case FastMixer_Dynamic:
3279 mNormalSink = mOutputSink;
3280 break;
3281 case FastMixer_Always:
3282 mNormalSink = mPipeSink;
3283 break;
3284 case FastMixer_Static:
3285 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3286 break;
3287 }
3288}
3289
3290AudioFlinger::MixerThread::~MixerThread()
3291{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003292 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003293 FastMixerStateQueue *sq = mFastMixer->sq();
3294 FastMixerState *state = sq->begin();
3295 if (state->mCommand == FastMixerState::COLD_IDLE) {
3296 int32_t old = android_atomic_inc(&mFastMixerFutex);
3297 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003298 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003299 }
3300 }
3301 state->mCommand = FastMixerState::EXIT;
3302 sq->end();
3303 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3304 mFastMixer->join();
3305 // Though the fast mixer thread has exited, it's state queue is still valid.
3306 // We'll use that extract the final state which contains one remaining fast track
3307 // corresponding to our sub-mix.
3308 state = sq->begin();
3309 ALOG_ASSERT(state->mTrackMask == 1);
3310 FastTrack *fastTrack = &state->mFastTracks[0];
3311 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3312 delete fastTrack->mBufferProvider;
3313 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003314 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003315#ifdef AUDIO_WATCHDOG
3316 if (mAudioWatchdog != 0) {
3317 mAudioWatchdog->requestExit();
3318 mAudioWatchdog->requestExitAndWait();
3319 mAudioWatchdog.clear();
3320 }
3321#endif
3322 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003323 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003324 delete mAudioMixer;
3325}
3326
3327
3328uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3329{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003330 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003331 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3332 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3333 }
3334 return latency;
3335}
3336
3337
3338void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3339{
3340 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3341}
3342
Eric Laurentbfb1b832013-01-07 09:53:42 -08003343ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003344{
3345 // FIXME we should only do one push per cycle; confirm this is true
3346 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003347 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003348 FastMixerStateQueue *sq = mFastMixer->sq();
3349 FastMixerState *state = sq->begin();
3350 if (state->mCommand != FastMixerState::MIX_WRITE &&
3351 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3352 if (state->mCommand == FastMixerState::COLD_IDLE) {
3353 int32_t old = android_atomic_inc(&mFastMixerFutex);
3354 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003355 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003356 }
3357#ifdef AUDIO_WATCHDOG
3358 if (mAudioWatchdog != 0) {
3359 mAudioWatchdog->resume();
3360 }
3361#endif
3362 }
3363 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003364#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003365 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003366 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003367#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003368 sq->end();
3369 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3370 if (kUseFastMixer == FastMixer_Dynamic) {
3371 mNormalSink = mPipeSink;
3372 }
3373 } else {
3374 sq->end(false /*didModify*/);
3375 }
3376 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003378}
3379
3380void AudioFlinger::MixerThread::threadLoop_standby()
3381{
3382 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003383 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003384 FastMixerStateQueue *sq = mFastMixer->sq();
3385 FastMixerState *state = sq->begin();
3386 if (!(state->mCommand & FastMixerState::IDLE)) {
3387 state->mCommand = FastMixerState::COLD_IDLE;
3388 state->mColdFutexAddr = &mFastMixerFutex;
3389 state->mColdGen++;
3390 mFastMixerFutex = 0;
3391 sq->end();
3392 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3393 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3394 if (kUseFastMixer == FastMixer_Dynamic) {
3395 mNormalSink = mOutputSink;
3396 }
3397#ifdef AUDIO_WATCHDOG
3398 if (mAudioWatchdog != 0) {
3399 mAudioWatchdog->pause();
3400 }
3401#endif
3402 } else {
3403 sq->end(false /*didModify*/);
3404 }
3405 }
3406 PlaybackThread::threadLoop_standby();
3407}
3408
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3410{
3411 return false;
3412}
3413
3414bool AudioFlinger::PlaybackThread::shouldStandby_l()
3415{
3416 return !mStandby;
3417}
3418
3419bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3420{
3421 Mutex::Autolock _l(mLock);
3422 return waitingAsyncCallback_l();
3423}
3424
Eric Laurent81784c32012-11-19 14:55:58 -08003425// shared by MIXER and DIRECT, overridden by DUPLICATING
3426void AudioFlinger::PlaybackThread::threadLoop_standby()
3427{
3428 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003429 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003430 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003431 // discard any pending drain or write ack by incrementing sequence
3432 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3433 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003434 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003435 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3436 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003437 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003438 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003439}
3440
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003441void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3442{
3443 ALOGV("signal playback thread");
3444 broadcast_l();
3445}
3446
Eric Laurent81784c32012-11-19 14:55:58 -08003447void AudioFlinger::MixerThread::threadLoop_mix()
3448{
3449 // obtain the presentation timestamp of the next output buffer
3450 int64_t pts;
3451 status_t status = INVALID_OPERATION;
3452
3453 if (mNormalSink != 0) {
3454 status = mNormalSink->getNextWriteTimestamp(&pts);
3455 } else {
3456 status = mOutputSink->getNextWriteTimestamp(&pts);
3457 }
3458
3459 if (status != NO_ERROR) {
3460 pts = AudioBufferProvider::kInvalidPTS;
3461 }
3462
3463 // mix buffers...
3464 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003465 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003466 // increase sleep time progressively when application underrun condition clears.
3467 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3468 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3469 // such that we would underrun the audio HAL.
3470 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3471 sleepTimeShift--;
3472 }
3473 sleepTime = 0;
3474 standbyTime = systemTime() + standbyDelay;
3475 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003476
Eric Laurent81784c32012-11-19 14:55:58 -08003477}
3478
3479void AudioFlinger::MixerThread::threadLoop_sleepTime()
3480{
3481 // If no tracks are ready, sleep once for the duration of an output
3482 // buffer size, then write 0s to the output
3483 if (sleepTime == 0) {
3484 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3485 sleepTime = activeSleepTime >> sleepTimeShift;
3486 if (sleepTime < kMinThreadSleepTimeUs) {
3487 sleepTime = kMinThreadSleepTimeUs;
3488 }
3489 // reduce sleep time in case of consecutive application underruns to avoid
3490 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3491 // duration we would end up writing less data than needed by the audio HAL if
3492 // the condition persists.
3493 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3494 sleepTimeShift++;
3495 }
3496 } else {
3497 sleepTime = idleSleepTime;
3498 }
3499 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003500 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3501 // before effects processing or output.
3502 if (mMixerBufferValid) {
3503 memset(mMixerBuffer, 0, mMixerBufferSize);
3504 } else {
3505 memset(mSinkBuffer, 0, mSinkBufferSize);
3506 }
Eric Laurent81784c32012-11-19 14:55:58 -08003507 sleepTime = 0;
3508 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3509 "anticipated start");
3510 }
3511 // TODO add standby time extension fct of effect tail
3512}
3513
3514// prepareTracks_l() must be called with ThreadBase::mLock held
3515AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3516 Vector< sp<Track> > *tracksToRemove)
3517{
3518
3519 mixer_state mixerStatus = MIXER_IDLE;
3520 // find out which tracks need to be processed
3521 size_t count = mActiveTracks.size();
3522 size_t mixedTracks = 0;
3523 size_t tracksWithEffect = 0;
3524 // counts only _active_ fast tracks
3525 size_t fastTracks = 0;
3526 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3527
3528 float masterVolume = mMasterVolume;
3529 bool masterMute = mMasterMute;
3530
3531 if (masterMute) {
3532 masterVolume = 0;
3533 }
3534 // Delegate master volume control to effect in output mix effect chain if needed
3535 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3536 if (chain != 0) {
3537 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3538 chain->setVolume_l(&v, &v);
3539 masterVolume = (float)((v + (1 << 23)) >> 24);
3540 chain.clear();
3541 }
3542
3543 // prepare a new state to push
3544 FastMixerStateQueue *sq = NULL;
3545 FastMixerState *state = NULL;
3546 bool didModify = false;
3547 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003548 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003549 sq = mFastMixer->sq();
3550 state = sq->begin();
3551 }
3552
Andy Hung69aed5f2014-02-25 17:24:40 -08003553 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003554 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003555
Eric Laurent81784c32012-11-19 14:55:58 -08003556 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003557 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003558 if (t == 0) {
3559 continue;
3560 }
3561
3562 // this const just means the local variable doesn't change
3563 Track* const track = t.get();
3564
3565 // process fast tracks
3566 if (track->isFastTrack()) {
3567
3568 // It's theoretically possible (though unlikely) for a fast track to be created
3569 // and then removed within the same normal mix cycle. This is not a problem, as
3570 // the track never becomes active so it's fast mixer slot is never touched.
3571 // The converse, of removing an (active) track and then creating a new track
3572 // at the identical fast mixer slot within the same normal mix cycle,
3573 // is impossible because the slot isn't marked available until the end of each cycle.
3574 int j = track->mFastIndex;
3575 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3576 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3577 FastTrack *fastTrack = &state->mFastTracks[j];
3578
3579 // Determine whether the track is currently in underrun condition,
3580 // and whether it had a recent underrun.
3581 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3582 FastTrackUnderruns underruns = ftDump->mUnderruns;
3583 uint32_t recentFull = (underruns.mBitFields.mFull -
3584 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3585 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3586 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3587 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3588 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3589 uint32_t recentUnderruns = recentPartial + recentEmpty;
3590 track->mObservedUnderruns = underruns;
3591 // don't count underruns that occur while stopping or pausing
3592 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003593 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3594 recentUnderruns > 0) {
3595 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3596 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003597 }
3598
3599 // This is similar to the state machine for normal tracks,
3600 // with a few modifications for fast tracks.
3601 bool isActive = true;
3602 switch (track->mState) {
3603 case TrackBase::STOPPING_1:
3604 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003605 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003606 track->mState = TrackBase::STOPPING_2;
3607 }
3608 break;
3609 case TrackBase::PAUSING:
3610 // ramp down is not yet implemented
3611 track->setPaused();
3612 break;
3613 case TrackBase::RESUMING:
3614 // ramp up is not yet implemented
3615 track->mState = TrackBase::ACTIVE;
3616 break;
3617 case TrackBase::ACTIVE:
3618 if (recentFull > 0 || recentPartial > 0) {
3619 // track has provided at least some frames recently: reset retry count
3620 track->mRetryCount = kMaxTrackRetries;
3621 }
3622 if (recentUnderruns == 0) {
3623 // no recent underruns: stay active
3624 break;
3625 }
3626 // there has recently been an underrun of some kind
3627 if (track->sharedBuffer() == 0) {
3628 // were any of the recent underruns "empty" (no frames available)?
3629 if (recentEmpty == 0) {
3630 // no, then ignore the partial underruns as they are allowed indefinitely
3631 break;
3632 }
3633 // there has recently been an "empty" underrun: decrement the retry counter
3634 if (--(track->mRetryCount) > 0) {
3635 break;
3636 }
3637 // indicate to client process that the track was disabled because of underrun;
3638 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003639 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003640 // remove from active list, but state remains ACTIVE [confusing but true]
3641 isActive = false;
3642 break;
3643 }
3644 // fall through
3645 case TrackBase::STOPPING_2:
3646 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003647 case TrackBase::STOPPED:
3648 case TrackBase::FLUSHED: // flush() while active
3649 // Check for presentation complete if track is inactive
3650 // We have consumed all the buffers of this track.
3651 // This would be incomplete if we auto-paused on underrun
3652 {
3653 size_t audioHALFrames =
3654 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3655 size_t framesWritten = mBytesWritten / mFrameSize;
3656 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3657 // track stays in active list until presentation is complete
3658 break;
3659 }
3660 }
3661 if (track->isStopping_2()) {
3662 track->mState = TrackBase::STOPPED;
3663 }
3664 if (track->isStopped()) {
3665 // Can't reset directly, as fast mixer is still polling this track
3666 // track->reset();
3667 // So instead mark this track as needing to be reset after push with ack
3668 resetMask |= 1 << i;
3669 }
3670 isActive = false;
3671 break;
3672 case TrackBase::IDLE:
3673 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003674 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003675 }
3676
3677 if (isActive) {
3678 // was it previously inactive?
3679 if (!(state->mTrackMask & (1 << j))) {
3680 ExtendedAudioBufferProvider *eabp = track;
3681 VolumeProvider *vp = track;
3682 fastTrack->mBufferProvider = eabp;
3683 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003684 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003685 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003686 fastTrack->mGeneration++;
3687 state->mTrackMask |= 1 << j;
3688 didModify = true;
3689 // no acknowledgement required for newly active tracks
3690 }
3691 // cache the combined master volume and stream type volume for fast mixer; this
3692 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003693 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003694 ++fastTracks;
3695 } else {
3696 // was it previously active?
3697 if (state->mTrackMask & (1 << j)) {
3698 fastTrack->mBufferProvider = NULL;
3699 fastTrack->mGeneration++;
3700 state->mTrackMask &= ~(1 << j);
3701 didModify = true;
3702 // If any fast tracks were removed, we must wait for acknowledgement
3703 // because we're about to decrement the last sp<> on those tracks.
3704 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3705 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003706 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003707 }
3708 tracksToRemove->add(track);
3709 // Avoids a misleading display in dumpsys
3710 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3711 }
3712 continue;
3713 }
3714
3715 { // local variable scope to avoid goto warning
3716
3717 audio_track_cblk_t* cblk = track->cblk();
3718
3719 // The first time a track is added we wait
3720 // for all its buffers to be filled before processing it
3721 int name = track->name();
3722 // make sure that we have enough frames to mix one full buffer.
3723 // enforce this condition only once to enable draining the buffer in case the client
3724 // app does not call stop() and relies on underrun to stop:
3725 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3726 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003727 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003728 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003729 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003730
3731 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003732 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003733 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3734 // add frames already consumed but not yet released by the resampler
3735 // because mAudioTrackServerProxy->framesReady() will include these frames
3736 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3737
Eric Laurent81784c32012-11-19 14:55:58 -08003738 uint32_t minFrames = 1;
3739 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3740 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003741 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003742 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003743
3744 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003745 if (ATRACE_ENABLED()) {
3746 // I wish we had formatted trace names
3747 char traceName[16];
3748 strcpy(traceName, "nRdy");
3749 int name = track->name();
3750 if (AudioMixer::TRACK0 <= name &&
3751 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3752 name -= AudioMixer::TRACK0;
3753 traceName[4] = (name / 10) + '0';
3754 traceName[5] = (name % 10) + '0';
3755 } else {
3756 traceName[4] = '?';
3757 traceName[5] = '?';
3758 }
3759 traceName[6] = '\0';
3760 ATRACE_INT(traceName, framesReady);
3761 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003762 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003763 !track->isPaused() && !track->isTerminated())
3764 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003765 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003766
3767 mixedTracks++;
3768
Andy Hung69aed5f2014-02-25 17:24:40 -08003769 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3770 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003771 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003772 if (track->mainBuffer() != mSinkBuffer &&
3773 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003774 if (mEffectBufferEnabled) {
3775 mEffectBufferValid = true; // Later can set directly.
3776 }
Eric Laurent81784c32012-11-19 14:55:58 -08003777 chain = getEffectChain_l(track->sessionId());
3778 // Delegate volume control to effect in track effect chain if needed
3779 if (chain != 0) {
3780 tracksWithEffect++;
3781 } else {
3782 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3783 "session %d",
3784 name, track->sessionId());
3785 }
3786 }
3787
3788
3789 int param = AudioMixer::VOLUME;
3790 if (track->mFillingUpStatus == Track::FS_FILLED) {
3791 // no ramp for the first volume setting
3792 track->mFillingUpStatus = Track::FS_ACTIVE;
3793 if (track->mState == TrackBase::RESUMING) {
3794 track->mState = TrackBase::ACTIVE;
3795 param = AudioMixer::RAMP_VOLUME;
3796 }
3797 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003798 // FIXME should not make a decision based on mServer
3799 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003800 // If the track is stopped before the first frame was mixed,
3801 // do not apply ramp
3802 param = AudioMixer::RAMP_VOLUME;
3803 }
3804
3805 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003806 uint32_t vl, vr; // in U8.24 integer format
3807 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003808 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003809 vl = vr = 0;
3810 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003811 if (track->isPausing()) {
3812 track->setPaused();
3813 }
3814 } else {
3815
3816 // read original volumes with volume control
3817 float typeVolume = mStreamTypes[track->streamType()].volume;
3818 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003819 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003820 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003821 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3822 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003823 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003824 if (vlf > GAIN_FLOAT_UNITY) {
3825 ALOGV("Track left volume out of range: %.3g", vlf);
3826 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003827 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003828 if (vrf > GAIN_FLOAT_UNITY) {
3829 ALOGV("Track right volume out of range: %.3g", vrf);
3830 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003831 }
3832 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003833 vlf *= v;
3834 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003835 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003836 // then derive vl and vr as U8.24 versions for the effect chain
3837 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3838 vl = (uint32_t) (scaleto8_24 * vlf);
3839 vr = (uint32_t) (scaleto8_24 * vrf);
3840 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003841 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003842 // send level comes from shared memory and so may be corrupt
3843 if (sendLevel > MAX_GAIN_INT) {
3844 ALOGV("Track send level out of range: %04X", sendLevel);
3845 sendLevel = MAX_GAIN_INT;
3846 }
Andy Hung6be49402014-05-30 10:42:03 -07003847 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3848 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003849 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003850
Eric Laurent81784c32012-11-19 14:55:58 -08003851 // Delegate volume control to effect in track effect chain if needed
3852 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3853 // Do not ramp volume if volume is controlled by effect
3854 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003855 // Update remaining floating point volume levels
3856 vlf = (float)vl / (1 << 24);
3857 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003858 track->mHasVolumeController = true;
3859 } else {
3860 // force no volume ramp when volume controller was just disabled or removed
3861 // from effect chain to avoid volume spike
3862 if (track->mHasVolumeController) {
3863 param = AudioMixer::VOLUME;
3864 }
3865 track->mHasVolumeController = false;
3866 }
3867
Eric Laurent81784c32012-11-19 14:55:58 -08003868 // XXX: these things DON'T need to be done each time
3869 mAudioMixer->setBufferProvider(name, track);
3870 mAudioMixer->enable(name);
3871
Andy Hung6be49402014-05-30 10:42:03 -07003872 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3873 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3874 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 mAudioMixer->setParameter(
3876 name,
3877 AudioMixer::TRACK,
3878 AudioMixer::FORMAT, (void *)track->format());
3879 mAudioMixer->setParameter(
3880 name,
3881 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003882 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003883 mAudioMixer->setParameter(
3884 name,
3885 AudioMixer::TRACK,
3886 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003887 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003888 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003889 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003890 if (reqSampleRate == 0) {
3891 reqSampleRate = mSampleRate;
3892 } else if (reqSampleRate > maxSampleRate) {
3893 reqSampleRate = maxSampleRate;
3894 }
Eric Laurent81784c32012-11-19 14:55:58 -08003895 mAudioMixer->setParameter(
3896 name,
3897 AudioMixer::RESAMPLE,
3898 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003899 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003900
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003901 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003902 mAudioMixer->setParameter(
3903 name,
3904 AudioMixer::TIMESTRETCH,
3905 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003906 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003907
Andy Hung69aed5f2014-02-25 17:24:40 -08003908 /*
3909 * Select the appropriate output buffer for the track.
3910 *
Andy Hung98ef9782014-03-04 14:46:50 -08003911 * Tracks with effects go into their own effects chain buffer
3912 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003913 *
3914 * Other tracks can use mMixerBuffer for higher precision
3915 * channel accumulation. If this buffer is enabled
3916 * (mMixerBufferEnabled true), then selected tracks will accumulate
3917 * into it.
3918 *
3919 */
3920 if (mMixerBufferEnabled
3921 && (track->mainBuffer() == mSinkBuffer
3922 || track->mainBuffer() == mMixerBuffer)) {
3923 mAudioMixer->setParameter(
3924 name,
3925 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003926 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003927 mAudioMixer->setParameter(
3928 name,
3929 AudioMixer::TRACK,
3930 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3931 // TODO: override track->mainBuffer()?
3932 mMixerBufferValid = true;
3933 } else {
3934 mAudioMixer->setParameter(
3935 name,
3936 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003937 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003938 mAudioMixer->setParameter(
3939 name,
3940 AudioMixer::TRACK,
3941 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3942 }
Eric Laurent81784c32012-11-19 14:55:58 -08003943 mAudioMixer->setParameter(
3944 name,
3945 AudioMixer::TRACK,
3946 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3947
3948 // reset retry count
3949 track->mRetryCount = kMaxTrackRetries;
3950
3951 // If one track is ready, set the mixer ready if:
3952 // - the mixer was not ready during previous round OR
3953 // - no other track is not ready
3954 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3955 mixerStatus != MIXER_TRACKS_ENABLED) {
3956 mixerStatus = MIXER_TRACKS_READY;
3957 }
3958 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003959 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003960 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003961 }
Eric Laurent81784c32012-11-19 14:55:58 -08003962 // clear effect chain input buffer if an active track underruns to avoid sending
3963 // previous audio buffer again to effects
3964 chain = getEffectChain_l(track->sessionId());
3965 if (chain != 0) {
3966 chain->clearInputBuffer();
3967 }
3968
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003969 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003970 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3971 track->isStopped() || track->isPaused()) {
3972 // We have consumed all the buffers of this track.
3973 // Remove it from the list of active tracks.
3974 // TODO: use actual buffer filling status instead of latency when available from
3975 // audio HAL
3976 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3977 size_t framesWritten = mBytesWritten / mFrameSize;
3978 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3979 if (track->isStopped()) {
3980 track->reset();
3981 }
3982 tracksToRemove->add(track);
3983 }
3984 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003985 // No buffers for this track. Give it a few chances to
3986 // fill a buffer, then remove it from active list.
3987 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003988 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003989 tracksToRemove->add(track);
3990 // indicate to client process that the track was disabled because of underrun;
3991 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003992 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003993 // If one track is not ready, mark the mixer also not ready if:
3994 // - the mixer was ready during previous round OR
3995 // - no other track is ready
3996 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3997 mixerStatus != MIXER_TRACKS_READY) {
3998 mixerStatus = MIXER_TRACKS_ENABLED;
3999 }
4000 }
4001 mAudioMixer->disable(name);
4002 }
4003
4004 } // local variable scope to avoid goto warning
4005track_is_ready: ;
4006
4007 }
4008
4009 // Push the new FastMixer state if necessary
4010 bool pauseAudioWatchdog = false;
4011 if (didModify) {
4012 state->mFastTracksGen++;
4013 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4014 if (kUseFastMixer == FastMixer_Dynamic &&
4015 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4016 state->mCommand = FastMixerState::COLD_IDLE;
4017 state->mColdFutexAddr = &mFastMixerFutex;
4018 state->mColdGen++;
4019 mFastMixerFutex = 0;
4020 if (kUseFastMixer == FastMixer_Dynamic) {
4021 mNormalSink = mOutputSink;
4022 }
4023 // If we go into cold idle, need to wait for acknowledgement
4024 // so that fast mixer stops doing I/O.
4025 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4026 pauseAudioWatchdog = true;
4027 }
Eric Laurent81784c32012-11-19 14:55:58 -08004028 }
4029 if (sq != NULL) {
4030 sq->end(didModify);
4031 sq->push(block);
4032 }
4033#ifdef AUDIO_WATCHDOG
4034 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4035 mAudioWatchdog->pause();
4036 }
4037#endif
4038
4039 // Now perform the deferred reset on fast tracks that have stopped
4040 while (resetMask != 0) {
4041 size_t i = __builtin_ctz(resetMask);
4042 ALOG_ASSERT(i < count);
4043 resetMask &= ~(1 << i);
4044 sp<Track> t = mActiveTracks[i].promote();
4045 if (t == 0) {
4046 continue;
4047 }
4048 Track* track = t.get();
4049 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4050 track->reset();
4051 }
4052
4053 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004054 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004055
Eric Laurent97d547d2014-09-02 14:45:53 -07004056 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4057 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004058 }
4059
4060 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004061 // as long as there are effects we should clear the effects buffer, to avoid
4062 // passing a non-clean buffer to the effect chain
4063 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004064 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004065 // sink or mix buffer must be cleared if all tracks are connected to an
4066 // effect chain as in this case the mixer will not write to the sink or mix buffer
4067 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004068 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4069 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004070 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004071 if (mMixerBufferValid) {
4072 memset(mMixerBuffer, 0, mMixerBufferSize);
4073 // TODO: In testing, mSinkBuffer below need not be cleared because
4074 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4075 // after mixing.
4076 //
4077 // To enforce this guarantee:
4078 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4079 // (mixedTracks == 0 && fastTracks > 0))
4080 // must imply MIXER_TRACKS_READY.
4081 // Later, we may clear buffers regardless, and skip much of this logic.
4082 }
Andy Hung98ef9782014-03-04 14:46:50 -08004083 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004084 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004085 }
4086
4087 // if any fast tracks, then status is ready
4088 mMixerStatusIgnoringFastTracks = mixerStatus;
4089 if (fastTracks > 0) {
4090 mixerStatus = MIXER_TRACKS_READY;
4091 }
4092 return mixerStatus;
4093}
4094
4095// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004096int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4097 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004098{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004099 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004100}
4101
4102// deleteTrackName_l() must be called with ThreadBase::mLock held
4103void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4104{
4105 ALOGV("remove track (%d) and delete from mixer", name);
4106 mAudioMixer->deleteTrackName(name);
4107}
4108
Eric Laurent10351942014-05-08 18:49:52 -07004109// checkForNewParameter_l() must be called with ThreadBase::mLock held
4110bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4111 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004112{
Eric Laurent81784c32012-11-19 14:55:58 -08004113 bool reconfig = false;
4114
Eric Laurent10351942014-05-08 18:49:52 -07004115 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004116
Eric Laurent10351942014-05-08 18:49:52 -07004117 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4118 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004119 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004120 FastMixerStateQueue *sq = mFastMixer->sq();
4121 FastMixerState *state = sq->begin();
4122 if (!(state->mCommand & FastMixerState::IDLE)) {
4123 previousCommand = state->mCommand;
4124 state->mCommand = FastMixerState::HOT_IDLE;
4125 sq->end();
4126 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4127 } else {
4128 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004129 }
Eric Laurent10351942014-05-08 18:49:52 -07004130 }
Eric Laurent81784c32012-11-19 14:55:58 -08004131
Eric Laurent10351942014-05-08 18:49:52 -07004132 AudioParameter param = AudioParameter(keyValuePair);
4133 int value;
4134 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4135 reconfig = true;
4136 }
4137 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004138 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004139 status = BAD_VALUE;
4140 } else {
4141 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004142 reconfig = true;
4143 }
Eric Laurent10351942014-05-08 18:49:52 -07004144 }
4145 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004146 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004147 status = BAD_VALUE;
4148 } else {
4149 // no need to save value, since it's constant
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::keyFrameCount), value) == NO_ERROR) {
4154 // do not accept frame count changes if tracks are open as the track buffer
4155 // size depends on frame count and correct behavior would not be guaranteed
4156 // if frame count is changed after track creation
4157 if (!mTracks.isEmpty()) {
4158 status = INVALID_OPERATION;
4159 } else {
4160 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 }
Eric Laurent10351942014-05-08 18:49:52 -07004162 }
4163 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004164#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004165 // when changing the audio output device, call addBatteryData to notify
4166 // the change
4167 if (mOutDevice != value) {
4168 uint32_t params = 0;
4169 // check whether speaker is on
4170 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4171 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004172 }
Eric Laurent10351942014-05-08 18:49:52 -07004173
4174 audio_devices_t deviceWithoutSpeaker
4175 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4176 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004177 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004178 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4179 }
4180
4181 if (params != 0) {
4182 addBatteryData(params);
4183 }
4184 }
Eric Laurent81784c32012-11-19 14:55:58 -08004185#endif
4186
Eric Laurent10351942014-05-08 18:49:52 -07004187 // forward device change to effects that have requested to be
4188 // aware of attached audio device.
4189 if (value != AUDIO_DEVICE_NONE) {
4190 mOutDevice = value;
4191 for (size_t i = 0; i < mEffectChains.size(); i++) {
4192 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004193 }
4194 }
Eric Laurent10351942014-05-08 18:49:52 -07004195 }
Eric Laurent81784c32012-11-19 14:55:58 -08004196
Eric Laurent10351942014-05-08 18:49:52 -07004197 if (status == NO_ERROR) {
4198 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4199 keyValuePair.string());
4200 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004201 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004202 mStandby = true;
4203 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004204 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004205 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004206 }
Eric Laurent10351942014-05-08 18:49:52 -07004207 if (status == NO_ERROR && reconfig) {
4208 readOutputParameters_l();
4209 delete mAudioMixer;
4210 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4211 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004212 int name = getTrackName_l(mTracks[i]->mChannelMask,
4213 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004214 if (name < 0) {
4215 break;
4216 }
4217 mTracks[i]->mName = name;
4218 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004219 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004220 }
Eric Laurent81784c32012-11-19 14:55:58 -08004221 }
4222
4223 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004224 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004225 FastMixerStateQueue *sq = mFastMixer->sq();
4226 FastMixerState *state = sq->begin();
4227 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4228 state->mCommand = previousCommand;
4229 sq->end();
4230 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4231 }
4232
4233 return reconfig;
4234}
4235
4236
4237void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4238{
4239 const size_t SIZE = 256;
4240 char buffer[SIZE];
4241 String8 result;
4242
4243 PlaybackThread::dumpInternals(fd, args);
4244
Elliott Hughes87cebad2014-05-22 10:14:43 -07004245 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004246
4247 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004248 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004249 copy.dump(fd);
4250
4251#ifdef STATE_QUEUE_DUMP
4252 // Similar for state queue
4253 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4254 observerCopy.dump(fd);
4255 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4256 mutatorCopy.dump(fd);
4257#endif
4258
Glenn Kasten46909e72013-02-26 09:20:22 -08004259#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004260 // Write the tee output to a .wav file
4261 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004262#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004263
4264#ifdef AUDIO_WATCHDOG
4265 if (mAudioWatchdog != 0) {
4266 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4267 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4268 wdCopy.dump(fd);
4269 }
4270#endif
4271}
4272
4273uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4274{
4275 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4276}
4277
4278uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4279{
4280 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4281}
4282
4283void AudioFlinger::MixerThread::cacheParameters_l()
4284{
4285 PlaybackThread::cacheParameters_l();
4286
4287 // FIXME: Relaxed timing because of a certain device that can't meet latency
4288 // Should be reduced to 2x after the vendor fixes the driver issue
4289 // increase threshold again due to low power audio mode. The way this warning
4290 // threshold is calculated and its usefulness should be reconsidered anyway.
4291 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4292}
4293
4294// ----------------------------------------------------------------------------
4295
4296AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4297 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4298 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4299 // mLeftVolFloat, mRightVolFloat
4300{
4301}
4302
Eric Laurentbfb1b832013-01-07 09:53:42 -08004303AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4304 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4305 ThreadBase::type_t type)
4306 : PlaybackThread(audioFlinger, output, id, device, type)
4307 // mLeftVolFloat, mRightVolFloat
4308{
4309}
4310
Eric Laurent81784c32012-11-19 14:55:58 -08004311AudioFlinger::DirectOutputThread::~DirectOutputThread()
4312{
4313}
4314
Eric Laurentbfb1b832013-01-07 09:53:42 -08004315void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4316{
4317 audio_track_cblk_t* cblk = track->cblk();
4318 float left, right;
4319
4320 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4321 left = right = 0;
4322 } else {
4323 float typeVolume = mStreamTypes[track->streamType()].volume;
4324 float v = mMasterVolume * typeVolume;
4325 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004326 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4327 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4328 if (left > GAIN_FLOAT_UNITY) {
4329 left = GAIN_FLOAT_UNITY;
4330 }
4331 left *= v;
4332 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4333 if (right > GAIN_FLOAT_UNITY) {
4334 right = GAIN_FLOAT_UNITY;
4335 }
4336 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004337 }
4338
4339 if (lastTrack) {
4340 if (left != mLeftVolFloat || right != mRightVolFloat) {
4341 mLeftVolFloat = left;
4342 mRightVolFloat = right;
4343
4344 // Convert volumes from float to 8.24
4345 uint32_t vl = (uint32_t)(left * (1 << 24));
4346 uint32_t vr = (uint32_t)(right * (1 << 24));
4347
4348 // Delegate volume control to effect in track effect chain if needed
4349 // only one effect chain can be present on DirectOutputThread, so if
4350 // there is one, the track is connected to it
4351 if (!mEffectChains.isEmpty()) {
4352 mEffectChains[0]->setVolume_l(&vl, &vr);
4353 left = (float)vl / (1 << 24);
4354 right = (float)vr / (1 << 24);
4355 }
4356 if (mOutput->stream->set_volume) {
4357 mOutput->stream->set_volume(mOutput->stream, left, right);
4358 }
4359 }
4360 }
4361}
4362
4363
Eric Laurent81784c32012-11-19 14:55:58 -08004364AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4365 Vector< sp<Track> > *tracksToRemove
4366)
4367{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004368 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004369 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004370 bool doHwPause = false;
4371 bool doHwResume = false;
4372 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004373
4374 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004375 for (size_t i = 0; i < count; i++) {
4376 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004377 // The track died recently
4378 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004379 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004380 }
4381
4382 Track* const track = t.get();
4383 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004384 // Only consider last track started for volume and mixer state control.
4385 // In theory an older track could underrun and restart after the new one starts
4386 // but as we only care about the transition phase between two tracks on a
4387 // direct output, it is not a problem to ignore the underrun case.
4388 sp<Track> l = mLatestActiveTrack.promote();
4389 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004390
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004391 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004392 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004393 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004394 doHwPause = true;
4395 mHwPaused = true;
4396 }
4397 tracksToRemove->add(track);
4398 } else if (track->isFlushPending()) {
4399 track->flushAck();
4400 if (last) {
4401 flushPending = true;
4402 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004403 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004404 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004405 if (last && mHwPaused) {
4406 doHwResume = true;
4407 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004408 }
4409 }
4410
Eric Laurent81784c32012-11-19 14:55:58 -08004411 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004412 // for all its buffers to be filled before processing it.
4413 // Allow draining the buffer in case the client
4414 // app does not call stop() and relies on underrun to stop:
4415 // hence the test on (track->mRetryCount > 1).
4416 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004417 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004418 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4419 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004420 minFrames = mNormalFrameCount;
4421 } else {
4422 minFrames = 1;
4423 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004424
Eric Laurentab5cdba2014-06-09 17:22:27 -07004425 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4426 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004427 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004428 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004429
4430 if (track->mFillingUpStatus == Track::FS_FILLED) {
4431 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004432 // make sure processVolume_l() will apply new volume even if 0
4433 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004434 if (!mHwSupportsPause) {
4435 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004436 }
4437 }
4438
4439 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004440 processVolume_l(track, last);
4441 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004442 // reset retry count
4443 track->mRetryCount = kMaxTrackRetriesDirect;
4444 mActiveTrack = t;
4445 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004446 if (usesHwAvSync() && mHwPaused) {
4447 doHwResume = true;
4448 mHwPaused = false;
4449 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004450 }
Eric Laurent81784c32012-11-19 14:55:58 -08004451 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004452 // clear effect chain input buffer if the last active track started underruns
4453 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004454 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004455 mEffectChains[0]->clearInputBuffer();
4456 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004457 if (track->isStopping_1()) {
4458 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004459 if (last && mHwPaused) {
4460 doHwResume = true;
4461 mHwPaused = false;
4462 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004463 }
4464 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4465 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004466 // We have consumed all the buffers of this track.
4467 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004468 size_t audioHALFrames;
4469 if (audio_is_linear_pcm(mFormat)) {
4470 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4471 } else {
4472 audioHALFrames = 0;
4473 }
4474
Eric Laurent81784c32012-11-19 14:55:58 -08004475 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004476 if (mStandby || !last ||
4477 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004478 if (track->isStopping_2()) {
4479 track->mState = TrackBase::STOPPED;
4480 }
Eric Laurent81784c32012-11-19 14:55:58 -08004481 if (track->isStopped()) {
4482 track->reset();
4483 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004484 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004485 }
4486 } else {
4487 // No buffers for this track. Give it a few chances to
4488 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004489 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004490 if (--(track->mRetryCount) <= 0) {
4491 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004492 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004493 // indicate to client process that the track was disabled because of underrun;
4494 // it will then automatically call start() when data is available
4495 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004496 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004497 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004498 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4499 doHwPause = true;
4500 mHwPaused = true;
4501 }
Eric Laurent81784c32012-11-19 14:55:58 -08004502 }
4503 }
4504 }
4505 }
4506
Eric Laurentd1f69b02014-12-15 14:33:13 -08004507 // if an active track did not command a flush, check for pending flush on stopped tracks
4508 if (!flushPending) {
4509 for (size_t i = 0; i < mTracks.size(); i++) {
4510 if (mTracks[i]->isFlushPending()) {
4511 mTracks[i]->flushAck();
4512 flushPending = true;
4513 }
4514 }
4515 }
4516
4517 // make sure the pause/flush/resume sequence is executed in the right order.
4518 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4519 // before flush and then resume HW. This can happen in case of pause/flush/resume
4520 // if resume is received before pause is executed.
4521 if (mHwSupportsPause && !mStandby &&
4522 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4523 mOutput->stream->pause(mOutput->stream);
4524 }
4525 if (flushPending) {
4526 flushHw_l();
4527 }
4528 if (mHwSupportsPause && !mStandby && doHwResume) {
4529 mOutput->stream->resume(mOutput->stream);
4530 }
Eric Laurent81784c32012-11-19 14:55:58 -08004531 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004532 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004533
4534 return mixerStatus;
4535}
4536
4537void AudioFlinger::DirectOutputThread::threadLoop_mix()
4538{
Eric Laurent81784c32012-11-19 14:55:58 -08004539 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004540 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004541 // output audio to hardware
4542 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004543 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004544 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004545 status_t status = mActiveTrack->getNextBuffer(&buffer);
4546 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004547 memset(curBuf, 0, frameCount * mFrameSize);
4548 break;
4549 }
4550 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4551 frameCount -= buffer.frameCount;
4552 curBuf += buffer.frameCount * mFrameSize;
4553 mActiveTrack->releaseBuffer(&buffer);
4554 }
Andy Hung2098f272014-02-27 14:00:06 -08004555 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004556 sleepTime = 0;
4557 standbyTime = systemTime() + standbyDelay;
4558 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004559}
4560
4561void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4562{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004563 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004564 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004565 sleepTime = idleSleepTime;
4566 return;
4567 }
Eric Laurent81784c32012-11-19 14:55:58 -08004568 if (sleepTime == 0) {
4569 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4570 sleepTime = activeSleepTime;
4571 } else {
4572 sleepTime = idleSleepTime;
4573 }
4574 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004575 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004576 sleepTime = 0;
4577 }
4578}
4579
Eric Laurentd1f69b02014-12-15 14:33:13 -08004580void AudioFlinger::DirectOutputThread::threadLoop_exit()
4581{
4582 {
4583 Mutex::Autolock _l(mLock);
4584 bool flushPending = false;
4585 for (size_t i = 0; i < mTracks.size(); i++) {
4586 if (mTracks[i]->isFlushPending()) {
4587 mTracks[i]->flushAck();
4588 flushPending = true;
4589 }
4590 }
4591 if (flushPending) {
4592 flushHw_l();
4593 }
4594 }
4595 PlaybackThread::threadLoop_exit();
4596}
4597
4598// must be called with thread mutex locked
4599bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4600{
4601 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004602 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004603
4604 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4605 // after a timeout and we will enter standby then.
4606 if (mTracks.size() > 0) {
4607 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004608 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4609 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004610 }
4611
Eric Laurentb369caf2015-03-30 20:51:47 -07004612 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004613}
4614
Eric Laurent81784c32012-11-19 14:55:58 -08004615// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004616int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004617 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004618{
4619 return 0;
4620}
4621
4622// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004623void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004624{
4625}
4626
Eric Laurent10351942014-05-08 18:49:52 -07004627// checkForNewParameter_l() must be called with ThreadBase::mLock held
4628bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4629 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004630{
4631 bool reconfig = false;
4632
Eric Laurent10351942014-05-08 18:49:52 -07004633 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004634
Eric Laurent10351942014-05-08 18:49:52 -07004635 AudioParameter param = AudioParameter(keyValuePair);
4636 int value;
4637 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4638 // forward device change to effects that have requested to be
4639 // aware of attached audio device.
4640 if (value != AUDIO_DEVICE_NONE) {
4641 mOutDevice = value;
4642 for (size_t i = 0; i < mEffectChains.size(); i++) {
4643 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004644 }
4645 }
Eric Laurent81784c32012-11-19 14:55:58 -08004646 }
Eric Laurent10351942014-05-08 18:49:52 -07004647 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4648 // do not accept frame count changes if tracks are open as the track buffer
4649 // size depends on frame count and correct behavior would not be garantied
4650 // if frame count is changed after track creation
4651 if (!mTracks.isEmpty()) {
4652 status = INVALID_OPERATION;
4653 } else {
4654 reconfig = true;
4655 }
4656 }
4657 if (status == NO_ERROR) {
4658 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4659 keyValuePair.string());
4660 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004661 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004662 mStandby = true;
4663 mBytesWritten = 0;
4664 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4665 keyValuePair.string());
4666 }
4667 if (status == NO_ERROR && reconfig) {
4668 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07004669 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004670 }
4671 }
4672
Eric Laurent81784c32012-11-19 14:55:58 -08004673 return reconfig;
4674}
4675
4676uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4677{
4678 uint32_t time;
4679 if (audio_is_linear_pcm(mFormat)) {
4680 time = PlaybackThread::activeSleepTimeUs();
4681 } else {
4682 time = 10000;
4683 }
4684 return time;
4685}
4686
4687uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4688{
4689 uint32_t time;
4690 if (audio_is_linear_pcm(mFormat)) {
4691 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4692 } else {
4693 time = 10000;
4694 }
4695 return time;
4696}
4697
4698uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4699{
4700 uint32_t time;
4701 if (audio_is_linear_pcm(mFormat)) {
4702 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4703 } else {
4704 time = 10000;
4705 }
4706 return time;
4707}
4708
4709void AudioFlinger::DirectOutputThread::cacheParameters_l()
4710{
4711 PlaybackThread::cacheParameters_l();
4712
4713 // use shorter standby delay as on normal output to release
4714 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004715 // no delay on outputs with HW A/V sync
4716 if (usesHwAvSync()) {
4717 standbyDelay = 0;
4718 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004719 standbyDelay = microseconds(activeSleepTime*2);
4720 } else {
4721 standbyDelay = kOffloadStandbyDelayNs;
4722 }
Eric Laurent81784c32012-11-19 14:55:58 -08004723}
4724
Eric Laurente659ef42014-09-29 13:06:46 -07004725void AudioFlinger::DirectOutputThread::flushHw_l()
4726{
Phil Burk062e67a2015-02-11 13:40:50 -08004727 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004728 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004729}
4730
Eric Laurent81784c32012-11-19 14:55:58 -08004731// ----------------------------------------------------------------------------
4732
Eric Laurentbfb1b832013-01-07 09:53:42 -08004733AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004734 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004736 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004737 mWriteAckSequence(0),
4738 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004739{
4740}
4741
4742AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4743{
4744}
4745
4746void AudioFlinger::AsyncCallbackThread::onFirstRef()
4747{
4748 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4749}
4750
4751bool AudioFlinger::AsyncCallbackThread::threadLoop()
4752{
4753 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004754 uint32_t writeAckSequence;
4755 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004756
4757 {
4758 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004759 while (!((mWriteAckSequence & 1) ||
4760 (mDrainSequence & 1) ||
4761 exitPending())) {
4762 mWaitWorkCV.wait(mLock);
4763 }
4764
Eric Laurentbfb1b832013-01-07 09:53:42 -08004765 if (exitPending()) {
4766 break;
4767 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004768 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4769 mWriteAckSequence, mDrainSequence);
4770 writeAckSequence = mWriteAckSequence;
4771 mWriteAckSequence &= ~1;
4772 drainSequence = mDrainSequence;
4773 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004774 }
4775 {
Eric Laurent4de95592013-09-26 15:28:21 -07004776 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4777 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004778 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004779 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004780 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004781 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004782 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004783 }
4784 }
4785 }
4786 }
4787 return false;
4788}
4789
4790void AudioFlinger::AsyncCallbackThread::exit()
4791{
4792 ALOGV("AsyncCallbackThread::exit");
4793 Mutex::Autolock _l(mLock);
4794 requestExit();
4795 mWaitWorkCV.broadcast();
4796}
4797
Eric Laurent3b4529e2013-09-05 18:09:19 -07004798void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799{
4800 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004801 // bit 0 is cleared
4802 mWriteAckSequence = sequence << 1;
4803}
4804
4805void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4806{
4807 Mutex::Autolock _l(mLock);
4808 // ignore unexpected callbacks
4809 if (mWriteAckSequence & 2) {
4810 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004811 mWaitWorkCV.signal();
4812 }
4813}
4814
Eric Laurent3b4529e2013-09-05 18:09:19 -07004815void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004816{
4817 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004818 // bit 0 is cleared
4819 mDrainSequence = sequence << 1;
4820}
4821
4822void AudioFlinger::AsyncCallbackThread::resetDraining()
4823{
4824 Mutex::Autolock _l(mLock);
4825 // ignore unexpected callbacks
4826 if (mDrainSequence & 2) {
4827 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004828 mWaitWorkCV.signal();
4829 }
4830}
4831
4832
4833// ----------------------------------------------------------------------------
4834AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4835 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4836 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004837 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004838{
Eric Laurentfd477972013-10-25 18:10:40 -07004839 //FIXME: mStandby should be set to true by ThreadBase constructor
4840 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004841}
4842
Eric Laurentbfb1b832013-01-07 09:53:42 -08004843void AudioFlinger::OffloadThread::threadLoop_exit()
4844{
4845 if (mFlushPending || mHwPaused) {
4846 // If a flush is pending or track was paused, just discard buffered data
4847 flushHw_l();
4848 } else {
4849 mMixerStatus = MIXER_DRAIN_ALL;
4850 threadLoop_drain();
4851 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004852 if (mUseAsyncWrite) {
4853 ALOG_ASSERT(mCallbackThread != 0);
4854 mCallbackThread->exit();
4855 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004856 PlaybackThread::threadLoop_exit();
4857}
4858
4859AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4860 Vector< sp<Track> > *tracksToRemove
4861)
4862{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004863 size_t count = mActiveTracks.size();
4864
4865 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004866 bool doHwPause = false;
4867 bool doHwResume = false;
4868
Eric Laurentede6c3b2013-09-19 14:37:46 -07004869 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4870
Eric Laurentbfb1b832013-01-07 09:53:42 -08004871 // find out which tracks need to be processed
4872 for (size_t i = 0; i < count; i++) {
4873 sp<Track> t = mActiveTracks[i].promote();
4874 // The track died recently
4875 if (t == 0) {
4876 continue;
4877 }
4878 Track* const track = t.get();
4879 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004880 // Only consider last track started for volume and mixer state control.
4881 // In theory an older track could underrun and restart after the new one starts
4882 // but as we only care about the transition phase between two tracks on a
4883 // direct output, it is not a problem to ignore the underrun case.
4884 sp<Track> l = mLatestActiveTrack.promote();
4885 bool last = l.get() == track;
4886
Haynes Mathew George7844f672014-01-15 12:32:55 -08004887 if (track->isInvalid()) {
4888 ALOGW("An invalidated track shouldn't be in active list");
4889 tracksToRemove->add(track);
4890 continue;
4891 }
4892
4893 if (track->mState == TrackBase::IDLE) {
4894 ALOGW("An idle track shouldn't be in active list");
4895 continue;
4896 }
4897
Eric Laurentbfb1b832013-01-07 09:53:42 -08004898 if (track->isPausing()) {
4899 track->setPaused();
4900 if (last) {
4901 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004902 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004903 mHwPaused = true;
4904 }
4905 // If we were part way through writing the mixbuffer to
4906 // the HAL we must save this until we resume
4907 // BUG - this will be wrong if a different track is made active,
4908 // in that case we want to discard the pending data in the
4909 // mixbuffer and tell the client to present it again when the
4910 // track is resumed
4911 mPausedWriteLength = mCurrentWriteLength;
4912 mPausedBytesRemaining = mBytesRemaining;
4913 mBytesRemaining = 0; // stop writing
4914 }
4915 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004916 } else if (track->isFlushPending()) {
4917 track->flushAck();
4918 if (last) {
4919 mFlushPending = true;
4920 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004921 } else if (track->isResumePending()){
4922 track->resumeAck();
4923 if (last) {
4924 if (mPausedBytesRemaining) {
4925 // Need to continue write that was interrupted
4926 mCurrentWriteLength = mPausedWriteLength;
4927 mBytesRemaining = mPausedBytesRemaining;
4928 mPausedBytesRemaining = 0;
4929 }
4930 if (mHwPaused) {
4931 doHwResume = true;
4932 mHwPaused = false;
4933 // threadLoop_mix() will handle the case that we need to
4934 // resume an interrupted write
4935 }
4936 // enable write to audio HAL
4937 sleepTime = 0;
4938
4939 // Do not handle new data in this iteration even if track->framesReady()
4940 mixerStatus = MIXER_TRACKS_ENABLED;
4941 }
4942 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004943 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004944 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004945 if (track->mFillingUpStatus == Track::FS_FILLED) {
4946 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004947 // make sure processVolume_l() will apply new volume even if 0
4948 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004949 }
4950
4951 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004952 sp<Track> previousTrack = mPreviousTrack.promote();
4953 if (previousTrack != 0) {
4954 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004955 // Flush any data still being written from last track
4956 mBytesRemaining = 0;
4957 if (mPausedBytesRemaining) {
4958 // Last track was paused so we also need to flush saved
4959 // mixbuffer state and invalidate track so that it will
4960 // re-submit that unwritten data when it is next resumed
4961 mPausedBytesRemaining = 0;
4962 // Invalidate is a bit drastic - would be more efficient
4963 // to have a flag to tell client that some of the
4964 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004965 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004966 }
4967 // flush data already sent to the DSP if changing audio session as audio
4968 // comes from a different source. Also invalidate previous track to force a
4969 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004970 if (previousTrack->sessionId() != track->sessionId()) {
4971 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004972 }
4973 }
4974 }
4975 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004976 // reset retry count
4977 track->mRetryCount = kMaxTrackRetriesOffload;
4978 mActiveTrack = t;
4979 mixerStatus = MIXER_TRACKS_READY;
4980 }
4981 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004982 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004983 if (track->isStopping_1()) {
4984 // Hardware buffer can hold a large amount of audio so we must
4985 // wait for all current track's data to drain before we say
4986 // that the track is stopped.
4987 if (mBytesRemaining == 0) {
4988 // Only start draining when all data in mixbuffer
4989 // has been written
4990 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4991 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004992 // do not drain if no data was ever sent to HAL (mStandby == true)
4993 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004994 // do not modify drain sequence if we are already draining. This happens
4995 // when resuming from pause after drain.
4996 if ((mDrainSequence & 1) == 0) {
4997 sleepTime = 0;
4998 standbyTime = systemTime() + standbyDelay;
4999 mixerStatus = MIXER_DRAIN_TRACK;
5000 mDrainSequence += 2;
5001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005002 if (mHwPaused) {
5003 // It is possible to move from PAUSED to STOPPING_1 without
5004 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005005 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005006 mHwPaused = false;
5007 }
5008 }
5009 }
5010 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005011 // Drain has completed or we are in standby, signal presentation complete
5012 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005013 track->mState = TrackBase::STOPPED;
5014 size_t audioHALFrames =
5015 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
5016 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005017 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005018 track->presentationComplete(framesWritten, audioHALFrames);
5019 track->reset();
5020 tracksToRemove->add(track);
5021 }
5022 } else {
5023 // No buffers for this track. Give it a few chances to
5024 // fill a buffer, then remove it from active list.
5025 if (--(track->mRetryCount) <= 0) {
5026 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5027 track->name());
5028 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005029 // indicate to client process that the track was disabled because of underrun;
5030 // it will then automatically call start() when data is available
5031 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005032 } else if (last){
5033 mixerStatus = MIXER_TRACKS_ENABLED;
5034 }
5035 }
5036 }
5037 // compute volume for this track
5038 processVolume_l(track, last);
5039 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005040
Eric Laurentea0fade2013-10-04 16:23:48 -07005041 // make sure the pause/flush/resume sequence is executed in the right order.
5042 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5043 // before flush and then resume HW. This can happen in case of pause/flush/resume
5044 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005045 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005046 mOutput->stream->pause(mOutput->stream);
5047 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005048 if (mFlushPending) {
5049 flushHw_l();
5050 mFlushPending = false;
5051 }
Eric Laurentfd477972013-10-25 18:10:40 -07005052 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005053 mOutput->stream->resume(mOutput->stream);
5054 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005055
Eric Laurentbfb1b832013-01-07 09:53:42 -08005056 // remove all the tracks that need to be...
5057 removeTracks_l(*tracksToRemove);
5058
5059 return mixerStatus;
5060}
5061
Eric Laurentbfb1b832013-01-07 09:53:42 -08005062// must be called with thread mutex locked
5063bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5064{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005065 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5066 mWriteAckSequence, mDrainSequence);
5067 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068 return true;
5069 }
5070 return false;
5071}
5072
Eric Laurentbfb1b832013-01-07 09:53:42 -08005073bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5074{
5075 Mutex::Autolock _l(mLock);
5076 return waitingAsyncCallback_l();
5077}
5078
5079void AudioFlinger::OffloadThread::flushHw_l()
5080{
Eric Laurente659ef42014-09-29 13:06:46 -07005081 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005082 // Flush anything still waiting in the mixbuffer
5083 mCurrentWriteLength = 0;
5084 mBytesRemaining = 0;
5085 mPausedWriteLength = 0;
5086 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005087
Eric Laurentbfb1b832013-01-07 09:53:42 -08005088 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005089 // discard any pending drain or write ack by incrementing sequence
5090 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5091 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005092 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005093 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5094 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005095 }
5096}
5097
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005098void AudioFlinger::OffloadThread::onAddNewTrack_l()
5099{
5100 sp<Track> previousTrack = mPreviousTrack.promote();
5101 sp<Track> latestTrack = mLatestActiveTrack.promote();
5102
5103 if (previousTrack != 0 && latestTrack != 0 &&
5104 (previousTrack->sessionId() != latestTrack->sessionId())) {
5105 mFlushPending = true;
5106 }
5107 PlaybackThread::onAddNewTrack_l();
5108}
5109
Eric Laurentbfb1b832013-01-07 09:53:42 -08005110// ----------------------------------------------------------------------------
5111
Eric Laurent81784c32012-11-19 14:55:58 -08005112AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
5113 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
5114 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
5115 DUPLICATING),
5116 mWaitTimeMs(UINT_MAX)
5117{
5118 addOutputTrack(mainThread);
5119}
5120
5121AudioFlinger::DuplicatingThread::~DuplicatingThread()
5122{
5123 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5124 mOutputTracks[i]->destroy();
5125 }
5126}
5127
5128void AudioFlinger::DuplicatingThread::threadLoop_mix()
5129{
5130 // mix buffers...
5131 if (outputsReady(outputTracks)) {
5132 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5133 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005134 if (mMixerBufferValid) {
5135 memset(mMixerBuffer, 0, mMixerBufferSize);
5136 } else {
5137 memset(mSinkBuffer, 0, mSinkBufferSize);
5138 }
Eric Laurent81784c32012-11-19 14:55:58 -08005139 }
5140 sleepTime = 0;
5141 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005142 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005143 standbyTime = systemTime() + standbyDelay;
5144}
5145
5146void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5147{
5148 if (sleepTime == 0) {
5149 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5150 sleepTime = activeSleepTime;
5151 } else {
5152 sleepTime = idleSleepTime;
5153 }
5154 } else if (mBytesWritten != 0) {
5155 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5156 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005157 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005158 } else {
5159 // flush remaining overflow buffers in output tracks
5160 writeFrames = 0;
5161 }
5162 sleepTime = 0;
5163 }
5164}
5165
Eric Laurentbfb1b832013-01-07 09:53:42 -08005166ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005167{
5168 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005169 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005170 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005171 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005172 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005173}
5174
5175void AudioFlinger::DuplicatingThread::threadLoop_standby()
5176{
5177 // DuplicatingThread implements standby by stopping all tracks
5178 for (size_t i = 0; i < outputTracks.size(); i++) {
5179 outputTracks[i]->stop();
5180 }
5181}
5182
5183void AudioFlinger::DuplicatingThread::saveOutputTracks()
5184{
5185 outputTracks = mOutputTracks;
5186}
5187
5188void AudioFlinger::DuplicatingThread::clearOutputTracks()
5189{
5190 outputTracks.clear();
5191}
5192
5193void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5194{
5195 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005196 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5197 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5198 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5199 const size_t frameCount =
5200 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5201 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5202 // from different OutputTracks and their associated MixerThreads (e.g. one may
5203 // nearly empty and the other may be dropping data).
5204
5205 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005206 this,
5207 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005208 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005209 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005210 frameCount,
5211 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005212 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005213 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005214 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005215 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005216 updateWaitTime_l();
5217 }
5218}
5219
5220void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5221{
5222 Mutex::Autolock _l(mLock);
5223 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5224 if (mOutputTracks[i]->thread() == thread) {
5225 mOutputTracks[i]->destroy();
5226 mOutputTracks.removeAt(i);
5227 updateWaitTime_l();
5228 return;
5229 }
5230 }
5231 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5232}
5233
5234// caller must hold mLock
5235void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5236{
5237 mWaitTimeMs = UINT_MAX;
5238 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5239 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5240 if (strong != 0) {
5241 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5242 if (waitTimeMs < mWaitTimeMs) {
5243 mWaitTimeMs = waitTimeMs;
5244 }
5245 }
5246 }
5247}
5248
5249
5250bool AudioFlinger::DuplicatingThread::outputsReady(
5251 const SortedVector< sp<OutputTrack> > &outputTracks)
5252{
5253 for (size_t i = 0; i < outputTracks.size(); i++) {
5254 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5255 if (thread == 0) {
5256 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5257 outputTracks[i].get());
5258 return false;
5259 }
5260 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5261 // see note at standby() declaration
5262 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5263 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5264 thread.get());
5265 return false;
5266 }
5267 }
5268 return true;
5269}
5270
5271uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5272{
5273 return (mWaitTimeMs * 1000) / 2;
5274}
5275
5276void AudioFlinger::DuplicatingThread::cacheParameters_l()
5277{
5278 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5279 updateWaitTime_l();
5280
5281 MixerThread::cacheParameters_l();
5282}
5283
5284// ----------------------------------------------------------------------------
5285// Record
5286// ----------------------------------------------------------------------------
5287
5288AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5289 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005290 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005291 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005292 audio_devices_t inDevice
5293#ifdef TEE_SINK
5294 , const sp<NBAIO_Sink>& teeSink
5295#endif
5296 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005297 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005298 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005299 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005300 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005301#ifdef TEE_SINK
5302 , mTeeSink(teeSink)
5303#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005304 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5305 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005306 // mFastCapture below
5307 , mFastCaptureFutex(0)
5308 // mInputSource
5309 // mPipeSink
5310 // mPipeSource
5311 , mPipeFramesP2(0)
5312 // mPipeMemory
5313 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005314 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005315{
Glenn Kastend7dca052015-03-05 16:05:54 -08005316 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5317 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005318
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005319 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005320
5321 // create an NBAIO source for the HAL input stream, and negotiate
5322 mInputSource = new AudioStreamInSource(input->stream);
5323 size_t numCounterOffers = 0;
5324 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5325 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5326 ALOG_ASSERT(index == 0);
5327
5328 // initialize fast capture depending on configuration
5329 bool initFastCapture;
5330 switch (kUseFastCapture) {
5331 case FastCapture_Never:
5332 initFastCapture = false;
5333 break;
5334 case FastCapture_Always:
5335 initFastCapture = true;
5336 break;
5337 case FastCapture_Static:
5338 uint32_t primaryOutputSampleRate;
5339 {
5340 AutoMutex _l(audioFlinger->mHardwareLock);
5341 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5342 }
5343 initFastCapture =
5344 // either capture sample rate is same as (a reasonable) primary output sample rate
5345 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5346 (mSampleRate == primaryOutputSampleRate)) ||
5347 // or primary output sample rate is unknown, and capture sample rate is reasonable
5348 ((primaryOutputSampleRate == 0) &&
5349 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005350 // and the buffer size is < 12 ms
5351 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005352 break;
5353 // case FastCapture_Dynamic:
5354 }
5355
5356 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005357 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005358 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005359 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005360 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5361 void *pipeBuffer;
5362 const sp<MemoryDealer> roHeap(readOnlyHeap());
5363 sp<IMemory> pipeMemory;
5364 if ((roHeap == 0) ||
5365 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5366 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5367 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5368 goto failed;
5369 }
5370 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5371 memset(pipeBuffer, 0, pipeSize);
5372 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5373 const NBAIO_Format offers[1] = {format};
5374 size_t numCounterOffers = 0;
5375 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5376 ALOG_ASSERT(index == 0);
5377 mPipeSink = pipe;
5378 PipeReader *pipeReader = new PipeReader(*pipe);
5379 numCounterOffers = 0;
5380 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5381 ALOG_ASSERT(index == 0);
5382 mPipeSource = pipeReader;
5383 mPipeFramesP2 = pipeFramesP2;
5384 mPipeMemory = pipeMemory;
5385
5386 // create fast capture
5387 mFastCapture = new FastCapture();
5388 FastCaptureStateQueue *sq = mFastCapture->sq();
5389#ifdef STATE_QUEUE_DUMP
5390 // FIXME
5391#endif
5392 FastCaptureState *state = sq->begin();
5393 state->mCblk = NULL;
5394 state->mInputSource = mInputSource.get();
5395 state->mInputSourceGen++;
5396 state->mPipeSink = pipe;
5397 state->mPipeSinkGen++;
5398 state->mFrameCount = mFrameCount;
5399 state->mCommand = FastCaptureState::COLD_IDLE;
5400 // already done in constructor initialization list
5401 //mFastCaptureFutex = 0;
5402 state->mColdFutexAddr = &mFastCaptureFutex;
5403 state->mColdGen++;
5404 state->mDumpState = &mFastCaptureDumpState;
5405#ifdef TEE_SINK
5406 // FIXME
5407#endif
5408 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5409 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5410 sq->end();
5411 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5412
5413 // start the fast capture
5414 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5415 pid_t tid = mFastCapture->getTid();
5416 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5417 if (err != 0) {
5418 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5419 kPriorityFastCapture, getpid_cached, tid, err);
5420 }
5421
5422#ifdef AUDIO_WATCHDOG
5423 // FIXME
5424#endif
5425
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005426 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005427 }
5428failed: ;
5429
5430 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005431}
5432
Eric Laurent81784c32012-11-19 14:55:58 -08005433AudioFlinger::RecordThread::~RecordThread()
5434{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005435 if (mFastCapture != 0) {
5436 FastCaptureStateQueue *sq = mFastCapture->sq();
5437 FastCaptureState *state = sq->begin();
5438 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5439 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5440 if (old == -1) {
5441 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5442 }
5443 }
5444 state->mCommand = FastCaptureState::EXIT;
5445 sq->end();
5446 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5447 mFastCapture->join();
5448 mFastCapture.clear();
5449 }
5450 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005451 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005452 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005453}
5454
5455void AudioFlinger::RecordThread::onFirstRef()
5456{
Glenn Kastend7dca052015-03-05 16:05:54 -08005457 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005458}
5459
Eric Laurent81784c32012-11-19 14:55:58 -08005460bool AudioFlinger::RecordThread::threadLoop()
5461{
Eric Laurent81784c32012-11-19 14:55:58 -08005462 nsecs_t lastWarning = 0;
5463
5464 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005465
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005466reacquire_wakelock:
5467 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005468 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005469 {
5470 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005471 size_t size = mActiveTracks.size();
5472 activeTracksGen = mActiveTracksGen;
5473 if (size > 0) {
5474 // FIXME an arbitrary choice
5475 activeTrack = mActiveTracks[0];
5476 acquireWakeLock_l(activeTrack->uid());
5477 if (size > 1) {
5478 SortedVector<int> tmp;
5479 for (size_t i = 0; i < size; i++) {
5480 tmp.add(mActiveTracks[i]->uid());
5481 }
5482 updateWakeLockUids_l(tmp);
5483 }
5484 } else {
5485 acquireWakeLock_l(-1);
5486 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005487 }
5488
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005489 // used to request a deferred sleep, to be executed later while mutex is unlocked
5490 uint32_t sleepUs = 0;
5491
5492 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005493 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005494 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005495
Glenn Kasten5edadd42013-08-14 16:30:49 -07005496 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005497 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005498 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005499 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005500 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005501 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005502 }
5503
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005504 // activeTracks accumulates a copy of a subset of mActiveTracks
5505 Vector< sp<RecordTrack> > activeTracks;
5506
Glenn Kasten735f45f2014-08-18 15:51:59 -07005507 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005508 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005509
Glenn Kasten735f45f2014-08-18 15:51:59 -07005510 // reference to a fast track which is about to be removed
5511 sp<RecordTrack> fastTrackToRemove;
5512
Eric Laurent81784c32012-11-19 14:55:58 -08005513 { // scope for mLock
5514 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005515
Eric Laurent021cf962014-05-13 10:18:14 -07005516 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005517
Eric Laurent000a4192014-01-29 15:17:32 -08005518 // check exitPending here because checkForNewParameters_l() and
5519 // checkForNewParameters_l() can temporarily release mLock
5520 if (exitPending()) {
5521 break;
5522 }
5523
Glenn Kasten2b806402013-11-20 16:37:38 -08005524 // if no active track(s), then standby and release wakelock
5525 size_t size = mActiveTracks.size();
5526 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005527 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005528 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005529 releaseWakeLock_l();
5530 ALOGV("RecordThread: loop stopping");
5531 // go to sleep
5532 mWaitWorkCV.wait(mLock);
5533 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005534 goto reacquire_wakelock;
5535 }
5536
Glenn Kasten2b806402013-11-20 16:37:38 -08005537 if (mActiveTracksGen != activeTracksGen) {
5538 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005539 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005540 for (size_t i = 0; i < size; i++) {
5541 tmp.add(mActiveTracks[i]->uid());
5542 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005543 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005544 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005545
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005546 bool doBroadcast = false;
5547 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005548
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005549 activeTrack = mActiveTracks[i];
5550 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005551 if (activeTrack->isFastTrack()) {
5552 ALOG_ASSERT(fastTrackToRemove == 0);
5553 fastTrackToRemove = activeTrack;
5554 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005555 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005556 mActiveTracks.remove(activeTrack);
5557 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005558 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005559 continue;
5560 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005561
5562 TrackBase::track_state activeTrackState = activeTrack->mState;
5563 switch (activeTrackState) {
5564
5565 case TrackBase::PAUSING:
5566 mActiveTracks.remove(activeTrack);
5567 mActiveTracksGen++;
5568 doBroadcast = true;
5569 size--;
5570 continue;
5571
5572 case TrackBase::STARTING_1:
5573 sleepUs = 10000;
5574 i++;
5575 continue;
5576
5577 case TrackBase::STARTING_2:
5578 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005579 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005580 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005581 break;
5582
5583 case TrackBase::ACTIVE:
5584 break;
5585
5586 case TrackBase::IDLE:
5587 i++;
5588 continue;
5589
5590 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005591 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005592 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005593
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005594 activeTracks.add(activeTrack);
5595 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005596
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005597 if (activeTrack->isFastTrack()) {
5598 ALOG_ASSERT(!mFastTrackAvail);
5599 ALOG_ASSERT(fastTrack == 0);
5600 fastTrack = activeTrack;
5601 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005602 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005603 if (doBroadcast) {
5604 mStartStopCond.broadcast();
5605 }
5606
5607 // sleep if there are no active tracks to process
5608 if (activeTracks.size() == 0) {
5609 if (sleepUs == 0) {
5610 sleepUs = kRecordThreadSleepUs;
5611 }
5612 continue;
5613 }
5614 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005615
Eric Laurent81784c32012-11-19 14:55:58 -08005616 lockEffectChains_l(effectChains);
5617 }
5618
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005619 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005620
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005621 size_t size = effectChains.size();
5622 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005623 // thread mutex is not locked, but effect chain is locked
5624 effectChains[i]->process_l();
5625 }
5626
Glenn Kasten735f45f2014-08-18 15:51:59 -07005627 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005628 if (mFastCapture != 0) {
5629 FastCaptureStateQueue *sq = mFastCapture->sq();
5630 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005631 bool didModify = false;
5632 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005633 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5634 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5635 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5636 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5637 if (old == -1) {
5638 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5639 }
5640 }
5641 state->mCommand = FastCaptureState::READ_WRITE;
5642#if 0 // FIXME
5643 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005644 FastThreadDumpState::kSamplingNforLowRamDevice :
5645 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005646#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005647 didModify = true;
5648 }
5649 audio_track_cblk_t *cblkOld = state->mCblk;
5650 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5651 if (cblkNew != cblkOld) {
5652 state->mCblk = cblkNew;
5653 // block until acked if removing a fast track
5654 if (cblkOld != NULL) {
5655 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5656 }
5657 didModify = true;
5658 }
5659 sq->end(didModify);
5660 if (didModify) {
5661 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005662#if 0
5663 if (kUseFastCapture == FastCapture_Dynamic) {
5664 mNormalSource = mPipeSource;
5665 }
5666#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005667 }
5668 }
5669
Glenn Kasten735f45f2014-08-18 15:51:59 -07005670 // now run the fast track destructor with thread mutex unlocked
5671 fastTrackToRemove.clear();
5672
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005673 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5674 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5675 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5676 // If destination is non-contiguous, first read past the nominal end of buffer, then
5677 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005678
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005679 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005680 ssize_t framesRead;
5681
5682 // If an NBAIO source is present, use it to read the normal capture's data
5683 if (mPipeSource != 0) {
5684 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005685 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005686 framesToRead, AudioBufferProvider::kInvalidPTS);
5687 if (framesRead == 0) {
5688 // since pipe is non-blocking, simulate blocking input
5689 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5690 }
5691 // otherwise use the HAL / AudioStreamIn directly
5692 } else {
5693 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005694 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005695 if (bytesRead < 0) {
5696 framesRead = bytesRead;
5697 } else {
5698 framesRead = bytesRead / mFrameSize;
5699 }
5700 }
5701
5702 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5703 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005704 // Force input into standby so that it tries to recover at next read attempt
5705 inputStandBy();
5706 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005707 }
5708 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005709 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005710 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005711 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005712
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005713 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005714 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005715 }
5716 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005717 {
5718 size_t part1 = mRsmpInFramesP2 - rear;
5719 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005720 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005721 (framesRead - part1) * mFrameSize);
5722 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005723 }
5724 rear = mRsmpInRear += framesRead;
5725
5726 size = activeTracks.size();
5727 // loop over each active track
5728 for (size_t i = 0; i < size; i++) {
5729 activeTrack = activeTracks[i];
5730
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005731 // skip fast tracks, as those are handled directly by FastCapture
5732 if (activeTrack->isFastTrack()) {
5733 continue;
5734 }
5735
Andy Hung73c02e42015-03-29 01:13:58 -07005736 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005737 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5738
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005739 enum {
5740 OVERRUN_UNKNOWN,
5741 OVERRUN_TRUE,
5742 OVERRUN_FALSE
5743 } overrun = OVERRUN_UNKNOWN;
5744
5745 // loop over getNextBuffer to handle circular sink
5746 for (;;) {
5747
5748 activeTrack->mSink.frameCount = ~0;
5749 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5750 size_t framesOut = activeTrack->mSink.frameCount;
5751 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5752
Andy Hung73c02e42015-03-29 01:13:58 -07005753 // check available frames and handle overrun conditions
5754 // if the record track isn't draining fast enough.
5755 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005756 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005757 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5758 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005759 overrun = OVERRUN_TRUE;
5760 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005761 if (framesOut == 0 || framesIn == 0) {
5762 break;
5763 }
5764
Andy Hung6770c6f2015-04-07 13:43:36 -07005765 // Don't allow framesOut to be larger than what is possible with resampling
5766 // from framesIn.
5767 // This isn't strictly necessary but helps limit buffer resizing in
5768 // RecordBufferConverter. TODO: remove when no longer needed.
5769 framesOut = min(framesOut,
5770 destinationFramesPossible(
5771 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005772 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5773 framesOut = activeTrack->mRecordBufferConverter->convert(
5774 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005775
5776 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5777 overrun = OVERRUN_FALSE;
5778 }
5779
5780 if (activeTrack->mFramesToDrop == 0) {
5781 if (framesOut > 0) {
5782 activeTrack->mSink.frameCount = framesOut;
5783 activeTrack->releaseBuffer(&activeTrack->mSink);
5784 }
5785 } else {
5786 // FIXME could do a partial drop of framesOut
5787 if (activeTrack->mFramesToDrop > 0) {
5788 activeTrack->mFramesToDrop -= framesOut;
5789 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005790 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005791 }
5792 } else {
5793 activeTrack->mFramesToDrop += framesOut;
5794 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5795 activeTrack->mSyncStartEvent->isCancelled()) {
5796 ALOGW("Synced record %s, session %d, trigger session %d",
5797 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5798 activeTrack->sessionId(),
5799 (activeTrack->mSyncStartEvent != 0) ?
5800 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005801 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005802 }
5803 }
5804 }
5805
5806 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005807 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005808 }
5809 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005810
5811 switch (overrun) {
5812 case OVERRUN_TRUE:
5813 // client isn't retrieving buffers fast enough
5814 if (!activeTrack->setOverflow()) {
5815 nsecs_t now = systemTime();
5816 // FIXME should lastWarning per track?
5817 if ((now - lastWarning) > kWarningThrottleNs) {
5818 ALOGW("RecordThread: buffer overflow");
5819 lastWarning = now;
5820 }
5821 }
5822 break;
5823 case OVERRUN_FALSE:
5824 activeTrack->clearOverflow();
5825 break;
5826 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005827 break;
5828 }
5829
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005830 }
5831
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005832unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005833 // enable changes in effect chain
5834 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005835 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005836 }
5837
Glenn Kasten93e471f2013-08-19 08:40:07 -07005838 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005839
5840 {
5841 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005842 for (size_t i = 0; i < mTracks.size(); i++) {
5843 sp<RecordTrack> track = mTracks[i];
5844 track->invalidate();
5845 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005846 mActiveTracks.clear();
5847 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005848 mStartStopCond.broadcast();
5849 }
5850
5851 releaseWakeLock();
5852
5853 ALOGV("RecordThread %p exiting", this);
5854 return false;
5855}
5856
Glenn Kasten93e471f2013-08-19 08:40:07 -07005857void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005858{
5859 if (!mStandby) {
5860 inputStandBy();
5861 mStandby = true;
5862 }
5863}
5864
5865void AudioFlinger::RecordThread::inputStandBy()
5866{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005867 // Idle the fast capture if it's currently running
5868 if (mFastCapture != 0) {
5869 FastCaptureStateQueue *sq = mFastCapture->sq();
5870 FastCaptureState *state = sq->begin();
5871 if (!(state->mCommand & FastCaptureState::IDLE)) {
5872 state->mCommand = FastCaptureState::COLD_IDLE;
5873 state->mColdFutexAddr = &mFastCaptureFutex;
5874 state->mColdGen++;
5875 mFastCaptureFutex = 0;
5876 sq->end();
5877 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5878 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5879#if 0
5880 if (kUseFastCapture == FastCapture_Dynamic) {
5881 // FIXME
5882 }
5883#endif
5884#ifdef AUDIO_WATCHDOG
5885 // FIXME
5886#endif
5887 } else {
5888 sq->end(false /*didModify*/);
5889 }
5890 }
Eric Laurent81784c32012-11-19 14:55:58 -08005891 mInput->stream->common.standby(&mInput->stream->common);
5892}
5893
Glenn Kasten05997e22014-03-13 15:08:33 -07005894// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005895sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005896 const sp<AudioFlinger::Client>& client,
5897 uint32_t sampleRate,
5898 audio_format_t format,
5899 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005900 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005901 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005902 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005903 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005904 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005905 pid_t tid,
5906 status_t *status)
5907{
Glenn Kasten74935e42013-12-19 08:56:45 -08005908 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005909 sp<RecordTrack> track;
5910 status_t lStatus;
5911
Glenn Kasten90e58b12013-07-31 16:16:02 -07005912 // client expresses a preference for FAST, but we get the final say
5913 if (*flags & IAudioFlinger::TRACK_FAST) {
5914 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005915 // we formerly checked for a callback handler (non-0 tid),
5916 // but that is no longer required for TRANSFER_OBTAIN mode
5917 //
Glenn Kasten74105912014-07-03 12:28:53 -07005918 // frame count is not specified, or is exactly the pipe depth
5919 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005920 // PCM data
5921 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005922 // native format
5923 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005924 // native channel mask
5925 (channelMask == mChannelMask) &&
5926 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005927 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005928 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 hasFastCapture() &&
5930 // there are sufficient fast track slots available
5931 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005932 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005933 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005934 frameCount, mFrameCount);
5935 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005936 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5937 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005938 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005939 frameCount, mFrameCount, mPipeFramesP2,
5940 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5941 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005942 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005943 }
5944 }
5945
5946 // compute track buffer size in frames, and suggest the notification frame count
5947 if (*flags & IAudioFlinger::TRACK_FAST) {
5948 // fast track: frame count is exactly the pipe depth
5949 frameCount = mPipeFramesP2;
5950 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5951 *notificationFrames = mFrameCount;
5952 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005953 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5954 // or 20 ms if there is a fast capture
5955 // TODO This could be a roundupRatio inline, and const
5956 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5957 * sampleRate + mSampleRate - 1) / mSampleRate;
5958 // minimum number of notification periods is at least kMinNotifications,
5959 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5960 static const size_t kMinNotifications = 3;
5961 static const uint32_t kMinMs = 30;
5962 // TODO This could be a roundupRatio inline
5963 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5964 // TODO This could be a roundupRatio inline
5965 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5966 maxNotificationFrames;
5967 const size_t minFrameCount = maxNotificationFrames *
5968 max(kMinNotifications, minNotificationsByMs);
5969 frameCount = max(frameCount, minFrameCount);
5970 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5971 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005972 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005973 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005974 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005975
Glenn Kasten15e57982013-09-24 11:52:37 -07005976 lStatus = initCheck();
5977 if (lStatus != NO_ERROR) {
5978 ALOGE("createRecordTrack_l() audio driver not initialized");
5979 goto Exit;
5980 }
Eric Laurent81784c32012-11-19 14:55:58 -08005981
5982 { // scope for mLock
5983 Mutex::Autolock _l(mLock);
5984
5985 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005986 format, channelMask, frameCount, NULL, sessionId, uid,
5987 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005988
Glenn Kasten03003332013-08-06 15:40:54 -07005989 lStatus = track->initCheck();
5990 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005991 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005992 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005993 goto Exit;
5994 }
5995 mTracks.add(track);
5996
5997 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5998 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5999 mAudioFlinger->btNrecIsOff();
6000 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6001 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006002
6003 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6004 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6005 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6006 // so ask activity manager to do this on our behalf
6007 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6008 }
Eric Laurent81784c32012-11-19 14:55:58 -08006009 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006010
Eric Laurent81784c32012-11-19 14:55:58 -08006011 lStatus = NO_ERROR;
6012
6013Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006014 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006015 return track;
6016}
6017
6018status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6019 AudioSystem::sync_event_t event,
6020 int triggerSession)
6021{
6022 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6023 sp<ThreadBase> strongMe = this;
6024 status_t status = NO_ERROR;
6025
6026 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006027 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006028 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006029 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006030 triggerSession,
6031 recordTrack->sessionId(),
6032 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006033 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006034 // Sync event can be cancelled by the trigger session if the track is not in a
6035 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006036 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006037 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006038 } else {
6039 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006040 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006041 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006042 }
6043 }
6044
6045 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006046 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006047 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006048 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6049 if (recordTrack->mState == TrackBase::PAUSING) {
6050 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006051 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006052 } else {
6053 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006054 }
6055 return status;
6056 }
6057
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006058 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6059 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6060 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006061 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006062 mActiveTracks.add(recordTrack);
6063 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006064 status_t status = NO_ERROR;
6065 if (recordTrack->isExternalTrack()) {
6066 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006067 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006068 mLock.lock();
6069 // FIXME should verify that recordTrack is still in mActiveTracks
6070 if (status != NO_ERROR) {
6071 mActiveTracks.remove(recordTrack);
6072 mActiveTracksGen++;
6073 recordTrack->clearSyncStartEvent();
6074 ALOGV("RecordThread::start error %d", status);
6075 return status;
6076 }
Eric Laurent81784c32012-11-19 14:55:58 -08006077 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006078 // Catch up with current buffer indices if thread is already running.
6079 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6080 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6081 // see previously buffered data before it called start(), but with greater risk of overrun.
6082
Andy Hung73c02e42015-03-29 01:13:58 -07006083 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006084 // clear any converter state as new data will be discontinuous
6085 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006086 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006087 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006088 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006089 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006090 ALOGV("Record failed to start");
6091 status = BAD_VALUE;
6092 goto startError;
6093 }
Eric Laurent81784c32012-11-19 14:55:58 -08006094 return status;
6095 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006096
Eric Laurent81784c32012-11-19 14:55:58 -08006097startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006098 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006099 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006100 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006101 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006102 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006103 return status;
6104}
6105
Eric Laurent81784c32012-11-19 14:55:58 -08006106void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6107{
6108 sp<SyncEvent> strongEvent = event.promote();
6109
6110 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006111 sp<RefBase> ptr = strongEvent->cookie().promote();
6112 if (ptr != 0) {
6113 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6114 recordTrack->handleSyncStartEvent(strongEvent);
6115 }
Eric Laurent81784c32012-11-19 14:55:58 -08006116 }
6117}
6118
Glenn Kastena8356f62013-07-25 14:37:52 -07006119bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006120 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006121 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006122 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006123 return false;
6124 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006125 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006126 recordTrack->mState = TrackBase::PAUSING;
6127 // do not wait for mStartStopCond if exiting
6128 if (exitPending()) {
6129 return true;
6130 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006131 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006132 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006133 // if we have been restarted, recordTrack is in mActiveTracks here
6134 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006135 ALOGV("Record stopped OK");
6136 return true;
6137 }
6138 return false;
6139}
6140
Glenn Kasten0f11b512014-01-31 16:18:54 -08006141bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006142{
6143 return false;
6144}
6145
Glenn Kasten0f11b512014-01-31 16:18:54 -08006146status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006147{
6148#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6149 if (!isValidSyncEvent(event)) {
6150 return BAD_VALUE;
6151 }
6152
6153 int eventSession = event->triggerSession();
6154 status_t ret = NAME_NOT_FOUND;
6155
6156 Mutex::Autolock _l(mLock);
6157
6158 for (size_t i = 0; i < mTracks.size(); i++) {
6159 sp<RecordTrack> track = mTracks[i];
6160 if (eventSession == track->sessionId()) {
6161 (void) track->setSyncEvent(event);
6162 ret = NO_ERROR;
6163 }
6164 }
6165 return ret;
6166#else
6167 return BAD_VALUE;
6168#endif
6169}
6170
6171// destroyTrack_l() must be called with ThreadBase::mLock held
6172void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6173{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006174 track->terminate();
6175 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006176 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006177 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006178 removeTrack_l(track);
6179 }
6180}
6181
6182void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6183{
6184 mTracks.remove(track);
6185 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006186 if (track->isFastTrack()) {
6187 ALOG_ASSERT(!mFastTrackAvail);
6188 mFastTrackAvail = true;
6189 }
Eric Laurent81784c32012-11-19 14:55:58 -08006190}
6191
6192void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6193{
6194 dumpInternals(fd, args);
6195 dumpTracks(fd, args);
6196 dumpEffectChains(fd, args);
6197}
6198
6199void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6200{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006201 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006202
Glenn Kasten44182c22015-03-05 17:12:23 -08006203 dumpBase(fd, args);
6204
6205 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006206 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006207 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006208 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006209 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006210
6211 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6212 const FastCaptureDumpState copy(mFastCaptureDumpState);
6213 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006214}
6215
Glenn Kasten0f11b512014-01-31 16:18:54 -08006216void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006217{
6218 const size_t SIZE = 256;
6219 char buffer[SIZE];
6220 String8 result;
6221
Marco Nelissenb2208842014-02-07 14:00:50 -08006222 size_t numtracks = mTracks.size();
6223 size_t numactive = mActiveTracks.size();
6224 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006225 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006226 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006227 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006228 RecordTrack::appendDumpHeader(result);
6229 for (size_t i = 0; i < numtracks ; ++i) {
6230 sp<RecordTrack> track = mTracks[i];
6231 if (track != 0) {
6232 bool active = mActiveTracks.indexOf(track) >= 0;
6233 if (active) {
6234 numactiveseen++;
6235 }
6236 track->dump(buffer, SIZE, active);
6237 result.append(buffer);
6238 }
Eric Laurent81784c32012-11-19 14:55:58 -08006239 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006240 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006241 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006242 }
6243
Marco Nelissenb2208842014-02-07 14:00:50 -08006244 if (numactiveseen != numactive) {
6245 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6246 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006247 result.append(buffer);
6248 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006249 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006250 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006251 if (mTracks.indexOf(track) < 0) {
6252 track->dump(buffer, SIZE, true);
6253 result.append(buffer);
6254 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006255 }
Eric Laurent81784c32012-11-19 14:55:58 -08006256
6257 }
6258 write(fd, result.string(), result.size());
6259}
6260
Andy Hung73c02e42015-03-29 01:13:58 -07006261
6262void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6263{
6264 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6265 RecordThread *recordThread = (RecordThread *) threadBase.get();
6266 mRsmpInFront = recordThread->mRsmpInRear;
6267 mRsmpInUnrel = 0;
6268}
6269
6270void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6271 size_t *framesAvailable, bool *hasOverrun)
6272{
6273 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6274 RecordThread *recordThread = (RecordThread *) threadBase.get();
6275 const int32_t rear = recordThread->mRsmpInRear;
6276 const int32_t front = mRsmpInFront;
6277 const ssize_t filled = rear - front;
6278
6279 size_t framesIn;
6280 bool overrun = false;
6281 if (filled < 0) {
6282 // should not happen, but treat like a massive overrun and re-sync
6283 framesIn = 0;
6284 mRsmpInFront = rear;
6285 overrun = true;
6286 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6287 framesIn = (size_t) filled;
6288 } else {
6289 // client is not keeping up with server, but give it latest data
6290 framesIn = recordThread->mRsmpInFrames;
6291 mRsmpInFront = /* front = */ rear - framesIn;
6292 overrun = true;
6293 }
6294 if (framesAvailable != NULL) {
6295 *framesAvailable = framesIn;
6296 }
6297 if (hasOverrun != NULL) {
6298 *hasOverrun = overrun;
6299 }
6300}
6301
Eric Laurent81784c32012-11-19 14:55:58 -08006302// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6304 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006305{
Andy Hung73c02e42015-03-29 01:13:58 -07006306 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 if (threadBase == 0) {
6308 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006309 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006310 return NOT_ENOUGH_DATA;
6311 }
6312 RecordThread *recordThread = (RecordThread *) threadBase.get();
6313 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006314 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006315 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006316 // FIXME should not be P2 (don't want to increase latency)
6317 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006318 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006319 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006320 front &= recordThread->mRsmpInFramesP2 - 1;
6321 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006322 if (part1 > (size_t) filled) {
6323 part1 = filled;
6324 }
6325 size_t ask = buffer->frameCount;
6326 ALOG_ASSERT(ask > 0);
6327 if (part1 > ask) {
6328 part1 = ask;
6329 }
6330 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006331 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006332 buffer->raw = NULL;
6333 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006334 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006335 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006336 }
6337
Andy Hung57446612015-04-19 23:56:46 -07006338 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006339 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006340 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006341 return NO_ERROR;
6342}
6343
6344// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006345void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6346 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006347{
Glenn Kasten85948432013-08-19 12:09:05 -07006348 size_t stepCount = buffer->frameCount;
6349 if (stepCount == 0) {
6350 return;
6351 }
Andy Hung73c02e42015-03-29 01:13:58 -07006352 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6353 mRsmpInUnrel -= stepCount;
6354 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006355 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006356 buffer->frameCount = 0;
6357}
6358
Andy Hung97a893e2015-03-29 01:03:07 -07006359AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6360 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6361 uint32_t srcSampleRate,
6362 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6363 uint32_t dstSampleRate) :
6364 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6365 // mSrcFormat
6366 // mSrcSampleRate
6367 // mDstChannelMask
6368 // mDstFormat
6369 // mDstSampleRate
6370 // mSrcChannelCount
6371 // mDstChannelCount
6372 // mDstFrameSize
6373 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006374 mResampler(NULL),
6375 mIsLegacyDownmix(false),
6376 mIsLegacyUpmix(false),
6377 mRequiresFloat(false),
6378 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006379{
6380 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6381 dstChannelMask, dstFormat, dstSampleRate);
6382}
6383
6384AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6385 free(mBuf);
6386 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006387 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006388}
6389
6390size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6391 AudioBufferProvider *provider, size_t frames)
6392{
Andy Hungd330ee42015-04-20 13:23:41 -07006393 if (mInputConverterProvider != NULL) {
6394 mInputConverterProvider->setBufferProvider(provider);
6395 provider = mInputConverterProvider;
6396 }
6397
6398 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006399 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6400 mSrcSampleRate, mSrcFormat, mDstFormat);
6401
6402 AudioBufferProvider::Buffer buffer;
6403 for (size_t i = frames; i > 0; ) {
6404 buffer.frameCount = i;
6405 status_t status = provider->getNextBuffer(&buffer, 0);
6406 if (status != OK || buffer.frameCount == 0) {
6407 frames -= i; // cannot fill request.
6408 break;
6409 }
Andy Hungd330ee42015-04-20 13:23:41 -07006410 // format convert to destination buffer
6411 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006412
6413 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6414 i -= buffer.frameCount;
6415 provider->releaseBuffer(&buffer);
6416 }
6417 } else {
6418 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6419 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6420
Andy Hungd330ee42015-04-20 13:23:41 -07006421 // reallocate buffer if needed
6422 if (mBufFrameSize != 0 && mBufFrames < frames) {
6423 free(mBuf);
6424 mBufFrames = frames;
6425 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6426 }
Andy Hung97a893e2015-03-29 01:03:07 -07006427 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006428 memset(mBuf, 0, frames * mBufFrameSize);
6429 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6430 // format convert to destination buffer
6431 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006432 }
6433 return frames;
6434}
6435
6436status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6437 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6438 uint32_t srcSampleRate,
6439 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6440 uint32_t dstSampleRate)
6441{
6442 // quick evaluation if there is any change.
6443 if (mSrcFormat == srcFormat
6444 && mSrcChannelMask == srcChannelMask
6445 && mSrcSampleRate == srcSampleRate
6446 && mDstFormat == dstFormat
6447 && mDstChannelMask == dstChannelMask
6448 && mDstSampleRate == dstSampleRate) {
6449 return NO_ERROR;
6450 }
6451
6452 const bool valid =
6453 audio_is_input_channel(srcChannelMask)
6454 && audio_is_input_channel(dstChannelMask)
6455 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6456 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6457 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6458 ; // no upsampling checks for now
6459 if (!valid) {
6460 return BAD_VALUE;
6461 }
6462
6463 mSrcFormat = srcFormat;
6464 mSrcChannelMask = srcChannelMask;
6465 mSrcSampleRate = srcSampleRate;
6466 mDstFormat = dstFormat;
6467 mDstChannelMask = dstChannelMask;
6468 mDstSampleRate = dstSampleRate;
6469
6470 // compute derived parameters
6471 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6472 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6473 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6474
Andy Hungd330ee42015-04-20 13:23:41 -07006475 // do we need to resample?
6476 delete mResampler;
6477 mResampler = NULL;
6478 if (mSrcSampleRate != mDstSampleRate) {
6479 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6480 mSrcChannelCount, mDstSampleRate);
6481 mResampler->setSampleRate(mSrcSampleRate);
6482 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6483 }
6484
6485 // are we running legacy channel conversion modes?
6486 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6487 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6488 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6489 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6490 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6491 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6492
6493 // do we need to process in float?
6494 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6495
6496 // do we need a staging buffer to convert for destination (we can still optimize this)?
6497 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6498 if (mResampler != NULL) {
6499 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6500 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6501 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6502 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6503 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006504 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6505 } else {
6506 mBufFrameSize = 0;
6507 }
6508 mBufFrames = 0; // force the buffer to be resized.
6509
Andy Hungd330ee42015-04-20 13:23:41 -07006510 // do we need an input converter buffer provider to give us float?
6511 delete mInputConverterProvider;
6512 mInputConverterProvider = NULL;
6513 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6514 mInputConverterProvider = new ReformatBufferProvider(
6515 audio_channel_count_from_in_mask(mSrcChannelMask),
6516 mSrcFormat,
6517 AUDIO_FORMAT_PCM_FLOAT,
6518 256 /* provider buffer frame count */);
6519 }
6520
6521 // do we need a remixer to do channel mask conversion
6522 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6523 (void) memcpy_by_index_array_initialization_from_channel_mask(
6524 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006525 }
6526 return NO_ERROR;
6527}
6528
Andy Hungd330ee42015-04-20 13:23:41 -07006529void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6530 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006531{
Andy Hungd330ee42015-04-20 13:23:41 -07006532 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006533 if (mBufFrameSize != 0 && mBufFrames < frames) {
6534 free(mBuf);
6535 mBufFrames = frames;
6536 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6537 }
Andy Hungd330ee42015-04-20 13:23:41 -07006538 // do we need to do legacy upmix and downmix?
6539 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006540 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006541 if (mIsLegacyUpmix) {
6542 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6543 (const float *)src, frames);
6544 } else /*mIsLegacyDownmix */ {
6545 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6546 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006547 }
Andy Hungd330ee42015-04-20 13:23:41 -07006548 if (mBuf != NULL) {
6549 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6550 frames * mDstChannelCount);
6551 }
6552 return;
6553 }
6554 // do we need to do channel mask conversion?
6555 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006556 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006557 memcpy_by_index_array(dstBuf, mDstChannelCount,
6558 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6559 if (dstBuf == dst) {
6560 return; // format is the same
6561 }
6562 }
6563 // convert to destination buffer
6564 const void *convertBuf = mBuf != NULL ? mBuf : src;
6565 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6566 frames * mDstChannelCount);
6567}
6568
6569void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6570 void *dst, /*not-a-const*/ void *src, size_t frames)
6571{
6572 // src buffer format is ALWAYS float when entering this routine
6573 if (mIsLegacyUpmix) {
6574 ; // mono to stereo already handled by resampler
6575 } else if (mIsLegacyDownmix
6576 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6577 // the resampler outputs stereo for mono input channel (a feature?)
6578 // must convert to mono
6579 downmix_to_mono_float_from_stereo_float((float *)src,
6580 (const float *)src, frames);
6581 } else if (mSrcChannelMask != mDstChannelMask) {
6582 // convert to mono channel again for channel mask conversion (could be skipped
6583 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006584 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006585 downmix_to_mono_float_from_stereo_float((float *)src,
6586 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006587 }
Andy Hungd330ee42015-04-20 13:23:41 -07006588 // convert to destination format (in place, OK as float is larger than other types)
6589 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6590 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6591 frames * mSrcChannelCount);
6592 }
6593 // channel convert and save to dst
6594 memcpy_by_index_array(dst, mDstChannelCount,
6595 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6596 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006597 }
Andy Hungd330ee42015-04-20 13:23:41 -07006598 // convert to destination format and save to dst
6599 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6600 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006601}
6602
Eric Laurent10351942014-05-08 18:49:52 -07006603bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6604 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006605{
6606 bool reconfig = false;
6607
Eric Laurent10351942014-05-08 18:49:52 -07006608 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006609
Eric Laurent10351942014-05-08 18:49:52 -07006610 audio_format_t reqFormat = mFormat;
6611 uint32_t samplingRate = mSampleRate;
6612 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006613 // possible that we are > 2 channels, use channel index mask
6614 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6615 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6616 }
Eric Laurent10351942014-05-08 18:49:52 -07006617
6618 AudioParameter param = AudioParameter(keyValuePair);
6619 int value;
6620 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6621 // channel count change can be requested. Do we mandate the first client defines the
6622 // HAL sampling rate and channel count or do we allow changes on the fly?
6623 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6624 samplingRate = value;
6625 reconfig = true;
6626 }
6627 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006628 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006629 status = BAD_VALUE;
6630 } else {
6631 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006632 reconfig = true;
6633 }
Eric Laurent10351942014-05-08 18:49:52 -07006634 }
6635 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6636 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006637 if (!audio_is_input_channel(mask) ||
6638 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006639 status = BAD_VALUE;
6640 } else {
6641 channelMask = mask;
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::keyFrameCount), value) == NO_ERROR) {
6646 // do not accept frame count changes if tracks are open as the track buffer
6647 // size depends on frame count and correct behavior would not be guaranteed
6648 // if frame count is changed after track creation
6649 if (mActiveTracks.size() > 0) {
6650 status = INVALID_OPERATION;
6651 } else {
6652 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006653 }
Eric Laurent10351942014-05-08 18:49:52 -07006654 }
6655 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6656 // forward device change to effects that have requested to be
6657 // aware of attached audio device.
6658 for (size_t i = 0; i < mEffectChains.size(); i++) {
6659 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006660 }
Eric Laurent81784c32012-11-19 14:55:58 -08006661
Eric Laurent10351942014-05-08 18:49:52 -07006662 // store input device and output device but do not forward output device to audio HAL.
6663 // Note that status is ignored by the caller for output device
6664 // (see AudioFlinger::setParameters()
6665 if (audio_is_output_devices(value)) {
6666 mOutDevice = value;
6667 status = BAD_VALUE;
6668 } else {
6669 mInDevice = value;
6670 // disable AEC and NS if the device is a BT SCO headset supporting those
6671 // pre processings
6672 if (mTracks.size() > 0) {
6673 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6674 mAudioFlinger->btNrecIsOff();
6675 for (size_t i = 0; i < mTracks.size(); i++) {
6676 sp<RecordTrack> track = mTracks[i];
6677 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6678 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006679 }
6680 }
6681 }
Eric Laurent10351942014-05-08 18:49:52 -07006682 }
6683 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6684 mAudioSource != (audio_source_t)value) {
6685 // forward device change to effects that have requested to be
6686 // aware of attached audio device.
6687 for (size_t i = 0; i < mEffectChains.size(); i++) {
6688 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006689 }
Eric Laurent10351942014-05-08 18:49:52 -07006690 mAudioSource = (audio_source_t)value;
6691 }
Glenn Kastene198c362013-08-13 09:13:36 -07006692
Eric Laurent10351942014-05-08 18:49:52 -07006693 if (status == NO_ERROR) {
6694 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6695 keyValuePair.string());
6696 if (status == INVALID_OPERATION) {
6697 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006698 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6699 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006700 }
6701 if (reconfig) {
6702 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006703 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6704 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006705 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006706 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006707 audio_channel_count_from_in_mask(
6708 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006709 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6710 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6711 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006712 }
Eric Laurent10351942014-05-08 18:49:52 -07006713 if (status == NO_ERROR) {
6714 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006715 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006716 }
6717 }
Eric Laurent81784c32012-11-19 14:55:58 -08006718 }
Eric Laurent10351942014-05-08 18:49:52 -07006719
Eric Laurent81784c32012-11-19 14:55:58 -08006720 return reconfig;
6721}
6722
6723String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6724{
Eric Laurent81784c32012-11-19 14:55:58 -08006725 Mutex::Autolock _l(mLock);
6726 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006727 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006728 }
6729
Glenn Kastend8ea6992013-07-16 14:17:15 -07006730 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6731 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006732 free(s);
6733 return out_s8;
6734}
6735
Eric Laurent73e26b62015-04-27 16:55:58 -07006736void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event) {
6737 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
6738
6739 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08006740
6741 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07006742 case AUDIO_INPUT_OPENED:
6743 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07006744 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07006745 desc->mChannelMask = mChannelMask;
6746 desc->mSamplingRate = mSampleRate;
6747 desc->mFormat = mFormat;
6748 desc->mFrameCount = mFrameCount;
6749 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006750 break;
6751
Eric Laurent73e26b62015-04-27 16:55:58 -07006752 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08006753 default:
6754 break;
6755 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006756 mAudioFlinger->ioConfigChanged(event, desc);
Eric Laurent81784c32012-11-19 14:55:58 -08006757}
6758
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006759void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006760{
Eric Laurent81784c32012-11-19 14:55:58 -08006761 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6762 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006763 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006764 if (mChannelCount > FCC_8) {
6765 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6766 }
Andy Hung463be252014-07-10 16:56:07 -07006767 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6768 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006769 if (!audio_is_linear_pcm(mFormat)) {
6770 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006771 }
Eric Laurent665470b2014-07-03 16:37:08 -07006772 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006773 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6774 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006775 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006776 // 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 -07006777 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006778 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006779 // A larger value should allow more old data to be read after a track calls start(),
6780 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006781 //
6782 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006783 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006784 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006785 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006786
6787 // TODO optimize audio capture buffer sizes ...
6788 // Here we calculate the size of the sliding buffer used as a source
6789 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6790 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6791 // be better to have it derived from the pipe depth in the long term.
6792 // The current value is higher than necessary. However it should not add to latency.
6793
Glenn Kasten85948432013-08-19 12:09:05 -07006794 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006795 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006796
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006797 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6798 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006799}
6800
Glenn Kasten5f972c02014-01-13 09:59:31 -08006801uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006802{
6803 Mutex::Autolock _l(mLock);
6804 if (initCheck() != NO_ERROR) {
6805 return 0;
6806 }
6807
6808 return mInput->stream->get_input_frames_lost(mInput->stream);
6809}
6810
6811uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6812{
6813 Mutex::Autolock _l(mLock);
6814 uint32_t result = 0;
6815 if (getEffectChain_l(sessionId) != 0) {
6816 result = EFFECT_SESSION;
6817 }
6818
6819 for (size_t i = 0; i < mTracks.size(); ++i) {
6820 if (sessionId == mTracks[i]->sessionId()) {
6821 result |= TRACK_SESSION;
6822 break;
6823 }
6824 }
6825
6826 return result;
6827}
6828
6829KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6830{
6831 KeyedVector<int, bool> ids;
6832 Mutex::Autolock _l(mLock);
6833 for (size_t j = 0; j < mTracks.size(); ++j) {
6834 sp<RecordThread::RecordTrack> track = mTracks[j];
6835 int sessionId = track->sessionId();
6836 if (ids.indexOfKey(sessionId) < 0) {
6837 ids.add(sessionId, true);
6838 }
6839 }
6840 return ids;
6841}
6842
6843AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6844{
6845 Mutex::Autolock _l(mLock);
6846 AudioStreamIn *input = mInput;
6847 mInput = NULL;
6848 return input;
6849}
6850
6851// this method must always be called either with ThreadBase mLock held or inside the thread loop
6852audio_stream_t* AudioFlinger::RecordThread::stream() const
6853{
6854 if (mInput == NULL) {
6855 return NULL;
6856 }
6857 return &mInput->stream->common;
6858}
6859
6860status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6861{
6862 // only one chain per input thread
6863 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006864 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006865 return INVALID_OPERATION;
6866 }
6867 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006868 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006869 chain->setInBuffer(NULL);
6870 chain->setOutBuffer(NULL);
6871
6872 checkSuspendOnAddEffectChain_l(chain);
6873
Eric Laurent1b928682014-10-02 19:41:47 -07006874 // make sure enabled pre processing effects state is communicated to the HAL as we
6875 // just moved them to a new input stream.
6876 chain->syncHalEffectsState();
6877
Eric Laurent81784c32012-11-19 14:55:58 -08006878 mEffectChains.add(chain);
6879
6880 return NO_ERROR;
6881}
6882
6883size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6884{
6885 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6886 ALOGW_IF(mEffectChains.size() != 1,
6887 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6888 chain.get(), mEffectChains.size(), this);
6889 if (mEffectChains.size() == 1) {
6890 mEffectChains.removeAt(0);
6891 }
6892 return 0;
6893}
6894
Eric Laurent1c333e22014-05-20 10:48:17 -07006895status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6896 audio_patch_handle_t *handle)
6897{
6898 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006899
6900 // store new device and send to effects
6901 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07006902 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07006903 for (size_t i = 0; i < mEffectChains.size(); i++) {
6904 mEffectChains[i]->setDevice_l(mInDevice);
6905 }
6906
6907 // disable AEC and NS if the device is a BT SCO headset supporting those
6908 // pre processings
6909 if (mTracks.size() > 0) {
6910 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6911 mAudioFlinger->btNrecIsOff();
6912 for (size_t i = 0; i < mTracks.size(); i++) {
6913 sp<RecordTrack> track = mTracks[i];
6914 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6915 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6916 }
6917 }
6918
6919 // store new source and send to effects
6920 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6921 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07006922 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07006923 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07006924 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006925 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006926
Eric Laurent054d9d32015-04-24 08:48:48 -07006927 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006928 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6929 status = hwDevice->create_audio_patch(hwDevice,
6930 patch->num_sources,
6931 patch->sources,
6932 patch->num_sinks,
6933 patch->sinks,
6934 handle);
6935 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006936 char *address;
6937 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
6938 address = audio_device_address_to_parameter(
6939 patch->sources[0].ext.device.type,
6940 patch->sources[0].ext.device.address);
6941 } else {
6942 address = (char *)calloc(1, 1);
6943 }
6944 AudioParameter param = AudioParameter(String8(address));
6945 free(address);
6946 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
6947 (int)patch->sources[0].ext.device.type);
6948 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
6949 (int)patch->sinks[0].ext.mix.usecase.source);
6950 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6951 param.toString().string());
6952 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07006953 }
Eric Laurent054d9d32015-04-24 08:48:48 -07006954
Eric Laurent296fb132015-05-01 11:38:42 -07006955 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
6956
Eric Laurent1c333e22014-05-20 10:48:17 -07006957 return status;
6958}
6959
6960status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6961{
6962 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07006963
6964 mInDevice = AUDIO_DEVICE_NONE;
6965
Eric Laurent1c333e22014-05-20 10:48:17 -07006966 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6967 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6968 status = hwDevice->release_audio_patch(hwDevice, handle);
6969 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07006970 AudioParameter param;
6971 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
6972 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6973 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07006974 }
6975 return status;
6976}
6977
Eric Laurent83b88082014-06-20 18:31:16 -07006978void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6979{
6980 Mutex::Autolock _l(mLock);
6981 mTracks.add(record);
6982}
6983
6984void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6985{
6986 Mutex::Autolock _l(mLock);
6987 destroyTrack_l(record);
6988}
6989
6990void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6991{
6992 ThreadBase::getAudioPortConfig(config);
6993 config->role = AUDIO_PORT_ROLE_SINK;
6994 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6995 config->ext.mix.usecase.source = mAudioSource;
6996}
Eric Laurent1c333e22014-05-20 10:48:17 -07006997
Glenn Kasten63238ef2015-03-02 15:50:29 -08006998} // namespace android