blob: ef889aad1c6db4fc0463da2047170d85e2f01c0d [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
59#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
62#include "SchedulingPolicyService.h"
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Glenn Kasten49d00ad2014-07-21 11:22:03 -070089#define max(a, b) ((a) > (b) ? (a) : (b))
90
Eric Laurent81784c32012-11-19 14:55:58 -080091namespace android {
92
93// retry counts for buffer fill timeout
94// 50 * ~20msecs = 1 second
95static const int8_t kMaxTrackRetries = 50;
96static const int8_t kMaxTrackStartupRetries = 50;
97// allow less retry attempts on direct output thread.
98// direct outputs can be a scarce resource in audio hardware and should
99// be released as quickly as possible.
100static const int8_t kMaxTrackRetriesDirect = 2;
101
102// don't warn about blocked writes or record buffer overflows more often than this
103static const nsecs_t kWarningThrottleNs = seconds(5);
104
105// RecordThread loop sleep time upon application overrun or audio HAL read error
106static const int kRecordThreadSleepUs = 5000;
107
Eric Laurent10351942014-05-08 18:49:52 -0700108// maximum time to wait in sendConfigEvent_l() for a status to be received
109static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800110
111// minimum sleep time for the mixer thread loop when tracks are active but in underrun
112static const uint32_t kMinThreadSleepTimeUs = 5000;
113// maximum divider applied to the active sleep time in the mixer thread loop
114static const uint32_t kMaxThreadSleepTimeShift = 2;
115
Andy Hung09a50072014-02-27 14:30:47 -0800116// minimum normal sink buffer size, expressed in milliseconds rather than frames
117static const uint32_t kMinNormalSinkBufferSizeMs = 20;
118// maximum normal sink buffer size
119static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800120
Eric Laurent972a1732013-09-04 09:42:59 -0700121// Offloaded output thread standby delay: allows track transition without going to standby
122static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// Whether to use fast mixer
125static const enum {
126 FastMixer_Never, // never initialize or use: for debugging only
127 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
128 // normal mixer multiplier is 1
129 FastMixer_Static, // initialize if needed, then use all the time if initialized,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 // FIXME for FastMixer_Dynamic:
134 // Supporting this option will require fixing HALs that can't handle large writes.
135 // For example, one HAL implementation returns an error from a large write,
136 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
137 // We could either fix the HAL implementations, or provide a wrapper that breaks
138 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
139} kUseFastMixer = FastMixer_Static;
140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700141// Whether to use fast capture
142static const enum {
143 FastCapture_Never, // never initialize or use: for debugging only
144 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
145 FastCapture_Static, // initialize if needed, then use all the time if initialized
146} kUseFastCapture = FastCapture_Static;
147
Eric Laurent81784c32012-11-19 14:55:58 -0800148// Priorities for requestPriority
149static const int kPriorityAudioApp = 2;
150static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700151static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
154// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800155// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
156// So for now we just assume that client is double-buffered for fast tracks.
157// FIXME It would be better for client to tell AudioFlinger the value of N,
158// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800159// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700160
161// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800162static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasten03490092014-05-27 12:30:54 -0700164// The minimum and maximum allowed values
165static const int kFastTrackMultiplierMin = 1;
166static const int kFastTrackMultiplierMax = 2;
167
168// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
169static int sFastTrackMultiplier = kFastTrackMultiplier;
170
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700171// See Thread::readOnlyHeap().
172// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
173// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
174// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700175static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// ----------------------------------------------------------------------------
178
Glenn Kasten03490092014-05-27 12:30:54 -0700179static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
180
181static void sFastTrackMultiplierInit()
182{
183 char value[PROPERTY_VALUE_MAX];
184 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
185 char *endptr;
186 unsigned long ul = strtoul(value, &endptr, 0);
187 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
188 sFastTrackMultiplier = (int) ul;
189 }
190 }
191}
192
193// ----------------------------------------------------------------------------
194
Eric Laurent81784c32012-11-19 14:55:58 -0800195#ifdef ADD_BATTERY_DATA
196// To collect the amplifier usage
197static void addBatteryData(uint32_t params) {
198 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
199 if (service == NULL) {
200 // it already logged
201 return;
202 }
203
204 service->addBatteryData(params);
205}
206#endif
207
208
209// ----------------------------------------------------------------------------
210// CPU Stats
211// ----------------------------------------------------------------------------
212
213class CpuStats {
214public:
215 CpuStats();
216 void sample(const String8 &title);
217#ifdef DEBUG_CPU_USAGE
218private:
219 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
220 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
221
222 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
223
224 int mCpuNum; // thread's current CPU number
225 int mCpukHz; // frequency of thread's current CPU in kHz
226#endif
227};
228
229CpuStats::CpuStats()
230#ifdef DEBUG_CPU_USAGE
231 : mCpuNum(-1), mCpukHz(-1)
232#endif
233{
234}
235
Glenn Kasten0f11b512014-01-31 16:18:54 -0800236void CpuStats::sample(const String8 &title
237#ifndef DEBUG_CPU_USAGE
238 __unused
239#endif
240 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800241#ifdef DEBUG_CPU_USAGE
242 // get current thread's delta CPU time in wall clock ns
243 double wcNs;
244 bool valid = mCpuUsage.sampleAndEnable(wcNs);
245
246 // record sample for wall clock statistics
247 if (valid) {
248 mWcStats.sample(wcNs);
249 }
250
251 // get the current CPU number
252 int cpuNum = sched_getcpu();
253
254 // get the current CPU frequency in kHz
255 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
256
257 // check if either CPU number or frequency changed
258 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
259 mCpuNum = cpuNum;
260 mCpukHz = cpukHz;
261 // ignore sample for purposes of cycles
262 valid = false;
263 }
264
265 // if no change in CPU number or frequency, then record sample for cycle statistics
266 if (valid && mCpukHz > 0) {
267 double cycles = wcNs * cpukHz * 0.000001;
268 mHzStats.sample(cycles);
269 }
270
271 unsigned n = mWcStats.n();
272 // mCpuUsage.elapsed() is expensive, so don't call it every loop
273 if ((n & 127) == 1) {
274 long long elapsed = mCpuUsage.elapsed();
275 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
276 double perLoop = elapsed / (double) n;
277 double perLoop100 = perLoop * 0.01;
278 double perLoop1k = perLoop * 0.001;
279 double mean = mWcStats.mean();
280 double stddev = mWcStats.stddev();
281 double minimum = mWcStats.minimum();
282 double maximum = mWcStats.maximum();
283 double meanCycles = mHzStats.mean();
284 double stddevCycles = mHzStats.stddev();
285 double minCycles = mHzStats.minimum();
286 double maxCycles = mHzStats.maximum();
287 mCpuUsage.resetElapsed();
288 mWcStats.reset();
289 mHzStats.reset();
290 ALOGD("CPU usage for %s over past %.1f secs\n"
291 " (%u mixer loops at %.1f mean ms per loop):\n"
292 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
293 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
294 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
295 title.string(),
296 elapsed * .000000001, n, perLoop * .000001,
297 mean * .001,
298 stddev * .001,
299 minimum * .001,
300 maximum * .001,
301 mean / perLoop100,
302 stddev / perLoop100,
303 minimum / perLoop100,
304 maximum / perLoop100,
305 meanCycles / perLoop1k,
306 stddevCycles / perLoop1k,
307 minCycles / perLoop1k,
308 maxCycles / perLoop1k);
309
310 }
311 }
312#endif
313};
314
315// ----------------------------------------------------------------------------
316// ThreadBase
317// ----------------------------------------------------------------------------
318
Glenn Kasten97b7b752014-09-28 13:04:24 -0700319// static
320const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
321{
322 switch (type) {
323 case MIXER:
324 return "MIXER";
325 case DIRECT:
326 return "DIRECT";
327 case DUPLICATING:
328 return "DUPLICATING";
329 case RECORD:
330 return "RECORD";
331 case OFFLOAD:
332 return "OFFLOAD";
333 default:
334 return "unknown";
335 }
336}
337
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800338String8 devicesToString(audio_devices_t devices)
339{
340 static const struct mapping {
341 audio_devices_t mDevices;
342 const char * mString;
343 } mappingsOut[] = {
344 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
345 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
346 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
347 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
348 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
349 AUDIO_DEVICE_NONE, "NONE", // must be last
350 }, mappingsIn[] = {
351 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
352 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
353 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
354 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
355 AUDIO_DEVICE_NONE, "NONE", // must be last
356 };
357 String8 result;
358 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
359 const mapping *entry;
360 if (devices & AUDIO_DEVICE_BIT_IN) {
361 devices &= ~AUDIO_DEVICE_BIT_IN;
362 entry = mappingsIn;
363 } else {
364 entry = mappingsOut;
365 }
366 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
367 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
368 if (devices & entry->mDevices) {
369 if (!result.isEmpty()) {
370 result.append("|");
371 }
372 result.append(entry->mString);
373 }
374 }
375 if (devices & ~allDevices) {
376 if (!result.isEmpty()) {
377 result.append("|");
378 }
379 result.appendFormat("0x%X", devices & ~allDevices);
380 }
381 if (result.isEmpty()) {
382 result.append(entry->mString);
383 }
384 return result;
385}
386
387String8 inputFlagsToString(audio_input_flags_t flags)
388{
389 static const struct mapping {
390 audio_input_flags_t mFlag;
391 const char * mString;
392 } mappings[] = {
393 AUDIO_INPUT_FLAG_FAST, "FAST",
394 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
395 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
396 };
397 String8 result;
398 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
399 const mapping *entry;
400 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
401 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
402 if (flags & entry->mFlag) {
403 if (!result.isEmpty()) {
404 result.append("|");
405 }
406 result.append(entry->mString);
407 }
408 }
409 if (flags & ~allFlags) {
410 if (!result.isEmpty()) {
411 result.append("|");
412 }
413 result.appendFormat("0x%X", flags & ~allFlags);
414 }
415 if (result.isEmpty()) {
416 result.append(entry->mString);
417 }
418 return result;
419}
420
421String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700422{
423 static const struct mapping {
424 audio_output_flags_t mFlag;
425 const char * mString;
426 } mappings[] = {
427 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
428 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
429 AUDIO_OUTPUT_FLAG_FAST, "FAST",
430 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800431 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
433 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
434 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
435 };
436 String8 result;
437 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
438 const mapping *entry;
439 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
440 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
441 if (flags & entry->mFlag) {
442 if (!result.isEmpty()) {
443 result.append("|");
444 }
445 result.append(entry->mString);
446 }
447 }
448 if (flags & ~allFlags) {
449 if (!result.isEmpty()) {
450 result.append("|");
451 }
452 result.appendFormat("0x%X", flags & ~allFlags);
453 }
454 if (result.isEmpty()) {
455 result.append(entry->mString);
456 }
457 return result;
458}
459
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460const char *sourceToString(audio_source_t source)
461{
462 switch (source) {
463 case AUDIO_SOURCE_DEFAULT: return "default";
464 case AUDIO_SOURCE_MIC: return "mic";
465 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
466 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
467 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
468 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
469 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
470 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
471 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
472 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
473 case AUDIO_SOURCE_HOTWORD: return "hotword";
474 default: return "unknown";
475 }
476}
477
Eric Laurent81784c32012-11-19 14:55:58 -0800478AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
479 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
480 : Thread(false /*canCallJava*/),
481 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700482 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700483 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800484 // are set by PlaybackThread::readOutputParameters_l() or
485 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700486 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800487 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
488 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
489 // mName will be set by concrete (non-virtual) subclass
490 mDeathRecipient(new PMDeathRecipient(this))
491{
492}
493
494AudioFlinger::ThreadBase::~ThreadBase()
495{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700496 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700497 mConfigEvents.clear();
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499 // do not lock the mutex in destructor
500 releaseWakeLock_l();
501 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800502 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800503 binder->unlinkToDeath(mDeathRecipient);
504 }
505}
506
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700507status_t AudioFlinger::ThreadBase::readyToRun()
508{
509 status_t status = initCheck();
510 if (status == NO_ERROR) {
511 ALOGI("AudioFlinger's thread %p ready to run", this);
512 } else {
513 ALOGE("No working audio driver found.");
514 }
515 return status;
516}
517
Eric Laurent81784c32012-11-19 14:55:58 -0800518void AudioFlinger::ThreadBase::exit()
519{
520 ALOGV("ThreadBase::exit");
521 // do any cleanup required for exit to succeed
522 preExit();
523 {
524 // This lock prevents the following race in thread (uniprocessor for illustration):
525 // if (!exitPending()) {
526 // // context switch from here to exit()
527 // // exit() calls requestExit(), what exitPending() observes
528 // // exit() calls signal(), which is dropped since no waiters
529 // // context switch back from exit() to here
530 // mWaitWorkCV.wait(...);
531 // // now thread is hung
532 // }
533 AutoMutex lock(mLock);
534 requestExit();
535 mWaitWorkCV.broadcast();
536 }
537 // When Thread::requestExitAndWait is made virtual and this method is renamed to
538 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
539 requestExitAndWait();
540}
541
542status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
543{
544 status_t status;
545
546 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
547 Mutex::Autolock _l(mLock);
548
Eric Laurent10351942014-05-08 18:49:52 -0700549 return sendSetParameterConfigEvent_l(keyValuePairs);
550}
551
552// sendConfigEvent_l() must be called with ThreadBase::mLock held
553// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
554status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
555{
556 status_t status = NO_ERROR;
557
558 mConfigEvents.add(event);
559 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800560 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700561 mLock.unlock();
562 {
563 Mutex::Autolock _l(event->mLock);
564 while (event->mWaitStatus) {
565 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
566 event->mStatus = TIMED_OUT;
567 event->mWaitStatus = false;
568 }
569 }
570 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800571 }
Eric Laurent10351942014-05-08 18:49:52 -0700572 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800573 return status;
574}
575
576void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
577{
578 Mutex::Autolock _l(mLock);
579 sendIoConfigEvent_l(event, param);
580}
581
582// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
583void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
584{
Eric Laurent10351942014-05-08 18:49:52 -0700585 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
586 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800587}
588
589// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
590void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
591{
Eric Laurent10351942014-05-08 18:49:52 -0700592 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
593 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800594}
595
Eric Laurent10351942014-05-08 18:49:52 -0700596// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
597status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800598{
Eric Laurent10351942014-05-08 18:49:52 -0700599 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
600 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700601}
602
Eric Laurent1c333e22014-05-20 10:48:17 -0700603status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
604 const struct audio_patch *patch,
605 audio_patch_handle_t *handle)
606{
607 Mutex::Autolock _l(mLock);
608 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
609 status_t status = sendConfigEvent_l(configEvent);
610 if (status == NO_ERROR) {
611 CreateAudioPatchConfigEventData *data =
612 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
613 *handle = data->mHandle;
614 }
615 return status;
616}
617
618status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
619 const audio_patch_handle_t handle)
620{
621 Mutex::Autolock _l(mLock);
622 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
623 return sendConfigEvent_l(configEvent);
624}
625
626
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700627// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700628void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700629{
Eric Laurent10351942014-05-08 18:49:52 -0700630 bool configChanged = false;
631
Eric Laurent81784c32012-11-19 14:55:58 -0800632 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700633 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
634 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800635 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700636 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700637 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700638 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
639 // FIXME Need to understand why this has to be done asynchronously
640 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700641 true /*asynchronous*/);
642 if (err != 0) {
643 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700644 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700645 }
646 } break;
647 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700648 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700649 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700650 } break;
651 case CFG_EVENT_SET_PARAMETER: {
652 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
653 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
654 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700655 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700656 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700657 case CFG_EVENT_CREATE_AUDIO_PATCH: {
658 CreateAudioPatchConfigEventData *data =
659 (CreateAudioPatchConfigEventData *)event->mData.get();
660 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
661 } break;
662 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
663 ReleaseAudioPatchConfigEventData *data =
664 (ReleaseAudioPatchConfigEventData *)event->mData.get();
665 event->mStatus = releaseAudioPatch_l(data->mHandle);
666 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700667 default:
Eric Laurent10351942014-05-08 18:49:52 -0700668 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700669 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800670 }
Eric Laurent10351942014-05-08 18:49:52 -0700671 {
672 Mutex::Autolock _l(event->mLock);
673 if (event->mWaitStatus) {
674 event->mWaitStatus = false;
675 event->mCond.signal();
676 }
677 }
678 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
679 }
680
681 if (configChanged) {
682 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800683 }
Eric Laurent81784c32012-11-19 14:55:58 -0800684}
685
Marco Nelissenb2208842014-02-07 14:00:50 -0800686String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
687 String8 s;
688 if (output) {
689 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
690 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
691 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
692 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
693 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
694 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
695 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
696 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
697 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
698 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
699 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
700 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
701 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
702 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
703 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
704 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
705 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
706 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
707 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
708 } else {
709 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
710 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
711 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
712 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
713 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
714 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
715 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
716 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
717 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
718 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
719 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
720 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
721 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
722 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
723 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
724 }
725 int len = s.length();
726 if (s.length() > 2) {
727 char *str = s.lockBuffer(len);
728 s.unlockBuffer(len - 2);
729 }
730 return s;
731}
732
Glenn Kasten0f11b512014-01-31 16:18:54 -0800733void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800734{
735 const size_t SIZE = 256;
736 char buffer[SIZE];
737 String8 result;
738
739 bool locked = AudioFlinger::dumpTryLock(mLock);
740 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700741 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
743
Elliott Hughes87cebad2014-05-22 10:14:43 -0700744 dprintf(fd, " I/O handle: %d\n", mId);
745 dprintf(fd, " TID: %d\n", getTid());
746 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700747 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700748 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700749 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700750 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700751 dprintf(fd, " Channel count: %u\n", mChannelCount);
752 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800753 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700754 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
755 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700756 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800757 size_t numConfig = mConfigEvents.size();
758 if (numConfig) {
759 for (size_t i = 0; i < numConfig; i++) {
760 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700761 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800762 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700763 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800764 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700765 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800766 }
Eric Laurent81784c32012-11-19 14:55:58 -0800767
768 if (locked) {
769 mLock.unlock();
770 }
771}
772
773void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
774{
775 const size_t SIZE = 256;
776 char buffer[SIZE];
777 String8 result;
778
Marco Nelissenb2208842014-02-07 14:00:50 -0800779 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000780 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800781 write(fd, buffer, strlen(buffer));
782
Marco Nelissenb2208842014-02-07 14:00:50 -0800783 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800784 sp<EffectChain> chain = mEffectChains[i];
785 if (chain != 0) {
786 chain->dump(fd, args);
787 }
788 }
789}
790
Marco Nelissene14a5d62013-10-03 08:51:24 -0700791void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800792{
793 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700794 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800795}
796
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100797String16 AudioFlinger::ThreadBase::getWakeLockTag()
798{
799 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800800 case MIXER:
801 return String16("AudioMix");
802 case DIRECT:
803 return String16("AudioDirectOut");
804 case DUPLICATING:
805 return String16("AudioDup");
806 case RECORD:
807 return String16("AudioIn");
808 case OFFLOAD:
809 return String16("AudioOffload");
810 default:
811 ALOG_ASSERT(false);
812 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100813 }
814}
815
Marco Nelissene14a5d62013-10-03 08:51:24 -0700816void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800817{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800818 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800819 if (mPowerManager != 0) {
820 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700821 status_t status;
822 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700823 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700824 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100825 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700826 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700827 uid,
828 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700829 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700830 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700831 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100832 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700833 String16("media"),
834 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700835 }
Eric Laurent81784c32012-11-19 14:55:58 -0800836 if (status == NO_ERROR) {
837 mWakeLockToken = binder;
838 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800839 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800840 }
841}
842
843void AudioFlinger::ThreadBase::releaseWakeLock()
844{
845 Mutex::Autolock _l(mLock);
846 releaseWakeLock_l();
847}
848
849void AudioFlinger::ThreadBase::releaseWakeLock_l()
850{
851 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800852 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800853 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700854 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
855 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800856 }
857 mWakeLockToken.clear();
858 }
859}
860
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800861void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
862 Mutex::Autolock _l(mLock);
863 updateWakeLockUids_l(uids);
864}
865
866void AudioFlinger::ThreadBase::getPowerManager_l() {
867
868 if (mPowerManager == 0) {
869 // use checkService() to avoid blocking if power service is not up yet
870 sp<IBinder> binder =
871 defaultServiceManager()->checkService(String16("power"));
872 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800873 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800874 } else {
875 mPowerManager = interface_cast<IPowerManager>(binder);
876 binder->linkToDeath(mDeathRecipient);
877 }
878 }
879}
880
881void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
882
883 getPowerManager_l();
884 if (mWakeLockToken == NULL) {
885 ALOGE("no wake lock to update!");
886 return;
887 }
888 if (mPowerManager != 0) {
889 sp<IBinder> binder = new BBinder();
890 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700891 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
892 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800893 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800894 }
895}
896
Eric Laurent81784c32012-11-19 14:55:58 -0800897void AudioFlinger::ThreadBase::clearPowerManager()
898{
899 Mutex::Autolock _l(mLock);
900 releaseWakeLock_l();
901 mPowerManager.clear();
902}
903
Glenn Kasten0f11b512014-01-31 16:18:54 -0800904void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800905{
906 sp<ThreadBase> thread = mThread.promote();
907 if (thread != 0) {
908 thread->clearPowerManager();
909 }
910 ALOGW("power manager service died !!!");
911}
912
913void AudioFlinger::ThreadBase::setEffectSuspended(
914 const effect_uuid_t *type, bool suspend, int sessionId)
915{
916 Mutex::Autolock _l(mLock);
917 setEffectSuspended_l(type, suspend, sessionId);
918}
919
920void AudioFlinger::ThreadBase::setEffectSuspended_l(
921 const effect_uuid_t *type, bool suspend, int sessionId)
922{
923 sp<EffectChain> chain = getEffectChain_l(sessionId);
924 if (chain != 0) {
925 if (type != NULL) {
926 chain->setEffectSuspended_l(type, suspend);
927 } else {
928 chain->setEffectSuspendedAll_l(suspend);
929 }
930 }
931
932 updateSuspendedSessions_l(type, suspend, sessionId);
933}
934
935void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
936{
937 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
938 if (index < 0) {
939 return;
940 }
941
942 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
943 mSuspendedSessions.valueAt(index);
944
945 for (size_t i = 0; i < sessionEffects.size(); i++) {
946 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
947 for (int j = 0; j < desc->mRefCount; j++) {
948 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
949 chain->setEffectSuspendedAll_l(true);
950 } else {
951 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
952 desc->mType.timeLow);
953 chain->setEffectSuspended_l(&desc->mType, true);
954 }
955 }
956 }
957}
958
959void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
960 bool suspend,
961 int sessionId)
962{
963 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
964
965 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
966
967 if (suspend) {
968 if (index >= 0) {
969 sessionEffects = mSuspendedSessions.valueAt(index);
970 } else {
971 mSuspendedSessions.add(sessionId, sessionEffects);
972 }
973 } else {
974 if (index < 0) {
975 return;
976 }
977 sessionEffects = mSuspendedSessions.valueAt(index);
978 }
979
980
981 int key = EffectChain::kKeyForSuspendAll;
982 if (type != NULL) {
983 key = type->timeLow;
984 }
985 index = sessionEffects.indexOfKey(key);
986
987 sp<SuspendedSessionDesc> desc;
988 if (suspend) {
989 if (index >= 0) {
990 desc = sessionEffects.valueAt(index);
991 } else {
992 desc = new SuspendedSessionDesc();
993 if (type != NULL) {
994 desc->mType = *type;
995 }
996 sessionEffects.add(key, desc);
997 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
998 }
999 desc->mRefCount++;
1000 } else {
1001 if (index < 0) {
1002 return;
1003 }
1004 desc = sessionEffects.valueAt(index);
1005 if (--desc->mRefCount == 0) {
1006 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1007 sessionEffects.removeItemsAt(index);
1008 if (sessionEffects.isEmpty()) {
1009 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1010 sessionId);
1011 mSuspendedSessions.removeItem(sessionId);
1012 }
1013 }
1014 }
1015 if (!sessionEffects.isEmpty()) {
1016 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1017 }
1018}
1019
1020void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1021 bool enabled,
1022 int sessionId)
1023{
1024 Mutex::Autolock _l(mLock);
1025 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1026}
1027
1028void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1029 bool enabled,
1030 int sessionId)
1031{
1032 if (mType != RECORD) {
1033 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1034 // another session. This gives the priority to well behaved effect control panels
1035 // and applications not using global effects.
1036 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1037 // global effects
1038 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1039 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1040 }
1041 }
1042
1043 sp<EffectChain> chain = getEffectChain_l(sessionId);
1044 if (chain != 0) {
1045 chain->checkSuspendOnEffectEnabled(effect, enabled);
1046 }
1047}
1048
1049// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1050sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1051 const sp<AudioFlinger::Client>& client,
1052 const sp<IEffectClient>& effectClient,
1053 int32_t priority,
1054 int sessionId,
1055 effect_descriptor_t *desc,
1056 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001057 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001058{
1059 sp<EffectModule> effect;
1060 sp<EffectHandle> handle;
1061 status_t lStatus;
1062 sp<EffectChain> chain;
1063 bool chainCreated = false;
1064 bool effectCreated = false;
1065 bool effectRegistered = false;
1066
1067 lStatus = initCheck();
1068 if (lStatus != NO_ERROR) {
1069 ALOGW("createEffect_l() Audio driver not initialized.");
1070 goto Exit;
1071 }
1072
Andy Hung98ef9782014-03-04 14:46:50 -08001073 // Reject any effect on Direct output threads for now, since the format of
1074 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1075 if (mType == DIRECT) {
1076 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001077 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001078 lStatus = BAD_VALUE;
1079 goto Exit;
1080 }
1081
Andy Hung389cfdb2014-08-07 17:49:53 -07001082 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001083 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001084 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1085 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1086 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001087 lStatus = BAD_VALUE;
1088 goto Exit;
1089 }
1090
Eric Laurent5baf2af2013-09-12 17:37:00 -07001091 // Allow global effects only on offloaded and mixer threads
1092 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1093 switch (mType) {
1094 case MIXER:
1095 case OFFLOAD:
1096 break;
1097 case DIRECT:
1098 case DUPLICATING:
1099 case RECORD:
1100 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001101 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1102 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001103 lStatus = BAD_VALUE;
1104 goto Exit;
1105 }
Eric Laurent81784c32012-11-19 14:55:58 -08001106 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001107
Eric Laurent81784c32012-11-19 14:55:58 -08001108 // Only Pre processor effects are allowed on input threads and only on input threads
1109 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1110 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1111 desc->name, desc->flags, mType);
1112 lStatus = BAD_VALUE;
1113 goto Exit;
1114 }
1115
1116 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1117
1118 { // scope for mLock
1119 Mutex::Autolock _l(mLock);
1120
1121 // check for existing effect chain with the requested audio session
1122 chain = getEffectChain_l(sessionId);
1123 if (chain == 0) {
1124 // create a new chain for this session
1125 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1126 chain = new EffectChain(this, sessionId);
1127 addEffectChain_l(chain);
1128 chain->setStrategy(getStrategyForSession_l(sessionId));
1129 chainCreated = true;
1130 } else {
1131 effect = chain->getEffectFromDesc_l(desc);
1132 }
1133
1134 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1135
1136 if (effect == 0) {
1137 int id = mAudioFlinger->nextUniqueId();
1138 // Check CPU and memory usage
1139 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1140 if (lStatus != NO_ERROR) {
1141 goto Exit;
1142 }
1143 effectRegistered = true;
1144 // create a new effect module if none present in the chain
1145 effect = new EffectModule(this, chain, desc, id, sessionId);
1146 lStatus = effect->status();
1147 if (lStatus != NO_ERROR) {
1148 goto Exit;
1149 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001150 effect->setOffloaded(mType == OFFLOAD, mId);
1151
Eric Laurent81784c32012-11-19 14:55:58 -08001152 lStatus = chain->addEffect_l(effect);
1153 if (lStatus != NO_ERROR) {
1154 goto Exit;
1155 }
1156 effectCreated = true;
1157
1158 effect->setDevice(mOutDevice);
1159 effect->setDevice(mInDevice);
1160 effect->setMode(mAudioFlinger->getMode());
1161 effect->setAudioSource(mAudioSource);
1162 }
1163 // create effect handle and connect it to effect module
1164 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001165 lStatus = handle->initCheck();
1166 if (lStatus == OK) {
1167 lStatus = effect->addHandle(handle.get());
1168 }
Eric Laurent81784c32012-11-19 14:55:58 -08001169 if (enabled != NULL) {
1170 *enabled = (int)effect->isEnabled();
1171 }
1172 }
1173
1174Exit:
1175 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1176 Mutex::Autolock _l(mLock);
1177 if (effectCreated) {
1178 chain->removeEffect_l(effect);
1179 }
1180 if (effectRegistered) {
1181 AudioSystem::unregisterEffect(effect->id());
1182 }
1183 if (chainCreated) {
1184 removeEffectChain_l(chain);
1185 }
1186 handle.clear();
1187 }
1188
Glenn Kasten9156ef32013-08-06 15:39:08 -07001189 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001190 return handle;
1191}
1192
1193sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1194{
1195 Mutex::Autolock _l(mLock);
1196 return getEffect_l(sessionId, effectId);
1197}
1198
1199sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1200{
1201 sp<EffectChain> chain = getEffectChain_l(sessionId);
1202 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1203}
1204
1205// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1206// PlaybackThread::mLock held
1207status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1208{
1209 // check for existing effect chain with the requested audio session
1210 int sessionId = effect->sessionId();
1211 sp<EffectChain> chain = getEffectChain_l(sessionId);
1212 bool chainCreated = false;
1213
Eric Laurent5baf2af2013-09-12 17:37:00 -07001214 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1215 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1216 this, effect->desc().name, effect->desc().flags);
1217
Eric Laurent81784c32012-11-19 14:55:58 -08001218 if (chain == 0) {
1219 // create a new chain for this session
1220 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1221 chain = new EffectChain(this, sessionId);
1222 addEffectChain_l(chain);
1223 chain->setStrategy(getStrategyForSession_l(sessionId));
1224 chainCreated = true;
1225 }
1226 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1227
1228 if (chain->getEffectFromId_l(effect->id()) != 0) {
1229 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1230 this, effect->desc().name, chain.get());
1231 return BAD_VALUE;
1232 }
1233
Eric Laurent5baf2af2013-09-12 17:37:00 -07001234 effect->setOffloaded(mType == OFFLOAD, mId);
1235
Eric Laurent81784c32012-11-19 14:55:58 -08001236 status_t status = chain->addEffect_l(effect);
1237 if (status != NO_ERROR) {
1238 if (chainCreated) {
1239 removeEffectChain_l(chain);
1240 }
1241 return status;
1242 }
1243
1244 effect->setDevice(mOutDevice);
1245 effect->setDevice(mInDevice);
1246 effect->setMode(mAudioFlinger->getMode());
1247 effect->setAudioSource(mAudioSource);
1248 return NO_ERROR;
1249}
1250
1251void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1252
1253 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1254 effect_descriptor_t desc = effect->desc();
1255 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1256 detachAuxEffect_l(effect->id());
1257 }
1258
1259 sp<EffectChain> chain = effect->chain().promote();
1260 if (chain != 0) {
1261 // remove effect chain if removing last effect
1262 if (chain->removeEffect_l(effect) == 0) {
1263 removeEffectChain_l(chain);
1264 }
1265 } else {
1266 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1267 }
1268}
1269
1270void AudioFlinger::ThreadBase::lockEffectChains_l(
1271 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1272{
1273 effectChains = mEffectChains;
1274 for (size_t i = 0; i < mEffectChains.size(); i++) {
1275 mEffectChains[i]->lock();
1276 }
1277}
1278
1279void AudioFlinger::ThreadBase::unlockEffectChains(
1280 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1281{
1282 for (size_t i = 0; i < effectChains.size(); i++) {
1283 effectChains[i]->unlock();
1284 }
1285}
1286
1287sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1288{
1289 Mutex::Autolock _l(mLock);
1290 return getEffectChain_l(sessionId);
1291}
1292
1293sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1294{
1295 size_t size = mEffectChains.size();
1296 for (size_t i = 0; i < size; i++) {
1297 if (mEffectChains[i]->sessionId() == sessionId) {
1298 return mEffectChains[i];
1299 }
1300 }
1301 return 0;
1302}
1303
1304void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1305{
1306 Mutex::Autolock _l(mLock);
1307 size_t size = mEffectChains.size();
1308 for (size_t i = 0; i < size; i++) {
1309 mEffectChains[i]->setMode_l(mode);
1310 }
1311}
1312
Eric Laurent83b88082014-06-20 18:31:16 -07001313void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1314{
1315 config->type = AUDIO_PORT_TYPE_MIX;
1316 config->ext.mix.handle = mId;
1317 config->sample_rate = mSampleRate;
1318 config->format = mFormat;
1319 config->channel_mask = mChannelMask;
1320 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1321 AUDIO_PORT_CONFIG_FORMAT;
1322}
1323
1324
Eric Laurent81784c32012-11-19 14:55:58 -08001325// ----------------------------------------------------------------------------
1326// Playback
1327// ----------------------------------------------------------------------------
1328
1329AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1330 AudioStreamOut* output,
1331 audio_io_handle_t id,
1332 audio_devices_t device,
1333 type_t type)
1334 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001335 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001336 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001337 mMixerBuffer(NULL),
1338 mMixerBufferSize(0),
1339 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1340 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001341 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001342 mEffectBuffer(NULL),
1343 mEffectBufferSize(0),
1344 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1345 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001346 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001347 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001348 // mStreamTypes[] initialized in constructor body
1349 mOutput(output),
1350 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1351 mMixerStatus(MIXER_IDLE),
1352 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1353 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001354 mBytesRemaining(0),
1355 mCurrentWriteLength(0),
1356 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001357 mWriteAckSequence(0),
1358 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001359 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001360 mScreenState(AudioFlinger::mScreenState),
1361 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001362 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001363 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001364 // mLatchD, mLatchQ,
1365 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001366{
Glenn Kastend7dca052015-03-05 16:05:54 -08001367 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1368 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001369
1370 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1371 // it would be safer to explicitly pass initial masterVolume/masterMute as
1372 // parameter.
1373 //
1374 // If the HAL we are using has support for master volume or master mute,
1375 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1376 // and the mute set to false).
1377 mMasterVolume = audioFlinger->masterVolume_l();
1378 mMasterMute = audioFlinger->masterMute_l();
1379 if (mOutput && mOutput->audioHwDev) {
1380 if (mOutput->audioHwDev->canSetMasterVolume()) {
1381 mMasterVolume = 1.0;
1382 }
1383
1384 if (mOutput->audioHwDev->canSetMasterMute()) {
1385 mMasterMute = false;
1386 }
1387 }
1388
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001389 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001390
Eric Laurent223fd5c2014-11-11 13:43:36 -08001391 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001392 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001393 stream = (audio_stream_type_t) (stream + 1)) {
1394 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1395 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1396 }
Eric Laurent81784c32012-11-19 14:55:58 -08001397}
1398
1399AudioFlinger::PlaybackThread::~PlaybackThread()
1400{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001401 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001402 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001403 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001404 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001405}
1406
1407void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1408{
1409 dumpInternals(fd, args);
1410 dumpTracks(fd, args);
1411 dumpEffectChains(fd, args);
1412}
1413
Glenn Kasten0f11b512014-01-31 16:18:54 -08001414void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001415{
1416 const size_t SIZE = 256;
1417 char buffer[SIZE];
1418 String8 result;
1419
Marco Nelissenb2208842014-02-07 14:00:50 -08001420 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001421 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1422 const stream_type_t *st = &mStreamTypes[i];
1423 if (i > 0) {
1424 result.appendFormat(", ");
1425 }
1426 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1427 if (st->mute) {
1428 result.append("M");
1429 }
1430 }
1431 result.append("\n");
1432 write(fd, result.string(), result.length());
1433 result.clear();
1434
Eric Laurent81784c32012-11-19 14:55:58 -08001435 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1436 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001437 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001438 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001439
1440 size_t numtracks = mTracks.size();
1441 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001442 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001443 size_t numactiveseen = 0;
1444 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001445 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001446 Track::appendDumpHeader(result);
1447 for (size_t i = 0; i < numtracks; ++i) {
1448 sp<Track> track = mTracks[i];
1449 if (track != 0) {
1450 bool active = mActiveTracks.indexOf(track) >= 0;
1451 if (active) {
1452 numactiveseen++;
1453 }
1454 track->dump(buffer, SIZE, active);
1455 result.append(buffer);
1456 }
1457 }
1458 } else {
1459 result.append("\n");
1460 }
1461 if (numactiveseen != numactive) {
1462 // some tracks in the active list were not in the tracks list
1463 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1464 " not in the track list\n");
1465 result.append(buffer);
1466 Track::appendDumpHeader(result);
1467 for (size_t i = 0; i < numactive; ++i) {
1468 sp<Track> track = mActiveTracks[i].promote();
1469 if (track != 0 && mTracks.indexOf(track) < 0) {
1470 track->dump(buffer, SIZE, true);
1471 result.append(buffer);
1472 }
1473 }
1474 }
1475
1476 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001477}
1478
1479void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1480{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001481 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001482 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1483 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1484 dprintf(fd, " Total writes: %d\n", mNumWrites);
1485 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1486 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1487 dprintf(fd, " Suspend count: %d\n", mSuspended);
1488 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1489 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1490 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1491 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001492 AudioStreamOut *output = mOutput;
1493 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1494 String8 flagsAsString = outputFlagsToString(flags);
1495 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001496
1497 dumpBase(fd, args);
1498}
1499
1500// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001501
1502void AudioFlinger::PlaybackThread::onFirstRef()
1503{
Glenn Kastend7dca052015-03-05 16:05:54 -08001504 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001505}
1506
1507// ThreadBase virtuals
1508void AudioFlinger::PlaybackThread::preExit()
1509{
1510 ALOGV(" preExit()");
1511 // FIXME this is using hard-coded strings but in the future, this functionality will be
1512 // converted to use audio HAL extensions required to support tunneling
1513 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1514}
1515
1516// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1517sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1518 const sp<AudioFlinger::Client>& client,
1519 audio_stream_type_t streamType,
1520 uint32_t sampleRate,
1521 audio_format_t format,
1522 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001523 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001524 const sp<IMemory>& sharedBuffer,
1525 int sessionId,
1526 IAudioFlinger::track_flags_t *flags,
1527 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001528 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001529 status_t *status)
1530{
Glenn Kasten74935e42013-12-19 08:56:45 -08001531 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001532 sp<Track> track;
1533 status_t lStatus;
1534
1535 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1536
1537 // client expresses a preference for FAST, but we get the final say
1538 if (*flags & IAudioFlinger::TRACK_FAST) {
1539 if (
1540 // not timed
1541 (!isTimed) &&
1542 // either of these use cases:
1543 (
1544 // use case 1: shared buffer with any frame count
1545 (
1546 (sharedBuffer != 0)
1547 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001548 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001549 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001550 // we formerly checked for a callback handler (non-0 tid),
1551 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001552 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001553 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001554 )
1555 ) &&
1556 // PCM data
1557 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001558 // identical channel mask to sink, or mono in and stereo sink
1559 (channelMask == mChannelMask ||
1560 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1561 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001562 // hardware sample rate
1563 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001564 // normal mixer has an associated fast mixer
1565 hasFastMixer() &&
1566 // there are sufficient fast track slots available
1567 (mFastTrackAvailMask != 0)
1568 // FIXME test that MixerThread for this fast track has a capable output HAL
1569 // FIXME add a permission test also?
1570 ) {
1571 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1572 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001573 // read the fast track multiplier property the first time it is needed
1574 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1575 if (ok != 0) {
1576 ALOGE("%s pthread_once failed: %d", __func__, ok);
1577 }
1578 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001579 }
1580 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1581 frameCount, mFrameCount);
1582 } else {
1583 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001584 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1585 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001586 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001587 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001588 audio_is_linear_pcm(format),
1589 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1590 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001591 }
1592 }
1593 // For normal PCM streaming tracks, update minimum frame count.
1594 // For compatibility with AudioTrack calculation, buffer depth is forced
1595 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1596 // This is probably too conservative, but legacy application code may depend on it.
1597 // If you change this calculation, also review the start threshold which is related.
1598 if (!(*flags & IAudioFlinger::TRACK_FAST)
1599 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001600 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1601 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1602 if (minBufCount < 2) {
1603 minBufCount = 2;
1604 }
Andy Hung0e48d252015-01-26 11:43:15 -08001605 size_t minFrameCount =
1606 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1607 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001608 frameCount = minFrameCount;
1609 }
Eric Laurent81784c32012-11-19 14:55:58 -08001610 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001611 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001612
Glenn Kastenc3df8382014-03-13 15:05:25 -07001613 switch (mType) {
1614
1615 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001616 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001617 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001618 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1619 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001620 sampleRate, format, channelMask, mOutput, mFormat);
1621 lStatus = BAD_VALUE;
1622 goto Exit;
1623 }
1624 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001625 break;
1626
1627 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001628 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001629 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1630 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001631 sampleRate, format, channelMask, mOutput, mFormat);
1632 lStatus = BAD_VALUE;
1633 goto Exit;
1634 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001635 break;
1636
1637 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001638 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001639 ALOGE("createTrack_l() Bad parameter: format %#x \""
1640 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001641 format, mOutput, mFormat);
1642 lStatus = BAD_VALUE;
1643 goto Exit;
1644 }
Andy Hungcd044842014-08-07 11:04:34 -07001645 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001646 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1647 lStatus = BAD_VALUE;
1648 goto Exit;
1649 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001650 break;
1651
Eric Laurent81784c32012-11-19 14:55:58 -08001652 }
1653
1654 lStatus = initCheck();
1655 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001656 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001657 goto Exit;
1658 }
1659
1660 { // scope for mLock
1661 Mutex::Autolock _l(mLock);
1662
1663 // all tracks in same audio session must share the same routing strategy otherwise
1664 // conflicts will happen when tracks are moved from one output to another by audio policy
1665 // manager
1666 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1667 for (size_t i = 0; i < mTracks.size(); ++i) {
1668 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001669 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001670 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1671 if (sessionId == t->sessionId() && strategy != actual) {
1672 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1673 strategy, actual);
1674 lStatus = BAD_VALUE;
1675 goto Exit;
1676 }
1677 }
1678 }
1679
1680 if (!isTimed) {
1681 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001682 channelMask, frameCount, NULL, sharedBuffer,
1683 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001684 } else {
1685 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001686 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001687 }
Glenn Kasten03003332013-08-06 15:40:54 -07001688
1689 // new Track always returns non-NULL,
1690 // but TimedTrack::create() is a factory that could fail by returning NULL
1691 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1692 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001693 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001694 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001695 goto Exit;
1696 }
1697 mTracks.add(track);
1698
1699 sp<EffectChain> chain = getEffectChain_l(sessionId);
1700 if (chain != 0) {
1701 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1702 track->setMainBuffer(chain->inBuffer());
1703 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1704 chain->incTrackCnt();
1705 }
1706
1707 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1708 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1709 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1710 // so ask activity manager to do this on our behalf
1711 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1712 }
1713 }
1714
1715 lStatus = NO_ERROR;
1716
1717Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001718 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001719 return track;
1720}
1721
1722uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1723{
1724 return latency;
1725}
1726
1727uint32_t AudioFlinger::PlaybackThread::latency() const
1728{
1729 Mutex::Autolock _l(mLock);
1730 return latency_l();
1731}
1732uint32_t AudioFlinger::PlaybackThread::latency_l() const
1733{
1734 if (initCheck() == NO_ERROR) {
1735 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1736 } else {
1737 return 0;
1738 }
1739}
1740
1741void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1742{
1743 Mutex::Autolock _l(mLock);
1744 // Don't apply master volume in SW if our HAL can do it for us.
1745 if (mOutput && mOutput->audioHwDev &&
1746 mOutput->audioHwDev->canSetMasterVolume()) {
1747 mMasterVolume = 1.0;
1748 } else {
1749 mMasterVolume = value;
1750 }
1751}
1752
1753void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1754{
1755 Mutex::Autolock _l(mLock);
1756 // Don't apply master mute in SW if our HAL can do it for us.
1757 if (mOutput && mOutput->audioHwDev &&
1758 mOutput->audioHwDev->canSetMasterMute()) {
1759 mMasterMute = false;
1760 } else {
1761 mMasterMute = muted;
1762 }
1763}
1764
1765void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1766{
1767 Mutex::Autolock _l(mLock);
1768 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001769 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001770}
1771
1772void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1773{
1774 Mutex::Autolock _l(mLock);
1775 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001776 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001777}
1778
1779float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1780{
1781 Mutex::Autolock _l(mLock);
1782 return mStreamTypes[stream].volume;
1783}
1784
1785// addTrack_l() must be called with ThreadBase::mLock held
1786status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1787{
1788 status_t status = ALREADY_EXISTS;
1789
1790 // set retry count for buffer fill
1791 track->mRetryCount = kMaxTrackStartupRetries;
1792 if (mActiveTracks.indexOf(track) < 0) {
1793 // the track is newly added, make sure it fills up all its
1794 // buffers before playing. This is to ensure the client will
1795 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001796 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001797 TrackBase::track_state state = track->mState;
1798 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001799 status = AudioSystem::startOutput(mId, track->streamType(),
1800 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001801 mLock.lock();
1802 // abort track was stopped/paused while we released the lock
1803 if (state != track->mState) {
1804 if (status == NO_ERROR) {
1805 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001806 AudioSystem::stopOutput(mId, track->streamType(),
1807 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001808 mLock.lock();
1809 }
1810 return INVALID_OPERATION;
1811 }
1812 // abort if start is rejected by audio policy manager
1813 if (status != NO_ERROR) {
1814 return PERMISSION_DENIED;
1815 }
1816#ifdef ADD_BATTERY_DATA
1817 // to track the speaker usage
1818 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1819#endif
1820 }
1821
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001822 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001823 track->mResetDone = false;
1824 track->mPresentationCompleteFrames = 0;
1825 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001826 mWakeLockUids.add(track->uid());
1827 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001828 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001829 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1830 if (chain != 0) {
1831 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1832 track->sessionId());
1833 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001834 }
1835
1836 status = NO_ERROR;
1837 }
1838
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001839 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001840 return status;
1841}
1842
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001844{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001846 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001847 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1848 track->mState = TrackBase::STOPPED;
1849 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001850 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001851 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001852 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001853 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001854
1855 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001856}
1857
1858void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1859{
1860 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1861 mTracks.remove(track);
1862 deleteTrackName_l(track->name());
1863 // redundant as track is about to be destroyed, for dumpsys only
1864 track->mName = -1;
1865 if (track->isFastTrack()) {
1866 int index = track->mFastIndex;
1867 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1868 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1869 mFastTrackAvailMask |= 1 << index;
1870 // redundant as track is about to be destroyed, for dumpsys only
1871 track->mFastIndex = -1;
1872 }
1873 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1874 if (chain != 0) {
1875 chain->decTrackCnt();
1876 }
1877}
1878
Eric Laurentede6c3b2013-09-19 14:37:46 -07001879void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001880{
1881 // Thread could be blocked waiting for async
1882 // so signal it to handle state changes immediately
1883 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1884 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1885 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001886 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001887}
1888
Eric Laurent81784c32012-11-19 14:55:58 -08001889String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1890{
Eric Laurent81784c32012-11-19 14:55:58 -08001891 Mutex::Autolock _l(mLock);
1892 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001893 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001894 }
1895
Glenn Kastend8ea6992013-07-16 14:17:15 -07001896 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1897 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001898 free(s);
1899 return out_s8;
1900}
1901
Eric Laurent021cf962014-05-13 10:18:14 -07001902void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001903 AudioSystem::OutputDescriptor desc;
1904 void *param2 = NULL;
1905
Eric Laurent021cf962014-05-13 10:18:14 -07001906 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001907 param);
1908
1909 switch (event) {
1910 case AudioSystem::OUTPUT_OPENED:
1911 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001912 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001913 desc.samplingRate = mSampleRate;
1914 desc.format = mFormat;
1915 desc.frameCount = mNormalFrameCount; // FIXME see
1916 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001917 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001918 param2 = &desc;
1919 break;
1920
1921 case AudioSystem::STREAM_CONFIG_CHANGED:
1922 param2 = &param;
1923 case AudioSystem::OUTPUT_CLOSED:
1924 default:
1925 break;
1926 }
Eric Laurent021cf962014-05-13 10:18:14 -07001927 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001928}
1929
Eric Laurentbfb1b832013-01-07 09:53:42 -08001930void AudioFlinger::PlaybackThread::writeCallback()
1931{
1932 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001933 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001934}
1935
1936void AudioFlinger::PlaybackThread::drainCallback()
1937{
1938 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001939 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001940}
1941
Eric Laurent3b4529e2013-09-05 18:09:19 -07001942void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001943{
1944 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001945 // reject out of sequence requests
1946 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1947 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948 mWaitWorkCV.signal();
1949 }
1950}
1951
Eric Laurent3b4529e2013-09-05 18:09:19 -07001952void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953{
1954 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001955 // reject out of sequence requests
1956 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1957 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 mWaitWorkCV.signal();
1959 }
1960}
1961
1962// static
1963int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001964 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965 void *cookie)
1966{
1967 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1968 ALOGV("asyncCallback() event %d", event);
1969 switch (event) {
1970 case STREAM_CBK_EVENT_WRITE_READY:
1971 me->writeCallback();
1972 break;
1973 case STREAM_CBK_EVENT_DRAIN_READY:
1974 me->drainCallback();
1975 break;
1976 default:
1977 ALOGW("asyncCallback() unknown event %d", event);
1978 break;
1979 }
1980 return 0;
1981}
1982
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001983void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001984{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001985 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001986 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1987 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001988 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001989 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001990 }
Andy Hung9a592762014-07-21 21:56:01 -07001991 if ((mType == MIXER || mType == DUPLICATING)
1992 && !isValidPcmSinkChannelMask(mChannelMask)) {
1993 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1994 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001995 }
Andy Hunge5412692014-05-16 11:25:07 -07001996 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001997 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1998 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001999 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002000 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002001 }
Andy Hung6146c082014-03-18 11:56:15 -07002002 if ((mType == MIXER || mType == DUPLICATING)
2003 && !isValidPcmSinkFormat(mFormat)) {
2004 LOG_FATAL("HAL format %#x not supported for mixed output",
2005 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002006 }
Eric Laurent665470b2014-07-03 16:37:08 -07002007 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07002008 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2009 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002010 if (mFrameCount & 15) {
2011 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2012 mFrameCount);
2013 }
2014
Eric Laurentbfb1b832013-01-07 09:53:42 -08002015 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2016 (mOutput->stream->set_callback != NULL)) {
2017 if (mOutput->stream->set_callback(mOutput->stream,
2018 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2019 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002020 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002021 }
2022 }
2023
Eric Laurentd1f69b02014-12-15 14:33:13 -08002024 mHwSupportsPause = false;
2025 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2026 if (mOutput->stream->pause != NULL) {
2027 if (mOutput->stream->resume != NULL) {
2028 mHwSupportsPause = true;
2029 } else {
2030 ALOGW("direct output implements pause but not resume");
2031 }
2032 } else if (mOutput->stream->resume != NULL) {
2033 ALOGW("direct output implements resume but not pause");
2034 }
2035 }
2036
Andy Hungfbfc3952015-01-15 13:33:51 -08002037 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2038 // For best precision, we use float instead of the associated output
2039 // device format (typically PCM 16 bit).
2040
2041 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2042 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2043 mBufferSize = mFrameSize * mFrameCount;
2044
2045 // TODO: We currently use the associated output device channel mask and sample rate.
2046 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2047 // (if a valid mask) to avoid premature downmix.
2048 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2049 // instead of the output device sample rate to avoid loss of high frequency information.
2050 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2051 }
2052
Andy Hung09a50072014-02-27 14:30:47 -08002053 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002054 double multiplier = 1.0;
2055 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2056 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002057 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2058 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002059 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2060 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2061 maxNormalFrameCount = maxNormalFrameCount & ~15;
2062 if (maxNormalFrameCount < minNormalFrameCount) {
2063 maxNormalFrameCount = minNormalFrameCount;
2064 }
2065 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2066 if (multiplier <= 1.0) {
2067 multiplier = 1.0;
2068 } else if (multiplier <= 2.0) {
2069 if (2 * mFrameCount <= maxNormalFrameCount) {
2070 multiplier = 2.0;
2071 } else {
2072 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2073 }
2074 } else {
2075 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002076 // 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 -08002077 // track, but we sometimes have to do this to satisfy the maximum frame count
2078 // constraint)
2079 // FIXME this rounding up should not be done if no HAL SRC
2080 uint32_t truncMult = (uint32_t) multiplier;
2081 if ((truncMult & 1)) {
2082 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2083 ++truncMult;
2084 }
2085 }
2086 multiplier = (double) truncMult;
2087 }
2088 }
2089 mNormalFrameCount = multiplier * mFrameCount;
2090 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002091 if (mType == MIXER || mType == DUPLICATING) {
2092 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2093 }
Andy Hung09a50072014-02-27 14:30:47 -08002094 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002095 mNormalFrameCount);
2096
Andy Hung010a1a12014-03-13 13:57:33 -07002097 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2098 // Originally this was int16_t[] array, need to remove legacy implications.
2099 free(mSinkBuffer);
2100 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002101 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2102 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2103 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002104 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002105
Andy Hung69aed5f2014-02-25 17:24:40 -08002106 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2107 // drives the output.
2108 free(mMixerBuffer);
2109 mMixerBuffer = NULL;
2110 if (mMixerBufferEnabled) {
2111 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2112 mMixerBufferSize = mNormalFrameCount * mChannelCount
2113 * audio_bytes_per_sample(mMixerBufferFormat);
2114 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2115 }
Andy Hung98ef9782014-03-04 14:46:50 -08002116 free(mEffectBuffer);
2117 mEffectBuffer = NULL;
2118 if (mEffectBufferEnabled) {
2119 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2120 mEffectBufferSize = mNormalFrameCount * mChannelCount
2121 * audio_bytes_per_sample(mEffectBufferFormat);
2122 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2123 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002124
Eric Laurent81784c32012-11-19 14:55:58 -08002125 // force reconfiguration of effect chains and engines to take new buffer size and audio
2126 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002127 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002128 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2129 // matter.
2130 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2131 Vector< sp<EffectChain> > effectChains = mEffectChains;
2132 for (size_t i = 0; i < effectChains.size(); i ++) {
2133 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2134 }
2135}
2136
2137
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002138status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002139{
2140 if (halFrames == NULL || dspFrames == NULL) {
2141 return BAD_VALUE;
2142 }
2143 Mutex::Autolock _l(mLock);
2144 if (initCheck() != NO_ERROR) {
2145 return INVALID_OPERATION;
2146 }
2147 size_t framesWritten = mBytesWritten / mFrameSize;
2148 *halFrames = framesWritten;
2149
2150 if (isSuspended()) {
2151 // return an estimation of rendered frames when the output is suspended
2152 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2153 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2154 return NO_ERROR;
2155 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002156 status_t status;
2157 uint32_t frames;
2158 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2159 *dspFrames = (size_t)frames;
2160 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002161 }
2162}
2163
2164uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2165{
2166 Mutex::Autolock _l(mLock);
2167 uint32_t result = 0;
2168 if (getEffectChain_l(sessionId) != 0) {
2169 result = EFFECT_SESSION;
2170 }
2171
2172 for (size_t i = 0; i < mTracks.size(); ++i) {
2173 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002174 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002175 result |= TRACK_SESSION;
2176 break;
2177 }
2178 }
2179
2180 return result;
2181}
2182
2183uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2184{
2185 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2186 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2187 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2188 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2189 }
2190 for (size_t i = 0; i < mTracks.size(); i++) {
2191 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002192 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002193 return AudioSystem::getStrategyForStream(track->streamType());
2194 }
2195 }
2196 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2197}
2198
2199
2200AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2201{
2202 Mutex::Autolock _l(mLock);
2203 return mOutput;
2204}
2205
2206AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2207{
2208 Mutex::Autolock _l(mLock);
2209 AudioStreamOut *output = mOutput;
2210 mOutput = NULL;
2211 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2212 // must push a NULL and wait for ack
2213 mOutputSink.clear();
2214 mPipeSink.clear();
2215 mNormalSink.clear();
2216 return output;
2217}
2218
2219// this method must always be called either with ThreadBase mLock held or inside the thread loop
2220audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2221{
2222 if (mOutput == NULL) {
2223 return NULL;
2224 }
2225 return &mOutput->stream->common;
2226}
2227
2228uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2229{
2230 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2231}
2232
2233status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2234{
2235 if (!isValidSyncEvent(event)) {
2236 return BAD_VALUE;
2237 }
2238
2239 Mutex::Autolock _l(mLock);
2240
2241 for (size_t i = 0; i < mTracks.size(); ++i) {
2242 sp<Track> track = mTracks[i];
2243 if (event->triggerSession() == track->sessionId()) {
2244 (void) track->setSyncEvent(event);
2245 return NO_ERROR;
2246 }
2247 }
2248
2249 return NAME_NOT_FOUND;
2250}
2251
2252bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2253{
2254 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2255}
2256
2257void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2258 const Vector< sp<Track> >& tracksToRemove)
2259{
2260 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002261 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002262 for (size_t i = 0 ; i < count ; i++) {
2263 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002264 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002265 AudioSystem::stopOutput(mId, track->streamType(),
2266 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002267#ifdef ADD_BATTERY_DATA
2268 // to track the speaker usage
2269 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2270#endif
2271 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002272 AudioSystem::releaseOutput(mId, track->streamType(),
2273 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274 }
Eric Laurent81784c32012-11-19 14:55:58 -08002275 }
2276 }
2277 }
Eric Laurent81784c32012-11-19 14:55:58 -08002278}
2279
2280void AudioFlinger::PlaybackThread::checkSilentMode_l()
2281{
2282 if (!mMasterMute) {
2283 char value[PROPERTY_VALUE_MAX];
2284 if (property_get("ro.audio.silent", value, "0") > 0) {
2285 char *endptr;
2286 unsigned long ul = strtoul(value, &endptr, 0);
2287 if (*endptr == '\0' && ul != 0) {
2288 ALOGD("Silence is golden");
2289 // The setprop command will not allow a property to be changed after
2290 // the first time it is set, so we don't have to worry about un-muting.
2291 setMasterMute_l(true);
2292 }
2293 }
2294 }
2295}
2296
2297// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002298ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002299{
2300 // FIXME rewrite to reduce number of system calls
2301 mLastWriteTime = systemTime();
2302 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002304 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002305
2306 // If an NBAIO sink is present, use it to write the normal mixer's submix
2307 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002308
Andy Hung010a1a12014-03-13 13:57:33 -07002309 const size_t count = mBytesRemaining / mFrameSize;
2310
Simon Wilson2d590962012-11-29 15:18:50 -08002311 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002312 // update the setpoint when AudioFlinger::mScreenState changes
2313 uint32_t screenState = AudioFlinger::mScreenState;
2314 if (screenState != mScreenState) {
2315 mScreenState = screenState;
2316 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2317 if (pipe != NULL) {
2318 pipe->setAvgFrames((mScreenState & 1) ?
2319 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2320 }
2321 }
Andy Hung010a1a12014-03-13 13:57:33 -07002322 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002323 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002324 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002325 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002326 } else {
2327 bytesWritten = framesWritten;
2328 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002329 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002330 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002331 if (status == NO_ERROR) {
2332 size_t totalFramesWritten = mNormalSink->framesWritten();
2333 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2334 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002335 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002336 mLatchDValid = true;
2337 }
2338 }
Eric Laurent81784c32012-11-19 14:55:58 -08002339 // otherwise use the HAL / AudioStreamOut directly
2340 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002341 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002342
Eric Laurentbfb1b832013-01-07 09:53:42 -08002343 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002344 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2345 mWriteAckSequence += 2;
2346 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002347 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002348 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002349 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002350 // FIXME We should have an implementation of timestamps for direct output threads.
2351 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002353 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 if (mUseAsyncWrite &&
2355 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2356 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002357 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002358 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002359 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002360 }
Eric Laurent81784c32012-11-19 14:55:58 -08002361 }
2362
Eric Laurent81784c32012-11-19 14:55:58 -08002363 mNumWrites++;
2364 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002365 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366 return bytesWritten;
2367}
2368
2369void AudioFlinger::PlaybackThread::threadLoop_drain()
2370{
2371 if (mOutput->stream->drain) {
2372 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2373 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002374 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2375 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002377 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 }
2379 mOutput->stream->drain(mOutput->stream,
2380 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2381 : AUDIO_DRAIN_ALL);
2382 }
2383}
2384
2385void AudioFlinger::PlaybackThread::threadLoop_exit()
2386{
Eric Laurent275e8e92014-11-30 15:14:47 -08002387 {
2388 Mutex::Autolock _l(mLock);
2389 for (size_t i = 0; i < mTracks.size(); i++) {
2390 sp<Track> track = mTracks[i];
2391 track->invalidate();
2392 }
2393 }
Eric Laurent81784c32012-11-19 14:55:58 -08002394}
2395
2396/*
2397The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002398 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002399 - activeSleepTime from activeSleepTimeUs()
2400 - idleSleepTime from idleSleepTimeUs()
2401 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2402 - maxPeriod from frame count and sample rate (MIXER only)
2403
2404The parameters that affect these derived values are:
2405 - frame count
2406 - frame size
2407 - sample rate
2408 - device type: A2DP or not
2409 - device latency
2410 - format: PCM or not
2411 - active sleep time
2412 - idle sleep time
2413*/
2414
2415void AudioFlinger::PlaybackThread::cacheParameters_l()
2416{
Andy Hung25c2dac2014-02-27 14:56:00 -08002417 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002418 activeSleepTime = activeSleepTimeUs();
2419 idleSleepTime = idleSleepTimeUs();
2420}
2421
2422void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2423{
Glenn Kasten7c027242012-12-26 14:43:16 -08002424 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002425 this, streamType, mTracks.size());
2426 Mutex::Autolock _l(mLock);
2427
2428 size_t size = mTracks.size();
2429 for (size_t i = 0; i < size; i++) {
2430 sp<Track> t = mTracks[i];
2431 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002432 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002433 }
2434 }
2435}
2436
2437status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2438{
2439 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002440 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2441 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002442 bool ownsBuffer = false;
2443
2444 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2445 if (session > 0) {
2446 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002447 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002448 if (mType != DIRECT) {
2449 size_t numSamples = mNormalFrameCount * mChannelCount;
2450 buffer = new int16_t[numSamples];
2451 memset(buffer, 0, numSamples * sizeof(int16_t));
2452 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2453 ownsBuffer = true;
2454 }
2455
2456 // Attach all tracks with same session ID to this chain.
2457 for (size_t i = 0; i < mTracks.size(); ++i) {
2458 sp<Track> track = mTracks[i];
2459 if (session == track->sessionId()) {
2460 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2461 buffer);
2462 track->setMainBuffer(buffer);
2463 chain->incTrackCnt();
2464 }
2465 }
2466
2467 // indicate all active tracks in the chain
2468 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2469 sp<Track> track = mActiveTracks[i].promote();
2470 if (track == 0) {
2471 continue;
2472 }
2473 if (session == track->sessionId()) {
2474 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2475 chain->incActiveTrackCnt();
2476 }
2477 }
2478 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002479 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002480 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002481 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2482 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002483 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2484 // chains list in order to be processed last as it contains output stage effects
2485 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2486 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2487 // after track specific effects and before output stage
2488 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2489 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2490 // Effect chain for other sessions are inserted at beginning of effect
2491 // chains list to be processed before output mix effects. Relative order between other
2492 // sessions is not important
2493 size_t size = mEffectChains.size();
2494 size_t i = 0;
2495 for (i = 0; i < size; i++) {
2496 if (mEffectChains[i]->sessionId() < session) {
2497 break;
2498 }
2499 }
2500 mEffectChains.insertAt(chain, i);
2501 checkSuspendOnAddEffectChain_l(chain);
2502
2503 return NO_ERROR;
2504}
2505
2506size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2507{
2508 int session = chain->sessionId();
2509
2510 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2511
2512 for (size_t i = 0; i < mEffectChains.size(); i++) {
2513 if (chain == mEffectChains[i]) {
2514 mEffectChains.removeAt(i);
2515 // detach all active tracks from the chain
2516 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2517 sp<Track> track = mActiveTracks[i].promote();
2518 if (track == 0) {
2519 continue;
2520 }
2521 if (session == track->sessionId()) {
2522 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2523 chain.get(), session);
2524 chain->decActiveTrackCnt();
2525 }
2526 }
2527
2528 // detach all tracks with same session ID from this chain
2529 for (size_t i = 0; i < mTracks.size(); ++i) {
2530 sp<Track> track = mTracks[i];
2531 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002532 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002533 chain->decTrackCnt();
2534 }
2535 }
2536 break;
2537 }
2538 }
2539 return mEffectChains.size();
2540}
2541
2542status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2543 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2544{
2545 Mutex::Autolock _l(mLock);
2546 return attachAuxEffect_l(track, EffectId);
2547}
2548
2549status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2550 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2551{
2552 status_t status = NO_ERROR;
2553
2554 if (EffectId == 0) {
2555 track->setAuxBuffer(0, NULL);
2556 } else {
2557 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2558 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2559 if (effect != 0) {
2560 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2561 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2562 } else {
2563 status = INVALID_OPERATION;
2564 }
2565 } else {
2566 status = BAD_VALUE;
2567 }
2568 }
2569 return status;
2570}
2571
2572void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2573{
2574 for (size_t i = 0; i < mTracks.size(); ++i) {
2575 sp<Track> track = mTracks[i];
2576 if (track->auxEffectId() == effectId) {
2577 attachAuxEffect_l(track, 0);
2578 }
2579 }
2580}
2581
2582bool AudioFlinger::PlaybackThread::threadLoop()
2583{
2584 Vector< sp<Track> > tracksToRemove;
2585
2586 standbyTime = systemTime();
2587
2588 // MIXER
2589 nsecs_t lastWarning = 0;
2590
2591 // DUPLICATING
2592 // FIXME could this be made local to while loop?
2593 writeFrames = 0;
2594
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002595 int lastGeneration = 0;
2596
Eric Laurent81784c32012-11-19 14:55:58 -08002597 cacheParameters_l();
2598 sleepTime = idleSleepTime;
2599
2600 if (mType == MIXER) {
2601 sleepTimeShift = 0;
2602 }
2603
2604 CpuStats cpuStats;
2605 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2606
2607 acquireWakeLock();
2608
Glenn Kasten9e58b552013-01-18 15:09:48 -08002609 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2610 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2611 // and then that string will be logged at the next convenient opportunity.
2612 const char *logString = NULL;
2613
Eric Laurent664539d2013-09-23 18:24:31 -07002614 checkSilentMode_l();
2615
Eric Laurent81784c32012-11-19 14:55:58 -08002616 while (!exitPending())
2617 {
2618 cpuStats.sample(myName);
2619
2620 Vector< sp<EffectChain> > effectChains;
2621
Eric Laurent81784c32012-11-19 14:55:58 -08002622 { // scope for mLock
2623
2624 Mutex::Autolock _l(mLock);
2625
Eric Laurent021cf962014-05-13 10:18:14 -07002626 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002627
Glenn Kasten9e58b552013-01-18 15:09:48 -08002628 if (logString != NULL) {
2629 mNBLogWriter->logTimestamp();
2630 mNBLogWriter->log(logString);
2631 logString = NULL;
2632 }
2633
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002634 // Gather the framesReleased counters for all active tracks,
2635 // and latch them atomically with the timestamp.
2636 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2637 mLatchD.mFramesReleased.clear();
2638 size_t size = mActiveTracks.size();
2639 for (size_t i = 0; i < size; i++) {
2640 sp<Track> t = mActiveTracks[i].promote();
2641 if (t != 0) {
2642 mLatchD.mFramesReleased.add(t.get(),
2643 t->mAudioTrackServerProxy->framesReleased());
2644 }
2645 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002646 if (mLatchDValid) {
2647 mLatchQ = mLatchD;
2648 mLatchDValid = false;
2649 mLatchQValid = true;
2650 }
2651
Eric Laurent81784c32012-11-19 14:55:58 -08002652 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 if (mSignalPending) {
2654 // A signal was raised while we were unlocked
2655 mSignalPending = false;
2656 } else if (waitingAsyncCallback_l()) {
2657 if (exitPending()) {
2658 break;
2659 }
2660 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002661 mWakeLockUids.clear();
2662 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 ALOGV("wait async completion");
2664 mWaitWorkCV.wait(mLock);
2665 ALOGV("async completion/wake");
2666 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002667 standbyTime = systemTime() + standbyDelay;
2668 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002669
2670 continue;
2671 }
2672 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 isSuspended()) {
2674 // put audio hardware into standby after short delay
2675 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002676
2677 threadLoop_standby();
2678
2679 mStandby = true;
2680 }
2681
2682 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2683 // we're about to wait, flush the binder command buffer
2684 IPCThreadState::self()->flushCommands();
2685
2686 clearOutputTracks();
2687
2688 if (exitPending()) {
2689 break;
2690 }
2691
2692 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002693 mWakeLockUids.clear();
2694 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002695 // wait until we have something to do...
2696 ALOGV("%s going to sleep", myName.string());
2697 mWaitWorkCV.wait(mLock);
2698 ALOGV("%s waking up", myName.string());
2699 acquireWakeLock_l();
2700
2701 mMixerStatus = MIXER_IDLE;
2702 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2703 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002704 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002705 checkSilentMode_l();
2706
2707 standbyTime = systemTime() + standbyDelay;
2708 sleepTime = idleSleepTime;
2709 if (mType == MIXER) {
2710 sleepTimeShift = 0;
2711 }
2712
2713 continue;
2714 }
2715 }
Eric Laurent81784c32012-11-19 14:55:58 -08002716 // mMixerStatusIgnoringFastTracks is also updated internally
2717 mMixerStatus = prepareTracks_l(&tracksToRemove);
2718
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002719 // compare with previously applied list
2720 if (lastGeneration != mActiveTracksGeneration) {
2721 // update wakelock
2722 updateWakeLockUids_l(mWakeLockUids);
2723 lastGeneration = mActiveTracksGeneration;
2724 }
2725
Eric Laurent81784c32012-11-19 14:55:58 -08002726 // prevent any changes in effect chain list and in each effect chain
2727 // during mixing and effect process as the audio buffers could be deleted
2728 // or modified if an effect is created or deleted
2729 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002730 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002731
Eric Laurentbfb1b832013-01-07 09:53:42 -08002732 if (mBytesRemaining == 0) {
2733 mCurrentWriteLength = 0;
2734 if (mMixerStatus == MIXER_TRACKS_READY) {
2735 // threadLoop_mix() sets mCurrentWriteLength
2736 threadLoop_mix();
2737 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2738 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2739 // threadLoop_sleepTime sets sleepTime to 0 if data
2740 // must be written to HAL
2741 threadLoop_sleepTime();
2742 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002743 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002744 }
2745 }
Andy Hung98ef9782014-03-04 14:46:50 -08002746 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2747 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2748 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2749 // or mSinkBuffer (if there are no effects).
2750 //
2751 // This is done pre-effects computation; if effects change to
2752 // support higher precision, this needs to move.
2753 //
2754 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2755 // TODO use sleepTime == 0 as an additional condition.
2756 if (mMixerBufferValid) {
2757 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2758 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2759
2760 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2761 mNormalFrameCount * mChannelCount);
2762 }
2763
Eric Laurentbfb1b832013-01-07 09:53:42 -08002764 mBytesRemaining = mCurrentWriteLength;
2765 if (isSuspended()) {
2766 sleepTime = suspendSleepTimeUs();
2767 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002768 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769 mBytesRemaining = 0;
2770 }
Eric Laurent81784c32012-11-19 14:55:58 -08002771
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002773 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774 for (size_t i = 0; i < effectChains.size(); i ++) {
2775 effectChains[i]->process_l();
2776 }
Eric Laurent81784c32012-11-19 14:55:58 -08002777 }
2778 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002779 // Process effect chains for offloaded thread even if no audio
2780 // was read from audio track: process only updates effect state
2781 // and thus does have to be synchronized with audio writes but may have
2782 // to be called while waiting for async write callback
2783 if (mType == OFFLOAD) {
2784 for (size_t i = 0; i < effectChains.size(); i ++) {
2785 effectChains[i]->process_l();
2786 }
2787 }
Eric Laurent81784c32012-11-19 14:55:58 -08002788
Andy Hung98ef9782014-03-04 14:46:50 -08002789 // Only if the Effects buffer is enabled and there is data in the
2790 // Effects buffer (buffer valid), we need to
2791 // copy into the sink buffer.
2792 // TODO use sleepTime == 0 as an additional condition.
2793 if (mEffectBufferValid) {
2794 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2795 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2796 mNormalFrameCount * mChannelCount);
2797 }
2798
Eric Laurent81784c32012-11-19 14:55:58 -08002799 // enable changes in effect chain
2800 unlockEffectChains(effectChains);
2801
Eric Laurentbfb1b832013-01-07 09:53:42 -08002802 if (!waitingAsyncCallback()) {
2803 // sleepTime == 0 means we must write to audio hardware
2804 if (sleepTime == 0) {
2805 if (mBytesRemaining) {
2806 ssize_t ret = threadLoop_write();
2807 if (ret < 0) {
2808 mBytesRemaining = 0;
2809 } else {
2810 mBytesWritten += ret;
2811 mBytesRemaining -= ret;
2812 }
2813 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2814 (mMixerStatus == MIXER_DRAIN_ALL)) {
2815 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002816 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002817 if (mType == MIXER) {
2818 // write blocked detection
2819 nsecs_t now = systemTime();
2820 nsecs_t delta = now - mLastWriteTime;
2821 if (!mStandby && delta > maxPeriod) {
2822 mNumDelayedWrites++;
2823 if ((now - lastWarning) > kWarningThrottleNs) {
2824 ATRACE_NAME("underrun");
2825 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2826 ns2ms(delta), mNumDelayedWrites, this);
2827 lastWarning = now;
2828 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002829 }
2830 }
Eric Laurent81784c32012-11-19 14:55:58 -08002831
Eric Laurentbfb1b832013-01-07 09:53:42 -08002832 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002833 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002834 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002835 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002836 }
Eric Laurent81784c32012-11-19 14:55:58 -08002837 }
2838
2839 // Finally let go of removed track(s), without the lock held
2840 // since we can't guarantee the destructors won't acquire that
2841 // same lock. This will also mutate and push a new fast mixer state.
2842 threadLoop_removeTracks(tracksToRemove);
2843 tracksToRemove.clear();
2844
2845 // FIXME I don't understand the need for this here;
2846 // it was in the original code but maybe the
2847 // assignment in saveOutputTracks() makes this unnecessary?
2848 clearOutputTracks();
2849
2850 // Effect chains will be actually deleted here if they were removed from
2851 // mEffectChains list during mixing or effects processing
2852 effectChains.clear();
2853
2854 // FIXME Note that the above .clear() is no longer necessary since effectChains
2855 // is now local to this block, but will keep it for now (at least until merge done).
2856 }
2857
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 threadLoop_exit();
2859
Eric Laurentcf817a22014-08-04 20:36:31 -07002860 if (!mStandby) {
2861 threadLoop_standby();
2862 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002863 }
2864
2865 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002866 mWakeLockUids.clear();
2867 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002868
2869 ALOGV("Thread %p type %d exiting", this, mType);
2870 return false;
2871}
2872
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873// removeTracks_l() must be called with ThreadBase::mLock held
2874void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2875{
2876 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002877 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 for (size_t i=0 ; i<count ; i++) {
2879 const sp<Track>& track = tracksToRemove.itemAt(i);
2880 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002881 mWakeLockUids.remove(track->uid());
2882 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2884 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2885 if (chain != 0) {
2886 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2887 track->sessionId());
2888 chain->decActiveTrackCnt();
2889 }
2890 if (track->isTerminated()) {
2891 removeTrack_l(track);
2892 }
2893 }
2894 }
2895
2896}
Eric Laurent81784c32012-11-19 14:55:58 -08002897
Eric Laurentaccc1472013-09-20 09:36:34 -07002898status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2899{
2900 if (mNormalSink != 0) {
2901 return mNormalSink->getTimestamp(timestamp);
2902 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002903 if ((mType == OFFLOAD || mType == DIRECT)
2904 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002905 uint64_t position64;
2906 int ret = mOutput->stream->get_presentation_position(
2907 mOutput->stream, &position64, &timestamp.mTime);
2908 if (ret == 0) {
2909 timestamp.mPosition = (uint32_t)position64;
2910 return NO_ERROR;
2911 }
2912 }
2913 return INVALID_OPERATION;
2914}
Eric Laurent1c333e22014-05-20 10:48:17 -07002915
2916status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2917 audio_patch_handle_t *handle)
2918{
2919 status_t status = NO_ERROR;
2920 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2921 // store new device and send to effects
2922 audio_devices_t type = AUDIO_DEVICE_NONE;
2923 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2924 type |= patch->sinks[i].ext.device.type;
2925 }
2926 mOutDevice = type;
2927 for (size_t i = 0; i < mEffectChains.size(); i++) {
2928 mEffectChains[i]->setDevice_l(mOutDevice);
2929 }
2930
2931 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2932 status = hwDevice->create_audio_patch(hwDevice,
2933 patch->num_sources,
2934 patch->sources,
2935 patch->num_sinks,
2936 patch->sinks,
2937 handle);
2938 } else {
2939 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2940 }
2941 return status;
2942}
2943
2944status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2945{
2946 status_t status = NO_ERROR;
2947 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2948 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2949 status = hwDevice->release_audio_patch(hwDevice, handle);
2950 } else {
2951 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2952 }
2953 return status;
2954}
2955
Eric Laurent83b88082014-06-20 18:31:16 -07002956void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2957{
2958 Mutex::Autolock _l(mLock);
2959 mTracks.add(track);
2960}
2961
2962void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2963{
2964 Mutex::Autolock _l(mLock);
2965 destroyTrack_l(track);
2966}
2967
2968void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2969{
2970 ThreadBase::getAudioPortConfig(config);
2971 config->role = AUDIO_PORT_ROLE_SOURCE;
2972 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2973 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2974}
2975
Eric Laurent81784c32012-11-19 14:55:58 -08002976// ----------------------------------------------------------------------------
2977
2978AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2979 audio_io_handle_t id, audio_devices_t device, type_t type)
2980 : PlaybackThread(audioFlinger, output, id, device, type),
2981 // mAudioMixer below
2982 // mFastMixer below
2983 mFastMixerFutex(0)
2984 // mOutputSink below
2985 // mPipeSink below
2986 // mNormalSink below
2987{
2988 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002989 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002990 "mFrameCount=%d, mNormalFrameCount=%d",
2991 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2992 mNormalFrameCount);
2993 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2994
Andy Hungfbfc3952015-01-15 13:33:51 -08002995 if (type == DUPLICATING) {
2996 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
2997 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
2998 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
2999 return;
3000 }
Eric Laurent81784c32012-11-19 14:55:58 -08003001 // create an NBAIO sink for the HAL output stream, and negotiate
3002 mOutputSink = new AudioStreamOutSink(output->stream);
3003 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003004 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003005 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3006 ALOG_ASSERT(index == 0);
3007
3008 // initialize fast mixer depending on configuration
3009 bool initFastMixer;
3010 switch (kUseFastMixer) {
3011 case FastMixer_Never:
3012 initFastMixer = false;
3013 break;
3014 case FastMixer_Always:
3015 initFastMixer = true;
3016 break;
3017 case FastMixer_Static:
3018 case FastMixer_Dynamic:
3019 initFastMixer = mFrameCount < mNormalFrameCount;
3020 break;
3021 }
3022 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003023 audio_format_t fastMixerFormat;
3024 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3025 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3026 } else {
3027 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3028 }
3029 if (mFormat != fastMixerFormat) {
3030 // change our Sink format to accept our intermediate precision
3031 mFormat = fastMixerFormat;
3032 free(mSinkBuffer);
3033 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3034 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3035 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3036 }
Eric Laurent81784c32012-11-19 14:55:58 -08003037
3038 // create a MonoPipe to connect our submix to FastMixer
3039 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003040 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003041 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003042 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003043 format.mFormat = fastMixerFormat;
3044 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3045
Eric Laurent81784c32012-11-19 14:55:58 -08003046 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3047 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3048 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3049 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3050 const NBAIO_Format offers[1] = {format};
3051 size_t numCounterOffers = 0;
3052 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3053 ALOG_ASSERT(index == 0);
3054 monoPipe->setAvgFrames((mScreenState & 1) ?
3055 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3056 mPipeSink = monoPipe;
3057
Glenn Kasten46909e72013-02-26 09:20:22 -08003058#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003059 if (mTeeSinkOutputEnabled) {
3060 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003061 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3062 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003063 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003064 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003065 ALOG_ASSERT(index == 0);
3066 mTeeSink = teeSink;
3067 PipeReader *teeSource = new PipeReader(*teeSink);
3068 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003069 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003070 ALOG_ASSERT(index == 0);
3071 mTeeSource = teeSource;
3072 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003073#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003074
3075 // create fast mixer and configure it initially with just one fast track for our submix
3076 mFastMixer = new FastMixer();
3077 FastMixerStateQueue *sq = mFastMixer->sq();
3078#ifdef STATE_QUEUE_DUMP
3079 sq->setObserverDump(&mStateQueueObserverDump);
3080 sq->setMutatorDump(&mStateQueueMutatorDump);
3081#endif
3082 FastMixerState *state = sq->begin();
3083 FastTrack *fastTrack = &state->mFastTracks[0];
3084 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3085 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3086 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003087 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3088 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003089 fastTrack->mGeneration++;
3090 state->mFastTracksGen++;
3091 state->mTrackMask = 1;
3092 // fast mixer will use the HAL output sink
3093 state->mOutputSink = mOutputSink.get();
3094 state->mOutputSinkGen++;
3095 state->mFrameCount = mFrameCount;
3096 state->mCommand = FastMixerState::COLD_IDLE;
3097 // already done in constructor initialization list
3098 //mFastMixerFutex = 0;
3099 state->mColdFutexAddr = &mFastMixerFutex;
3100 state->mColdGen++;
3101 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003102#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003103 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003104#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003105 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3106 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003107 sq->end();
3108 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3109
3110 // start the fast mixer
3111 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3112 pid_t tid = mFastMixer->getTid();
3113 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3114 if (err != 0) {
3115 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3116 kPriorityFastMixer, getpid_cached, tid, err);
3117 }
3118
3119#ifdef AUDIO_WATCHDOG
3120 // create and start the watchdog
3121 mAudioWatchdog = new AudioWatchdog();
3122 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3123 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3124 tid = mAudioWatchdog->getTid();
3125 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3126 if (err != 0) {
3127 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3128 kPriorityFastMixer, getpid_cached, tid, err);
3129 }
3130#endif
3131
Eric Laurent81784c32012-11-19 14:55:58 -08003132 }
3133
3134 switch (kUseFastMixer) {
3135 case FastMixer_Never:
3136 case FastMixer_Dynamic:
3137 mNormalSink = mOutputSink;
3138 break;
3139 case FastMixer_Always:
3140 mNormalSink = mPipeSink;
3141 break;
3142 case FastMixer_Static:
3143 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3144 break;
3145 }
3146}
3147
3148AudioFlinger::MixerThread::~MixerThread()
3149{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003150 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003151 FastMixerStateQueue *sq = mFastMixer->sq();
3152 FastMixerState *state = sq->begin();
3153 if (state->mCommand == FastMixerState::COLD_IDLE) {
3154 int32_t old = android_atomic_inc(&mFastMixerFutex);
3155 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003156 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003157 }
3158 }
3159 state->mCommand = FastMixerState::EXIT;
3160 sq->end();
3161 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3162 mFastMixer->join();
3163 // Though the fast mixer thread has exited, it's state queue is still valid.
3164 // We'll use that extract the final state which contains one remaining fast track
3165 // corresponding to our sub-mix.
3166 state = sq->begin();
3167 ALOG_ASSERT(state->mTrackMask == 1);
3168 FastTrack *fastTrack = &state->mFastTracks[0];
3169 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3170 delete fastTrack->mBufferProvider;
3171 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003172 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003173#ifdef AUDIO_WATCHDOG
3174 if (mAudioWatchdog != 0) {
3175 mAudioWatchdog->requestExit();
3176 mAudioWatchdog->requestExitAndWait();
3177 mAudioWatchdog.clear();
3178 }
3179#endif
3180 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003181 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003182 delete mAudioMixer;
3183}
3184
3185
3186uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3187{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003188 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003189 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3190 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3191 }
3192 return latency;
3193}
3194
3195
3196void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3197{
3198 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3199}
3200
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003202{
3203 // FIXME we should only do one push per cycle; confirm this is true
3204 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003205 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003206 FastMixerStateQueue *sq = mFastMixer->sq();
3207 FastMixerState *state = sq->begin();
3208 if (state->mCommand != FastMixerState::MIX_WRITE &&
3209 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3210 if (state->mCommand == FastMixerState::COLD_IDLE) {
3211 int32_t old = android_atomic_inc(&mFastMixerFutex);
3212 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003213 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003214 }
3215#ifdef AUDIO_WATCHDOG
3216 if (mAudioWatchdog != 0) {
3217 mAudioWatchdog->resume();
3218 }
3219#endif
3220 }
3221 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003222#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003223 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003224 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003225#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003226 sq->end();
3227 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3228 if (kUseFastMixer == FastMixer_Dynamic) {
3229 mNormalSink = mPipeSink;
3230 }
3231 } else {
3232 sq->end(false /*didModify*/);
3233 }
3234 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003235 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003236}
3237
3238void AudioFlinger::MixerThread::threadLoop_standby()
3239{
3240 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003241 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003242 FastMixerStateQueue *sq = mFastMixer->sq();
3243 FastMixerState *state = sq->begin();
3244 if (!(state->mCommand & FastMixerState::IDLE)) {
3245 state->mCommand = FastMixerState::COLD_IDLE;
3246 state->mColdFutexAddr = &mFastMixerFutex;
3247 state->mColdGen++;
3248 mFastMixerFutex = 0;
3249 sq->end();
3250 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3251 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3252 if (kUseFastMixer == FastMixer_Dynamic) {
3253 mNormalSink = mOutputSink;
3254 }
3255#ifdef AUDIO_WATCHDOG
3256 if (mAudioWatchdog != 0) {
3257 mAudioWatchdog->pause();
3258 }
3259#endif
3260 } else {
3261 sq->end(false /*didModify*/);
3262 }
3263 }
3264 PlaybackThread::threadLoop_standby();
3265}
3266
Eric Laurentbfb1b832013-01-07 09:53:42 -08003267bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3268{
3269 return false;
3270}
3271
3272bool AudioFlinger::PlaybackThread::shouldStandby_l()
3273{
3274 return !mStandby;
3275}
3276
3277bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3278{
3279 Mutex::Autolock _l(mLock);
3280 return waitingAsyncCallback_l();
3281}
3282
Eric Laurent81784c32012-11-19 14:55:58 -08003283// shared by MIXER and DIRECT, overridden by DUPLICATING
3284void AudioFlinger::PlaybackThread::threadLoop_standby()
3285{
3286 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3287 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003288 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003289 // discard any pending drain or write ack by incrementing sequence
3290 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3291 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003292 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003293 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3294 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003296 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003297}
3298
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003299void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3300{
3301 ALOGV("signal playback thread");
3302 broadcast_l();
3303}
3304
Eric Laurent81784c32012-11-19 14:55:58 -08003305void AudioFlinger::MixerThread::threadLoop_mix()
3306{
3307 // obtain the presentation timestamp of the next output buffer
3308 int64_t pts;
3309 status_t status = INVALID_OPERATION;
3310
3311 if (mNormalSink != 0) {
3312 status = mNormalSink->getNextWriteTimestamp(&pts);
3313 } else {
3314 status = mOutputSink->getNextWriteTimestamp(&pts);
3315 }
3316
3317 if (status != NO_ERROR) {
3318 pts = AudioBufferProvider::kInvalidPTS;
3319 }
3320
3321 // mix buffers...
3322 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003323 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003324 // increase sleep time progressively when application underrun condition clears.
3325 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3326 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3327 // such that we would underrun the audio HAL.
3328 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3329 sleepTimeShift--;
3330 }
3331 sleepTime = 0;
3332 standbyTime = systemTime() + standbyDelay;
3333 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003334
Eric Laurent81784c32012-11-19 14:55:58 -08003335}
3336
3337void AudioFlinger::MixerThread::threadLoop_sleepTime()
3338{
3339 // If no tracks are ready, sleep once for the duration of an output
3340 // buffer size, then write 0s to the output
3341 if (sleepTime == 0) {
3342 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3343 sleepTime = activeSleepTime >> sleepTimeShift;
3344 if (sleepTime < kMinThreadSleepTimeUs) {
3345 sleepTime = kMinThreadSleepTimeUs;
3346 }
3347 // reduce sleep time in case of consecutive application underruns to avoid
3348 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3349 // duration we would end up writing less data than needed by the audio HAL if
3350 // the condition persists.
3351 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3352 sleepTimeShift++;
3353 }
3354 } else {
3355 sleepTime = idleSleepTime;
3356 }
3357 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003358 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3359 // before effects processing or output.
3360 if (mMixerBufferValid) {
3361 memset(mMixerBuffer, 0, mMixerBufferSize);
3362 } else {
3363 memset(mSinkBuffer, 0, mSinkBufferSize);
3364 }
Eric Laurent81784c32012-11-19 14:55:58 -08003365 sleepTime = 0;
3366 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3367 "anticipated start");
3368 }
3369 // TODO add standby time extension fct of effect tail
3370}
3371
3372// prepareTracks_l() must be called with ThreadBase::mLock held
3373AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3374 Vector< sp<Track> > *tracksToRemove)
3375{
3376
3377 mixer_state mixerStatus = MIXER_IDLE;
3378 // find out which tracks need to be processed
3379 size_t count = mActiveTracks.size();
3380 size_t mixedTracks = 0;
3381 size_t tracksWithEffect = 0;
3382 // counts only _active_ fast tracks
3383 size_t fastTracks = 0;
3384 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3385
3386 float masterVolume = mMasterVolume;
3387 bool masterMute = mMasterMute;
3388
3389 if (masterMute) {
3390 masterVolume = 0;
3391 }
3392 // Delegate master volume control to effect in output mix effect chain if needed
3393 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3394 if (chain != 0) {
3395 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3396 chain->setVolume_l(&v, &v);
3397 masterVolume = (float)((v + (1 << 23)) >> 24);
3398 chain.clear();
3399 }
3400
3401 // prepare a new state to push
3402 FastMixerStateQueue *sq = NULL;
3403 FastMixerState *state = NULL;
3404 bool didModify = false;
3405 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003406 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003407 sq = mFastMixer->sq();
3408 state = sq->begin();
3409 }
3410
Andy Hung69aed5f2014-02-25 17:24:40 -08003411 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003412 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003413
Eric Laurent81784c32012-11-19 14:55:58 -08003414 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003415 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003416 if (t == 0) {
3417 continue;
3418 }
3419
3420 // this const just means the local variable doesn't change
3421 Track* const track = t.get();
3422
3423 // process fast tracks
3424 if (track->isFastTrack()) {
3425
3426 // It's theoretically possible (though unlikely) for a fast track to be created
3427 // and then removed within the same normal mix cycle. This is not a problem, as
3428 // the track never becomes active so it's fast mixer slot is never touched.
3429 // The converse, of removing an (active) track and then creating a new track
3430 // at the identical fast mixer slot within the same normal mix cycle,
3431 // is impossible because the slot isn't marked available until the end of each cycle.
3432 int j = track->mFastIndex;
3433 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3434 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3435 FastTrack *fastTrack = &state->mFastTracks[j];
3436
3437 // Determine whether the track is currently in underrun condition,
3438 // and whether it had a recent underrun.
3439 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3440 FastTrackUnderruns underruns = ftDump->mUnderruns;
3441 uint32_t recentFull = (underruns.mBitFields.mFull -
3442 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3443 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3444 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3445 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3446 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3447 uint32_t recentUnderruns = recentPartial + recentEmpty;
3448 track->mObservedUnderruns = underruns;
3449 // don't count underruns that occur while stopping or pausing
3450 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003451 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3452 recentUnderruns > 0) {
3453 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3454 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003455 }
3456
3457 // This is similar to the state machine for normal tracks,
3458 // with a few modifications for fast tracks.
3459 bool isActive = true;
3460 switch (track->mState) {
3461 case TrackBase::STOPPING_1:
3462 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003463 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003464 track->mState = TrackBase::STOPPING_2;
3465 }
3466 break;
3467 case TrackBase::PAUSING:
3468 // ramp down is not yet implemented
3469 track->setPaused();
3470 break;
3471 case TrackBase::RESUMING:
3472 // ramp up is not yet implemented
3473 track->mState = TrackBase::ACTIVE;
3474 break;
3475 case TrackBase::ACTIVE:
3476 if (recentFull > 0 || recentPartial > 0) {
3477 // track has provided at least some frames recently: reset retry count
3478 track->mRetryCount = kMaxTrackRetries;
3479 }
3480 if (recentUnderruns == 0) {
3481 // no recent underruns: stay active
3482 break;
3483 }
3484 // there has recently been an underrun of some kind
3485 if (track->sharedBuffer() == 0) {
3486 // were any of the recent underruns "empty" (no frames available)?
3487 if (recentEmpty == 0) {
3488 // no, then ignore the partial underruns as they are allowed indefinitely
3489 break;
3490 }
3491 // there has recently been an "empty" underrun: decrement the retry counter
3492 if (--(track->mRetryCount) > 0) {
3493 break;
3494 }
3495 // indicate to client process that the track was disabled because of underrun;
3496 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003497 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003498 // remove from active list, but state remains ACTIVE [confusing but true]
3499 isActive = false;
3500 break;
3501 }
3502 // fall through
3503 case TrackBase::STOPPING_2:
3504 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003505 case TrackBase::STOPPED:
3506 case TrackBase::FLUSHED: // flush() while active
3507 // Check for presentation complete if track is inactive
3508 // We have consumed all the buffers of this track.
3509 // This would be incomplete if we auto-paused on underrun
3510 {
3511 size_t audioHALFrames =
3512 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3513 size_t framesWritten = mBytesWritten / mFrameSize;
3514 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3515 // track stays in active list until presentation is complete
3516 break;
3517 }
3518 }
3519 if (track->isStopping_2()) {
3520 track->mState = TrackBase::STOPPED;
3521 }
3522 if (track->isStopped()) {
3523 // Can't reset directly, as fast mixer is still polling this track
3524 // track->reset();
3525 // So instead mark this track as needing to be reset after push with ack
3526 resetMask |= 1 << i;
3527 }
3528 isActive = false;
3529 break;
3530 case TrackBase::IDLE:
3531 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003532 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003533 }
3534
3535 if (isActive) {
3536 // was it previously inactive?
3537 if (!(state->mTrackMask & (1 << j))) {
3538 ExtendedAudioBufferProvider *eabp = track;
3539 VolumeProvider *vp = track;
3540 fastTrack->mBufferProvider = eabp;
3541 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003542 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003543 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003544 fastTrack->mGeneration++;
3545 state->mTrackMask |= 1 << j;
3546 didModify = true;
3547 // no acknowledgement required for newly active tracks
3548 }
3549 // cache the combined master volume and stream type volume for fast mixer; this
3550 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003551 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003552 ++fastTracks;
3553 } else {
3554 // was it previously active?
3555 if (state->mTrackMask & (1 << j)) {
3556 fastTrack->mBufferProvider = NULL;
3557 fastTrack->mGeneration++;
3558 state->mTrackMask &= ~(1 << j);
3559 didModify = true;
3560 // If any fast tracks were removed, we must wait for acknowledgement
3561 // because we're about to decrement the last sp<> on those tracks.
3562 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3563 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003564 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003565 }
3566 tracksToRemove->add(track);
3567 // Avoids a misleading display in dumpsys
3568 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3569 }
3570 continue;
3571 }
3572
3573 { // local variable scope to avoid goto warning
3574
3575 audio_track_cblk_t* cblk = track->cblk();
3576
3577 // The first time a track is added we wait
3578 // for all its buffers to be filled before processing it
3579 int name = track->name();
3580 // make sure that we have enough frames to mix one full buffer.
3581 // enforce this condition only once to enable draining the buffer in case the client
3582 // app does not call stop() and relies on underrun to stop:
3583 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3584 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003585 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003586 uint32_t sr = track->sampleRate();
3587 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003588 desiredFrames = mNormalFrameCount;
3589 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003590 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003591 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003592 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003593 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003594#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003595 // the minimum track buffer size is normally twice the number of frames necessary
3596 // to fill one buffer and the resampler should not leave more than one buffer worth
3597 // of unreleased frames after each pass, but just in case...
3598 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003599#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003600 }
Eric Laurent81784c32012-11-19 14:55:58 -08003601 uint32_t minFrames = 1;
3602 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3603 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003604 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003605 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003606
3607 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003608 if (ATRACE_ENABLED()) {
3609 // I wish we had formatted trace names
3610 char traceName[16];
3611 strcpy(traceName, "nRdy");
3612 int name = track->name();
3613 if (AudioMixer::TRACK0 <= name &&
3614 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3615 name -= AudioMixer::TRACK0;
3616 traceName[4] = (name / 10) + '0';
3617 traceName[5] = (name % 10) + '0';
3618 } else {
3619 traceName[4] = '?';
3620 traceName[5] = '?';
3621 }
3622 traceName[6] = '\0';
3623 ATRACE_INT(traceName, framesReady);
3624 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003625 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003626 !track->isPaused() && !track->isTerminated())
3627 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003628 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003629
3630 mixedTracks++;
3631
Andy Hung69aed5f2014-02-25 17:24:40 -08003632 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3633 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003634 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003635 if (track->mainBuffer() != mSinkBuffer &&
3636 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003637 if (mEffectBufferEnabled) {
3638 mEffectBufferValid = true; // Later can set directly.
3639 }
Eric Laurent81784c32012-11-19 14:55:58 -08003640 chain = getEffectChain_l(track->sessionId());
3641 // Delegate volume control to effect in track effect chain if needed
3642 if (chain != 0) {
3643 tracksWithEffect++;
3644 } else {
3645 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3646 "session %d",
3647 name, track->sessionId());
3648 }
3649 }
3650
3651
3652 int param = AudioMixer::VOLUME;
3653 if (track->mFillingUpStatus == Track::FS_FILLED) {
3654 // no ramp for the first volume setting
3655 track->mFillingUpStatus = Track::FS_ACTIVE;
3656 if (track->mState == TrackBase::RESUMING) {
3657 track->mState = TrackBase::ACTIVE;
3658 param = AudioMixer::RAMP_VOLUME;
3659 }
3660 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003661 // FIXME should not make a decision based on mServer
3662 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003663 // If the track is stopped before the first frame was mixed,
3664 // do not apply ramp
3665 param = AudioMixer::RAMP_VOLUME;
3666 }
3667
3668 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003669 uint32_t vl, vr; // in U8.24 integer format
3670 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003671 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003672 vl = vr = 0;
3673 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003674 if (track->isPausing()) {
3675 track->setPaused();
3676 }
3677 } else {
3678
3679 // read original volumes with volume control
3680 float typeVolume = mStreamTypes[track->streamType()].volume;
3681 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003682 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003683 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003684 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3685 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003686 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003687 if (vlf > GAIN_FLOAT_UNITY) {
3688 ALOGV("Track left volume out of range: %.3g", vlf);
3689 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003690 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003691 if (vrf > GAIN_FLOAT_UNITY) {
3692 ALOGV("Track right volume out of range: %.3g", vrf);
3693 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003694 }
3695 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003696 vlf *= v;
3697 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003698 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003699 // then derive vl and vr as U8.24 versions for the effect chain
3700 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3701 vl = (uint32_t) (scaleto8_24 * vlf);
3702 vr = (uint32_t) (scaleto8_24 * vrf);
3703 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003704 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003705 // send level comes from shared memory and so may be corrupt
3706 if (sendLevel > MAX_GAIN_INT) {
3707 ALOGV("Track send level out of range: %04X", sendLevel);
3708 sendLevel = MAX_GAIN_INT;
3709 }
Andy Hung6be49402014-05-30 10:42:03 -07003710 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3711 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003712 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003713
Eric Laurent81784c32012-11-19 14:55:58 -08003714 // Delegate volume control to effect in track effect chain if needed
3715 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3716 // Do not ramp volume if volume is controlled by effect
3717 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003718 // Update remaining floating point volume levels
3719 vlf = (float)vl / (1 << 24);
3720 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003721 track->mHasVolumeController = true;
3722 } else {
3723 // force no volume ramp when volume controller was just disabled or removed
3724 // from effect chain to avoid volume spike
3725 if (track->mHasVolumeController) {
3726 param = AudioMixer::VOLUME;
3727 }
3728 track->mHasVolumeController = false;
3729 }
3730
Eric Laurent81784c32012-11-19 14:55:58 -08003731 // XXX: these things DON'T need to be done each time
3732 mAudioMixer->setBufferProvider(name, track);
3733 mAudioMixer->enable(name);
3734
Andy Hung6be49402014-05-30 10:42:03 -07003735 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3736 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3737 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003738 mAudioMixer->setParameter(
3739 name,
3740 AudioMixer::TRACK,
3741 AudioMixer::FORMAT, (void *)track->format());
3742 mAudioMixer->setParameter(
3743 name,
3744 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003745 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003746 mAudioMixer->setParameter(
3747 name,
3748 AudioMixer::TRACK,
3749 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003750 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003751 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003752 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003753 if (reqSampleRate == 0) {
3754 reqSampleRate = mSampleRate;
3755 } else if (reqSampleRate > maxSampleRate) {
3756 reqSampleRate = maxSampleRate;
3757 }
Eric Laurent81784c32012-11-19 14:55:58 -08003758 mAudioMixer->setParameter(
3759 name,
3760 AudioMixer::RESAMPLE,
3761 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003762 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003763 /*
3764 * Select the appropriate output buffer for the track.
3765 *
Andy Hung98ef9782014-03-04 14:46:50 -08003766 * Tracks with effects go into their own effects chain buffer
3767 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003768 *
3769 * Other tracks can use mMixerBuffer for higher precision
3770 * channel accumulation. If this buffer is enabled
3771 * (mMixerBufferEnabled true), then selected tracks will accumulate
3772 * into it.
3773 *
3774 */
3775 if (mMixerBufferEnabled
3776 && (track->mainBuffer() == mSinkBuffer
3777 || track->mainBuffer() == mMixerBuffer)) {
3778 mAudioMixer->setParameter(
3779 name,
3780 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003781 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003782 mAudioMixer->setParameter(
3783 name,
3784 AudioMixer::TRACK,
3785 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3786 // TODO: override track->mainBuffer()?
3787 mMixerBufferValid = true;
3788 } else {
3789 mAudioMixer->setParameter(
3790 name,
3791 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003792 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003793 mAudioMixer->setParameter(
3794 name,
3795 AudioMixer::TRACK,
3796 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3797 }
Eric Laurent81784c32012-11-19 14:55:58 -08003798 mAudioMixer->setParameter(
3799 name,
3800 AudioMixer::TRACK,
3801 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3802
3803 // reset retry count
3804 track->mRetryCount = kMaxTrackRetries;
3805
3806 // If one track is ready, set the mixer ready if:
3807 // - the mixer was not ready during previous round OR
3808 // - no other track is not ready
3809 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3810 mixerStatus != MIXER_TRACKS_ENABLED) {
3811 mixerStatus = MIXER_TRACKS_READY;
3812 }
3813 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003814 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003815 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003816 }
Eric Laurent81784c32012-11-19 14:55:58 -08003817 // clear effect chain input buffer if an active track underruns to avoid sending
3818 // previous audio buffer again to effects
3819 chain = getEffectChain_l(track->sessionId());
3820 if (chain != 0) {
3821 chain->clearInputBuffer();
3822 }
3823
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003824 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003825 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3826 track->isStopped() || track->isPaused()) {
3827 // We have consumed all the buffers of this track.
3828 // Remove it from the list of active tracks.
3829 // TODO: use actual buffer filling status instead of latency when available from
3830 // audio HAL
3831 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3832 size_t framesWritten = mBytesWritten / mFrameSize;
3833 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3834 if (track->isStopped()) {
3835 track->reset();
3836 }
3837 tracksToRemove->add(track);
3838 }
3839 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003840 // No buffers for this track. Give it a few chances to
3841 // fill a buffer, then remove it from active list.
3842 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003843 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003844 tracksToRemove->add(track);
3845 // indicate to client process that the track was disabled because of underrun;
3846 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003847 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003848 // If one track is not ready, mark the mixer also not ready if:
3849 // - the mixer was ready during previous round OR
3850 // - no other track is ready
3851 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3852 mixerStatus != MIXER_TRACKS_READY) {
3853 mixerStatus = MIXER_TRACKS_ENABLED;
3854 }
3855 }
3856 mAudioMixer->disable(name);
3857 }
3858
3859 } // local variable scope to avoid goto warning
3860track_is_ready: ;
3861
3862 }
3863
3864 // Push the new FastMixer state if necessary
3865 bool pauseAudioWatchdog = false;
3866 if (didModify) {
3867 state->mFastTracksGen++;
3868 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3869 if (kUseFastMixer == FastMixer_Dynamic &&
3870 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3871 state->mCommand = FastMixerState::COLD_IDLE;
3872 state->mColdFutexAddr = &mFastMixerFutex;
3873 state->mColdGen++;
3874 mFastMixerFutex = 0;
3875 if (kUseFastMixer == FastMixer_Dynamic) {
3876 mNormalSink = mOutputSink;
3877 }
3878 // If we go into cold idle, need to wait for acknowledgement
3879 // so that fast mixer stops doing I/O.
3880 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3881 pauseAudioWatchdog = true;
3882 }
Eric Laurent81784c32012-11-19 14:55:58 -08003883 }
3884 if (sq != NULL) {
3885 sq->end(didModify);
3886 sq->push(block);
3887 }
3888#ifdef AUDIO_WATCHDOG
3889 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3890 mAudioWatchdog->pause();
3891 }
3892#endif
3893
3894 // Now perform the deferred reset on fast tracks that have stopped
3895 while (resetMask != 0) {
3896 size_t i = __builtin_ctz(resetMask);
3897 ALOG_ASSERT(i < count);
3898 resetMask &= ~(1 << i);
3899 sp<Track> t = mActiveTracks[i].promote();
3900 if (t == 0) {
3901 continue;
3902 }
3903 Track* track = t.get();
3904 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3905 track->reset();
3906 }
3907
3908 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003909 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003910
Eric Laurent97d547d2014-09-02 14:45:53 -07003911 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3912 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003913 }
3914
3915 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003916 // as long as there are effects we should clear the effects buffer, to avoid
3917 // passing a non-clean buffer to the effect chain
3918 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003919 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003920 // sink or mix buffer must be cleared if all tracks are connected to an
3921 // effect chain as in this case the mixer will not write to the sink or mix buffer
3922 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003923 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3924 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003925 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003926 if (mMixerBufferValid) {
3927 memset(mMixerBuffer, 0, mMixerBufferSize);
3928 // TODO: In testing, mSinkBuffer below need not be cleared because
3929 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3930 // after mixing.
3931 //
3932 // To enforce this guarantee:
3933 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3934 // (mixedTracks == 0 && fastTracks > 0))
3935 // must imply MIXER_TRACKS_READY.
3936 // Later, we may clear buffers regardless, and skip much of this logic.
3937 }
Andy Hung98ef9782014-03-04 14:46:50 -08003938 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003939 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003940 }
3941
3942 // if any fast tracks, then status is ready
3943 mMixerStatusIgnoringFastTracks = mixerStatus;
3944 if (fastTracks > 0) {
3945 mixerStatus = MIXER_TRACKS_READY;
3946 }
3947 return mixerStatus;
3948}
3949
3950// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003951int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3952 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003953{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003954 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003955}
3956
3957// deleteTrackName_l() must be called with ThreadBase::mLock held
3958void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3959{
3960 ALOGV("remove track (%d) and delete from mixer", name);
3961 mAudioMixer->deleteTrackName(name);
3962}
3963
Eric Laurent10351942014-05-08 18:49:52 -07003964// checkForNewParameter_l() must be called with ThreadBase::mLock held
3965bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3966 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003967{
Eric Laurent81784c32012-11-19 14:55:58 -08003968 bool reconfig = false;
3969
Eric Laurent10351942014-05-08 18:49:52 -07003970 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003971
Eric Laurent10351942014-05-08 18:49:52 -07003972 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3973 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003974 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003975 FastMixerStateQueue *sq = mFastMixer->sq();
3976 FastMixerState *state = sq->begin();
3977 if (!(state->mCommand & FastMixerState::IDLE)) {
3978 previousCommand = state->mCommand;
3979 state->mCommand = FastMixerState::HOT_IDLE;
3980 sq->end();
3981 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3982 } else {
3983 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003984 }
Eric Laurent10351942014-05-08 18:49:52 -07003985 }
Eric Laurent81784c32012-11-19 14:55:58 -08003986
Eric Laurent10351942014-05-08 18:49:52 -07003987 AudioParameter param = AudioParameter(keyValuePair);
3988 int value;
3989 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3990 reconfig = true;
3991 }
3992 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003993 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003994 status = BAD_VALUE;
3995 } else {
3996 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003997 reconfig = true;
3998 }
Eric Laurent10351942014-05-08 18:49:52 -07003999 }
4000 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004001 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004002 status = BAD_VALUE;
4003 } else {
4004 // no need to save value, since it's constant
4005 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004006 }
Eric Laurent10351942014-05-08 18:49:52 -07004007 }
4008 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4009 // do not accept frame count changes if tracks are open as the track buffer
4010 // size depends on frame count and correct behavior would not be guaranteed
4011 // if frame count is changed after track creation
4012 if (!mTracks.isEmpty()) {
4013 status = INVALID_OPERATION;
4014 } else {
4015 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004016 }
Eric Laurent10351942014-05-08 18:49:52 -07004017 }
4018 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004019#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004020 // when changing the audio output device, call addBatteryData to notify
4021 // the change
4022 if (mOutDevice != value) {
4023 uint32_t params = 0;
4024 // check whether speaker is on
4025 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4026 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004027 }
Eric Laurent10351942014-05-08 18:49:52 -07004028
4029 audio_devices_t deviceWithoutSpeaker
4030 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4031 // check if any other device (except speaker) is on
4032 if (value & deviceWithoutSpeaker ) {
4033 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4034 }
4035
4036 if (params != 0) {
4037 addBatteryData(params);
4038 }
4039 }
Eric Laurent81784c32012-11-19 14:55:58 -08004040#endif
4041
Eric Laurent10351942014-05-08 18:49:52 -07004042 // forward device change to effects that have requested to be
4043 // aware of attached audio device.
4044 if (value != AUDIO_DEVICE_NONE) {
4045 mOutDevice = value;
4046 for (size_t i = 0; i < mEffectChains.size(); i++) {
4047 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004048 }
4049 }
Eric Laurent10351942014-05-08 18:49:52 -07004050 }
Eric Laurent81784c32012-11-19 14:55:58 -08004051
Eric Laurent10351942014-05-08 18:49:52 -07004052 if (status == NO_ERROR) {
4053 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4054 keyValuePair.string());
4055 if (!mStandby && status == INVALID_OPERATION) {
4056 mOutput->stream->common.standby(&mOutput->stream->common);
4057 mStandby = true;
4058 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004059 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004060 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004061 }
Eric Laurent10351942014-05-08 18:49:52 -07004062 if (status == NO_ERROR && reconfig) {
4063 readOutputParameters_l();
4064 delete mAudioMixer;
4065 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4066 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004067 int name = getTrackName_l(mTracks[i]->mChannelMask,
4068 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004069 if (name < 0) {
4070 break;
4071 }
4072 mTracks[i]->mName = name;
4073 }
4074 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4075 }
Eric Laurent81784c32012-11-19 14:55:58 -08004076 }
4077
4078 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004079 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004080 FastMixerStateQueue *sq = mFastMixer->sq();
4081 FastMixerState *state = sq->begin();
4082 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4083 state->mCommand = previousCommand;
4084 sq->end();
4085 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4086 }
4087
4088 return reconfig;
4089}
4090
4091
4092void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4093{
4094 const size_t SIZE = 256;
4095 char buffer[SIZE];
4096 String8 result;
4097
4098 PlaybackThread::dumpInternals(fd, args);
4099
Elliott Hughes87cebad2014-05-22 10:14:43 -07004100 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004101
4102 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004103 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004104 copy.dump(fd);
4105
4106#ifdef STATE_QUEUE_DUMP
4107 // Similar for state queue
4108 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4109 observerCopy.dump(fd);
4110 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4111 mutatorCopy.dump(fd);
4112#endif
4113
Glenn Kasten46909e72013-02-26 09:20:22 -08004114#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004115 // Write the tee output to a .wav file
4116 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004117#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004118
4119#ifdef AUDIO_WATCHDOG
4120 if (mAudioWatchdog != 0) {
4121 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4122 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4123 wdCopy.dump(fd);
4124 }
4125#endif
4126}
4127
4128uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4129{
4130 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4131}
4132
4133uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4134{
4135 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4136}
4137
4138void AudioFlinger::MixerThread::cacheParameters_l()
4139{
4140 PlaybackThread::cacheParameters_l();
4141
4142 // FIXME: Relaxed timing because of a certain device that can't meet latency
4143 // Should be reduced to 2x after the vendor fixes the driver issue
4144 // increase threshold again due to low power audio mode. The way this warning
4145 // threshold is calculated and its usefulness should be reconsidered anyway.
4146 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4147}
4148
4149// ----------------------------------------------------------------------------
4150
4151AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4152 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4153 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4154 // mLeftVolFloat, mRightVolFloat
4155{
4156}
4157
Eric Laurentbfb1b832013-01-07 09:53:42 -08004158AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4159 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4160 ThreadBase::type_t type)
4161 : PlaybackThread(audioFlinger, output, id, device, type)
4162 // mLeftVolFloat, mRightVolFloat
4163{
4164}
4165
Eric Laurent81784c32012-11-19 14:55:58 -08004166AudioFlinger::DirectOutputThread::~DirectOutputThread()
4167{
4168}
4169
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4171{
4172 audio_track_cblk_t* cblk = track->cblk();
4173 float left, right;
4174
4175 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4176 left = right = 0;
4177 } else {
4178 float typeVolume = mStreamTypes[track->streamType()].volume;
4179 float v = mMasterVolume * typeVolume;
4180 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004181 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4182 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4183 if (left > GAIN_FLOAT_UNITY) {
4184 left = GAIN_FLOAT_UNITY;
4185 }
4186 left *= v;
4187 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4188 if (right > GAIN_FLOAT_UNITY) {
4189 right = GAIN_FLOAT_UNITY;
4190 }
4191 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004192 }
4193
4194 if (lastTrack) {
4195 if (left != mLeftVolFloat || right != mRightVolFloat) {
4196 mLeftVolFloat = left;
4197 mRightVolFloat = right;
4198
4199 // Convert volumes from float to 8.24
4200 uint32_t vl = (uint32_t)(left * (1 << 24));
4201 uint32_t vr = (uint32_t)(right * (1 << 24));
4202
4203 // Delegate volume control to effect in track effect chain if needed
4204 // only one effect chain can be present on DirectOutputThread, so if
4205 // there is one, the track is connected to it
4206 if (!mEffectChains.isEmpty()) {
4207 mEffectChains[0]->setVolume_l(&vl, &vr);
4208 left = (float)vl / (1 << 24);
4209 right = (float)vr / (1 << 24);
4210 }
4211 if (mOutput->stream->set_volume) {
4212 mOutput->stream->set_volume(mOutput->stream, left, right);
4213 }
4214 }
4215 }
4216}
4217
4218
Eric Laurent81784c32012-11-19 14:55:58 -08004219AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4220 Vector< sp<Track> > *tracksToRemove
4221)
4222{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004223 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004224 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004225 bool doHwPause = false;
4226 bool doHwResume = false;
4227 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004228
4229 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004230 for (size_t i = 0; i < count; i++) {
4231 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004232 // The track died recently
4233 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004234 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004235 }
4236
4237 Track* const track = t.get();
4238 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004239 // Only consider last track started for volume and mixer state control.
4240 // In theory an older track could underrun and restart after the new one starts
4241 // but as we only care about the transition phase between two tracks on a
4242 // direct output, it is not a problem to ignore the underrun case.
4243 sp<Track> l = mLatestActiveTrack.promote();
4244 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004245
Eric Laurentd1f69b02014-12-15 14:33:13 -08004246 if (mHwSupportsPause && track->isPausing()) {
4247 track->setPaused();
4248 if (last && !mHwPaused) {
4249 doHwPause = true;
4250 mHwPaused = true;
4251 }
4252 tracksToRemove->add(track);
4253 } else if (track->isFlushPending()) {
4254 track->flushAck();
4255 if (last) {
4256 flushPending = true;
4257 }
4258 } else if (mHwSupportsPause && track->isResumePending()){
4259 track->resumeAck();
4260 if (last) {
4261 if (mHwPaused) {
4262 doHwResume = true;
4263 mHwPaused = false;
4264 }
4265 }
4266 }
4267
Eric Laurent81784c32012-11-19 14:55:58 -08004268 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004269 // for all its buffers to be filled before processing it.
4270 // Allow draining the buffer in case the client
4271 // app does not call stop() and relies on underrun to stop:
4272 // hence the test on (track->mRetryCount > 1).
4273 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004274 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004275 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4276 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004277 minFrames = mNormalFrameCount;
4278 } else {
4279 minFrames = 1;
4280 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004281
Eric Laurentab5cdba2014-06-09 17:22:27 -07004282 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4283 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004284 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004285 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004286
4287 if (track->mFillingUpStatus == Track::FS_FILLED) {
4288 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004289 // make sure processVolume_l() will apply new volume even if 0
4290 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004291 if (!mHwSupportsPause) {
4292 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004293 }
4294 }
4295
4296 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004297 processVolume_l(track, last);
4298 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004299 // reset retry count
4300 track->mRetryCount = kMaxTrackRetriesDirect;
4301 mActiveTrack = t;
4302 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004303 if (usesHwAvSync() && mHwPaused) {
4304 doHwResume = true;
4305 mHwPaused = false;
4306 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004307 }
Eric Laurent81784c32012-11-19 14:55:58 -08004308 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004309 // clear effect chain input buffer if the last active track started underruns
4310 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004311 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004312 mEffectChains[0]->clearInputBuffer();
4313 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004314 if (track->isStopping_1()) {
4315 track->mState = TrackBase::STOPPING_2;
4316 }
4317 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4318 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004319 // We have consumed all the buffers of this track.
4320 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004321 size_t audioHALFrames;
4322 if (audio_is_linear_pcm(mFormat)) {
4323 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4324 } else {
4325 audioHALFrames = 0;
4326 }
4327
Eric Laurent81784c32012-11-19 14:55:58 -08004328 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004329 if (mStandby || !last ||
4330 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004331 if (track->isStopping_2()) {
4332 track->mState = TrackBase::STOPPED;
4333 }
Eric Laurent81784c32012-11-19 14:55:58 -08004334 if (track->isStopped()) {
4335 track->reset();
4336 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004337 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004338 }
4339 } else {
4340 // No buffers for this track. Give it a few chances to
4341 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004342 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004343 if (--(track->mRetryCount) <= 0) {
4344 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004345 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004346 // indicate to client process that the track was disabled because of underrun;
4347 // it will then automatically call start() when data is available
4348 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004349 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004350 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004351 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4352 doHwPause = true;
4353 mHwPaused = true;
4354 }
Eric Laurent81784c32012-11-19 14:55:58 -08004355 }
4356 }
4357 }
4358 }
4359
Eric Laurentd1f69b02014-12-15 14:33:13 -08004360 // if an active track did not command a flush, check for pending flush on stopped tracks
4361 if (!flushPending) {
4362 for (size_t i = 0; i < mTracks.size(); i++) {
4363 if (mTracks[i]->isFlushPending()) {
4364 mTracks[i]->flushAck();
4365 flushPending = true;
4366 }
4367 }
4368 }
4369
4370 // make sure the pause/flush/resume sequence is executed in the right order.
4371 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4372 // before flush and then resume HW. This can happen in case of pause/flush/resume
4373 // if resume is received before pause is executed.
4374 if (mHwSupportsPause && !mStandby &&
4375 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4376 mOutput->stream->pause(mOutput->stream);
4377 }
4378 if (flushPending) {
4379 flushHw_l();
4380 }
4381 if (mHwSupportsPause && !mStandby && doHwResume) {
4382 mOutput->stream->resume(mOutput->stream);
4383 }
Eric Laurent81784c32012-11-19 14:55:58 -08004384 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004385 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004386
4387 return mixerStatus;
4388}
4389
4390void AudioFlinger::DirectOutputThread::threadLoop_mix()
4391{
Eric Laurent81784c32012-11-19 14:55:58 -08004392 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004393 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004394 // output audio to hardware
4395 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004396 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004397 buffer.frameCount = frameCount;
4398 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004399 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004400 memset(curBuf, 0, frameCount * mFrameSize);
4401 break;
4402 }
4403 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4404 frameCount -= buffer.frameCount;
4405 curBuf += buffer.frameCount * mFrameSize;
4406 mActiveTrack->releaseBuffer(&buffer);
4407 }
Andy Hung2098f272014-02-27 14:00:06 -08004408 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004409 sleepTime = 0;
4410 standbyTime = systemTime() + standbyDelay;
4411 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004412}
4413
4414void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4415{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004416 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004417 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004418 sleepTime = idleSleepTime;
4419 return;
4420 }
Eric Laurent81784c32012-11-19 14:55:58 -08004421 if (sleepTime == 0) {
4422 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4423 sleepTime = activeSleepTime;
4424 } else {
4425 sleepTime = idleSleepTime;
4426 }
4427 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004428 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004429 sleepTime = 0;
4430 }
4431}
4432
Eric Laurentd1f69b02014-12-15 14:33:13 -08004433void AudioFlinger::DirectOutputThread::threadLoop_exit()
4434{
4435 {
4436 Mutex::Autolock _l(mLock);
4437 bool flushPending = false;
4438 for (size_t i = 0; i < mTracks.size(); i++) {
4439 if (mTracks[i]->isFlushPending()) {
4440 mTracks[i]->flushAck();
4441 flushPending = true;
4442 }
4443 }
4444 if (flushPending) {
4445 flushHw_l();
4446 }
4447 }
4448 PlaybackThread::threadLoop_exit();
4449}
4450
4451// must be called with thread mutex locked
4452bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4453{
4454 bool trackPaused = false;
4455
4456 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4457 // after a timeout and we will enter standby then.
4458 if (mTracks.size() > 0) {
4459 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4460 }
4461
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004462 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004463}
4464
Eric Laurent81784c32012-11-19 14:55:58 -08004465// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004466int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004467 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004468{
4469 return 0;
4470}
4471
4472// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004473void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004474{
4475}
4476
Eric Laurent10351942014-05-08 18:49:52 -07004477// checkForNewParameter_l() must be called with ThreadBase::mLock held
4478bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4479 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004480{
4481 bool reconfig = false;
4482
Eric Laurent10351942014-05-08 18:49:52 -07004483 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004484
Eric Laurent10351942014-05-08 18:49:52 -07004485 AudioParameter param = AudioParameter(keyValuePair);
4486 int value;
4487 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4488 // forward device change to effects that have requested to be
4489 // aware of attached audio device.
4490 if (value != AUDIO_DEVICE_NONE) {
4491 mOutDevice = value;
4492 for (size_t i = 0; i < mEffectChains.size(); i++) {
4493 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004494 }
4495 }
Eric Laurent81784c32012-11-19 14:55:58 -08004496 }
Eric Laurent10351942014-05-08 18:49:52 -07004497 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4498 // do not accept frame count changes if tracks are open as the track buffer
4499 // size depends on frame count and correct behavior would not be garantied
4500 // if frame count is changed after track creation
4501 if (!mTracks.isEmpty()) {
4502 status = INVALID_OPERATION;
4503 } else {
4504 reconfig = true;
4505 }
4506 }
4507 if (status == NO_ERROR) {
4508 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4509 keyValuePair.string());
4510 if (!mStandby && status == INVALID_OPERATION) {
4511 mOutput->stream->common.standby(&mOutput->stream->common);
4512 mStandby = true;
4513 mBytesWritten = 0;
4514 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4515 keyValuePair.string());
4516 }
4517 if (status == NO_ERROR && reconfig) {
4518 readOutputParameters_l();
4519 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4520 }
4521 }
4522
Eric Laurent81784c32012-11-19 14:55:58 -08004523 return reconfig;
4524}
4525
4526uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4527{
4528 uint32_t time;
4529 if (audio_is_linear_pcm(mFormat)) {
4530 time = PlaybackThread::activeSleepTimeUs();
4531 } else {
4532 time = 10000;
4533 }
4534 return time;
4535}
4536
4537uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4538{
4539 uint32_t time;
4540 if (audio_is_linear_pcm(mFormat)) {
4541 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4542 } else {
4543 time = 10000;
4544 }
4545 return time;
4546}
4547
4548uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4549{
4550 uint32_t time;
4551 if (audio_is_linear_pcm(mFormat)) {
4552 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4553 } else {
4554 time = 10000;
4555 }
4556 return time;
4557}
4558
4559void AudioFlinger::DirectOutputThread::cacheParameters_l()
4560{
4561 PlaybackThread::cacheParameters_l();
4562
4563 // use shorter standby delay as on normal output to release
4564 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004565 if (audio_is_linear_pcm(mFormat)) {
4566 standbyDelay = microseconds(activeSleepTime*2);
4567 } else {
4568 standbyDelay = kOffloadStandbyDelayNs;
4569 }
Eric Laurent81784c32012-11-19 14:55:58 -08004570}
4571
Eric Laurente659ef42014-09-29 13:06:46 -07004572void AudioFlinger::DirectOutputThread::flushHw_l()
4573{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004574 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004575 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004576 }
4577 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004578}
4579
Eric Laurent81784c32012-11-19 14:55:58 -08004580// ----------------------------------------------------------------------------
4581
Eric Laurentbfb1b832013-01-07 09:53:42 -08004582AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004583 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004584 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004585 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004586 mWriteAckSequence(0),
4587 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004588{
4589}
4590
4591AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4592{
4593}
4594
4595void AudioFlinger::AsyncCallbackThread::onFirstRef()
4596{
4597 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4598}
4599
4600bool AudioFlinger::AsyncCallbackThread::threadLoop()
4601{
4602 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004603 uint32_t writeAckSequence;
4604 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605
4606 {
4607 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004608 while (!((mWriteAckSequence & 1) ||
4609 (mDrainSequence & 1) ||
4610 exitPending())) {
4611 mWaitWorkCV.wait(mLock);
4612 }
4613
Eric Laurentbfb1b832013-01-07 09:53:42 -08004614 if (exitPending()) {
4615 break;
4616 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004617 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4618 mWriteAckSequence, mDrainSequence);
4619 writeAckSequence = mWriteAckSequence;
4620 mWriteAckSequence &= ~1;
4621 drainSequence = mDrainSequence;
4622 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004623 }
4624 {
Eric Laurent4de95592013-09-26 15:28:21 -07004625 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4626 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004627 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004628 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004629 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004630 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004631 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004632 }
4633 }
4634 }
4635 }
4636 return false;
4637}
4638
4639void AudioFlinger::AsyncCallbackThread::exit()
4640{
4641 ALOGV("AsyncCallbackThread::exit");
4642 Mutex::Autolock _l(mLock);
4643 requestExit();
4644 mWaitWorkCV.broadcast();
4645}
4646
Eric Laurent3b4529e2013-09-05 18:09:19 -07004647void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004648{
4649 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004650 // bit 0 is cleared
4651 mWriteAckSequence = sequence << 1;
4652}
4653
4654void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4655{
4656 Mutex::Autolock _l(mLock);
4657 // ignore unexpected callbacks
4658 if (mWriteAckSequence & 2) {
4659 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004660 mWaitWorkCV.signal();
4661 }
4662}
4663
Eric Laurent3b4529e2013-09-05 18:09:19 -07004664void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004665{
4666 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004667 // bit 0 is cleared
4668 mDrainSequence = sequence << 1;
4669}
4670
4671void AudioFlinger::AsyncCallbackThread::resetDraining()
4672{
4673 Mutex::Autolock _l(mLock);
4674 // ignore unexpected callbacks
4675 if (mDrainSequence & 2) {
4676 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004677 mWaitWorkCV.signal();
4678 }
4679}
4680
4681
4682// ----------------------------------------------------------------------------
4683AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4684 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4685 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004686 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004687{
Eric Laurentfd477972013-10-25 18:10:40 -07004688 //FIXME: mStandby should be set to true by ThreadBase constructor
4689 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004690}
4691
Eric Laurentbfb1b832013-01-07 09:53:42 -08004692void AudioFlinger::OffloadThread::threadLoop_exit()
4693{
4694 if (mFlushPending || mHwPaused) {
4695 // If a flush is pending or track was paused, just discard buffered data
4696 flushHw_l();
4697 } else {
4698 mMixerStatus = MIXER_DRAIN_ALL;
4699 threadLoop_drain();
4700 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004701 if (mUseAsyncWrite) {
4702 ALOG_ASSERT(mCallbackThread != 0);
4703 mCallbackThread->exit();
4704 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 PlaybackThread::threadLoop_exit();
4706}
4707
4708AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4709 Vector< sp<Track> > *tracksToRemove
4710)
4711{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004712 size_t count = mActiveTracks.size();
4713
4714 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004715 bool doHwPause = false;
4716 bool doHwResume = false;
4717
Eric Laurentede6c3b2013-09-19 14:37:46 -07004718 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4719
Eric Laurentbfb1b832013-01-07 09:53:42 -08004720 // find out which tracks need to be processed
4721 for (size_t i = 0; i < count; i++) {
4722 sp<Track> t = mActiveTracks[i].promote();
4723 // The track died recently
4724 if (t == 0) {
4725 continue;
4726 }
4727 Track* const track = t.get();
4728 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004729 // Only consider last track started for volume and mixer state control.
4730 // In theory an older track could underrun and restart after the new one starts
4731 // but as we only care about the transition phase between two tracks on a
4732 // direct output, it is not a problem to ignore the underrun case.
4733 sp<Track> l = mLatestActiveTrack.promote();
4734 bool last = l.get() == track;
4735
Haynes Mathew George7844f672014-01-15 12:32:55 -08004736 if (track->isInvalid()) {
4737 ALOGW("An invalidated track shouldn't be in active list");
4738 tracksToRemove->add(track);
4739 continue;
4740 }
4741
4742 if (track->mState == TrackBase::IDLE) {
4743 ALOGW("An idle track shouldn't be in active list");
4744 continue;
4745 }
4746
Eric Laurentbfb1b832013-01-07 09:53:42 -08004747 if (track->isPausing()) {
4748 track->setPaused();
4749 if (last) {
4750 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004751 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004752 mHwPaused = true;
4753 }
4754 // If we were part way through writing the mixbuffer to
4755 // the HAL we must save this until we resume
4756 // BUG - this will be wrong if a different track is made active,
4757 // in that case we want to discard the pending data in the
4758 // mixbuffer and tell the client to present it again when the
4759 // track is resumed
4760 mPausedWriteLength = mCurrentWriteLength;
4761 mPausedBytesRemaining = mBytesRemaining;
4762 mBytesRemaining = 0; // stop writing
4763 }
4764 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004765 } else if (track->isFlushPending()) {
4766 track->flushAck();
4767 if (last) {
4768 mFlushPending = true;
4769 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004770 } else if (track->isResumePending()){
4771 track->resumeAck();
4772 if (last) {
4773 if (mPausedBytesRemaining) {
4774 // Need to continue write that was interrupted
4775 mCurrentWriteLength = mPausedWriteLength;
4776 mBytesRemaining = mPausedBytesRemaining;
4777 mPausedBytesRemaining = 0;
4778 }
4779 if (mHwPaused) {
4780 doHwResume = true;
4781 mHwPaused = false;
4782 // threadLoop_mix() will handle the case that we need to
4783 // resume an interrupted write
4784 }
4785 // enable write to audio HAL
4786 sleepTime = 0;
4787
4788 // Do not handle new data in this iteration even if track->framesReady()
4789 mixerStatus = MIXER_TRACKS_ENABLED;
4790 }
4791 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004792 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004793 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004794 if (track->mFillingUpStatus == Track::FS_FILLED) {
4795 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004796 // make sure processVolume_l() will apply new volume even if 0
4797 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004798 }
4799
4800 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004801 sp<Track> previousTrack = mPreviousTrack.promote();
4802 if (previousTrack != 0) {
4803 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004804 // Flush any data still being written from last track
4805 mBytesRemaining = 0;
4806 if (mPausedBytesRemaining) {
4807 // Last track was paused so we also need to flush saved
4808 // mixbuffer state and invalidate track so that it will
4809 // re-submit that unwritten data when it is next resumed
4810 mPausedBytesRemaining = 0;
4811 // Invalidate is a bit drastic - would be more efficient
4812 // to have a flag to tell client that some of the
4813 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004814 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004815 }
4816 // flush data already sent to the DSP if changing audio session as audio
4817 // comes from a different source. Also invalidate previous track to force a
4818 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004819 if (previousTrack->sessionId() != track->sessionId()) {
4820 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004821 }
4822 }
4823 }
4824 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004825 // reset retry count
4826 track->mRetryCount = kMaxTrackRetriesOffload;
4827 mActiveTrack = t;
4828 mixerStatus = MIXER_TRACKS_READY;
4829 }
4830 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004831 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004832 if (track->isStopping_1()) {
4833 // Hardware buffer can hold a large amount of audio so we must
4834 // wait for all current track's data to drain before we say
4835 // that the track is stopped.
4836 if (mBytesRemaining == 0) {
4837 // Only start draining when all data in mixbuffer
4838 // has been written
4839 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4840 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004841 // do not drain if no data was ever sent to HAL (mStandby == true)
4842 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004843 // do not modify drain sequence if we are already draining. This happens
4844 // when resuming from pause after drain.
4845 if ((mDrainSequence & 1) == 0) {
4846 sleepTime = 0;
4847 standbyTime = systemTime() + standbyDelay;
4848 mixerStatus = MIXER_DRAIN_TRACK;
4849 mDrainSequence += 2;
4850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004851 if (mHwPaused) {
4852 // It is possible to move from PAUSED to STOPPING_1 without
4853 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004854 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004855 mHwPaused = false;
4856 }
4857 }
4858 }
4859 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004860 // Drain has completed or we are in standby, signal presentation complete
4861 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004862 track->mState = TrackBase::STOPPED;
4863 size_t audioHALFrames =
4864 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4865 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004866 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867 track->presentationComplete(framesWritten, audioHALFrames);
4868 track->reset();
4869 tracksToRemove->add(track);
4870 }
4871 } else {
4872 // No buffers for this track. Give it a few chances to
4873 // fill a buffer, then remove it from active list.
4874 if (--(track->mRetryCount) <= 0) {
4875 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4876 track->name());
4877 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004878 // indicate to client process that the track was disabled because of underrun;
4879 // it will then automatically call start() when data is available
4880 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881 } else if (last){
4882 mixerStatus = MIXER_TRACKS_ENABLED;
4883 }
4884 }
4885 }
4886 // compute volume for this track
4887 processVolume_l(track, last);
4888 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004889
Eric Laurentea0fade2013-10-04 16:23:48 -07004890 // make sure the pause/flush/resume sequence is executed in the right order.
4891 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4892 // before flush and then resume HW. This can happen in case of pause/flush/resume
4893 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004894 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004895 mOutput->stream->pause(mOutput->stream);
4896 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004897 if (mFlushPending) {
4898 flushHw_l();
4899 mFlushPending = false;
4900 }
Eric Laurentfd477972013-10-25 18:10:40 -07004901 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004902 mOutput->stream->resume(mOutput->stream);
4903 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004904
Eric Laurentbfb1b832013-01-07 09:53:42 -08004905 // remove all the tracks that need to be...
4906 removeTracks_l(*tracksToRemove);
4907
4908 return mixerStatus;
4909}
4910
Eric Laurentbfb1b832013-01-07 09:53:42 -08004911// must be called with thread mutex locked
4912bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4913{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004914 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4915 mWriteAckSequence, mDrainSequence);
4916 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004917 return true;
4918 }
4919 return false;
4920}
4921
Eric Laurentbfb1b832013-01-07 09:53:42 -08004922bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4923{
4924 Mutex::Autolock _l(mLock);
4925 return waitingAsyncCallback_l();
4926}
4927
4928void AudioFlinger::OffloadThread::flushHw_l()
4929{
Eric Laurente659ef42014-09-29 13:06:46 -07004930 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931 // Flush anything still waiting in the mixbuffer
4932 mCurrentWriteLength = 0;
4933 mBytesRemaining = 0;
4934 mPausedWriteLength = 0;
4935 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004936
Eric Laurentbfb1b832013-01-07 09:53:42 -08004937 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004938 // discard any pending drain or write ack by incrementing sequence
4939 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4940 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004941 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004942 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4943 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004944 }
4945}
4946
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004947void AudioFlinger::OffloadThread::onAddNewTrack_l()
4948{
4949 sp<Track> previousTrack = mPreviousTrack.promote();
4950 sp<Track> latestTrack = mLatestActiveTrack.promote();
4951
4952 if (previousTrack != 0 && latestTrack != 0 &&
4953 (previousTrack->sessionId() != latestTrack->sessionId())) {
4954 mFlushPending = true;
4955 }
4956 PlaybackThread::onAddNewTrack_l();
4957}
4958
Eric Laurentbfb1b832013-01-07 09:53:42 -08004959// ----------------------------------------------------------------------------
4960
Eric Laurent81784c32012-11-19 14:55:58 -08004961AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4962 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4963 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4964 DUPLICATING),
4965 mWaitTimeMs(UINT_MAX)
4966{
4967 addOutputTrack(mainThread);
4968}
4969
4970AudioFlinger::DuplicatingThread::~DuplicatingThread()
4971{
4972 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4973 mOutputTracks[i]->destroy();
4974 }
4975}
4976
4977void AudioFlinger::DuplicatingThread::threadLoop_mix()
4978{
4979 // mix buffers...
4980 if (outputsReady(outputTracks)) {
4981 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4982 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004983 if (mMixerBufferValid) {
4984 memset(mMixerBuffer, 0, mMixerBufferSize);
4985 } else {
4986 memset(mSinkBuffer, 0, mSinkBufferSize);
4987 }
Eric Laurent81784c32012-11-19 14:55:58 -08004988 }
4989 sleepTime = 0;
4990 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004991 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004992 standbyTime = systemTime() + standbyDelay;
4993}
4994
4995void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4996{
4997 if (sleepTime == 0) {
4998 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4999 sleepTime = activeSleepTime;
5000 } else {
5001 sleepTime = idleSleepTime;
5002 }
5003 } else if (mBytesWritten != 0) {
5004 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5005 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005006 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005007 } else {
5008 // flush remaining overflow buffers in output tracks
5009 writeFrames = 0;
5010 }
5011 sleepTime = 0;
5012 }
5013}
5014
Eric Laurentbfb1b832013-01-07 09:53:42 -08005015ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005016{
5017 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005018 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005020 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005021 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005022}
5023
5024void AudioFlinger::DuplicatingThread::threadLoop_standby()
5025{
5026 // DuplicatingThread implements standby by stopping all tracks
5027 for (size_t i = 0; i < outputTracks.size(); i++) {
5028 outputTracks[i]->stop();
5029 }
5030}
5031
5032void AudioFlinger::DuplicatingThread::saveOutputTracks()
5033{
5034 outputTracks = mOutputTracks;
5035}
5036
5037void AudioFlinger::DuplicatingThread::clearOutputTracks()
5038{
5039 outputTracks.clear();
5040}
5041
5042void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5043{
5044 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005045 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5046 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5047 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5048 const size_t frameCount =
5049 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5050 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5051 // from different OutputTracks and their associated MixerThreads (e.g. one may
5052 // nearly empty and the other may be dropping data).
5053
5054 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005055 this,
5056 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005057 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005058 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005059 frameCount,
5060 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005061 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005062 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005063 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005064 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005065 updateWaitTime_l();
5066 }
5067}
5068
5069void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5070{
5071 Mutex::Autolock _l(mLock);
5072 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5073 if (mOutputTracks[i]->thread() == thread) {
5074 mOutputTracks[i]->destroy();
5075 mOutputTracks.removeAt(i);
5076 updateWaitTime_l();
5077 return;
5078 }
5079 }
5080 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5081}
5082
5083// caller must hold mLock
5084void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5085{
5086 mWaitTimeMs = UINT_MAX;
5087 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5088 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5089 if (strong != 0) {
5090 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5091 if (waitTimeMs < mWaitTimeMs) {
5092 mWaitTimeMs = waitTimeMs;
5093 }
5094 }
5095 }
5096}
5097
5098
5099bool AudioFlinger::DuplicatingThread::outputsReady(
5100 const SortedVector< sp<OutputTrack> > &outputTracks)
5101{
5102 for (size_t i = 0; i < outputTracks.size(); i++) {
5103 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5104 if (thread == 0) {
5105 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5106 outputTracks[i].get());
5107 return false;
5108 }
5109 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5110 // see note at standby() declaration
5111 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5112 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5113 thread.get());
5114 return false;
5115 }
5116 }
5117 return true;
5118}
5119
5120uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5121{
5122 return (mWaitTimeMs * 1000) / 2;
5123}
5124
5125void AudioFlinger::DuplicatingThread::cacheParameters_l()
5126{
5127 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5128 updateWaitTime_l();
5129
5130 MixerThread::cacheParameters_l();
5131}
5132
5133// ----------------------------------------------------------------------------
5134// Record
5135// ----------------------------------------------------------------------------
5136
5137AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5138 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005139 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005140 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005141 audio_devices_t inDevice
5142#ifdef TEE_SINK
5143 , const sp<NBAIO_Sink>& teeSink
5144#endif
5145 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005146 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005147 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005148 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005149 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005150#ifdef TEE_SINK
5151 , mTeeSink(teeSink)
5152#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005153 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5154 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005155 // mFastCapture below
5156 , mFastCaptureFutex(0)
5157 // mInputSource
5158 // mPipeSink
5159 // mPipeSource
5160 , mPipeFramesP2(0)
5161 // mPipeMemory
5162 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005163 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005164{
Glenn Kastend7dca052015-03-05 16:05:54 -08005165 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5166 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005167
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005168 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005169
5170 // create an NBAIO source for the HAL input stream, and negotiate
5171 mInputSource = new AudioStreamInSource(input->stream);
5172 size_t numCounterOffers = 0;
5173 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5174 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5175 ALOG_ASSERT(index == 0);
5176
5177 // initialize fast capture depending on configuration
5178 bool initFastCapture;
5179 switch (kUseFastCapture) {
5180 case FastCapture_Never:
5181 initFastCapture = false;
5182 break;
5183 case FastCapture_Always:
5184 initFastCapture = true;
5185 break;
5186 case FastCapture_Static:
5187 uint32_t primaryOutputSampleRate;
5188 {
5189 AutoMutex _l(audioFlinger->mHardwareLock);
5190 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5191 }
5192 initFastCapture =
5193 // either capture sample rate is same as (a reasonable) primary output sample rate
5194 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5195 (mSampleRate == primaryOutputSampleRate)) ||
5196 // or primary output sample rate is unknown, and capture sample rate is reasonable
5197 ((primaryOutputSampleRate == 0) &&
5198 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005199 // and the buffer size is < 12 ms
5200 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005201 break;
5202 // case FastCapture_Dynamic:
5203 }
5204
5205 if (initFastCapture) {
5206 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5207 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005208 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005209 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5210 void *pipeBuffer;
5211 const sp<MemoryDealer> roHeap(readOnlyHeap());
5212 sp<IMemory> pipeMemory;
5213 if ((roHeap == 0) ||
5214 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5215 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5216 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5217 goto failed;
5218 }
5219 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5220 memset(pipeBuffer, 0, pipeSize);
5221 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5222 const NBAIO_Format offers[1] = {format};
5223 size_t numCounterOffers = 0;
5224 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5225 ALOG_ASSERT(index == 0);
5226 mPipeSink = pipe;
5227 PipeReader *pipeReader = new PipeReader(*pipe);
5228 numCounterOffers = 0;
5229 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5230 ALOG_ASSERT(index == 0);
5231 mPipeSource = pipeReader;
5232 mPipeFramesP2 = pipeFramesP2;
5233 mPipeMemory = pipeMemory;
5234
5235 // create fast capture
5236 mFastCapture = new FastCapture();
5237 FastCaptureStateQueue *sq = mFastCapture->sq();
5238#ifdef STATE_QUEUE_DUMP
5239 // FIXME
5240#endif
5241 FastCaptureState *state = sq->begin();
5242 state->mCblk = NULL;
5243 state->mInputSource = mInputSource.get();
5244 state->mInputSourceGen++;
5245 state->mPipeSink = pipe;
5246 state->mPipeSinkGen++;
5247 state->mFrameCount = mFrameCount;
5248 state->mCommand = FastCaptureState::COLD_IDLE;
5249 // already done in constructor initialization list
5250 //mFastCaptureFutex = 0;
5251 state->mColdFutexAddr = &mFastCaptureFutex;
5252 state->mColdGen++;
5253 state->mDumpState = &mFastCaptureDumpState;
5254#ifdef TEE_SINK
5255 // FIXME
5256#endif
5257 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5258 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5259 sq->end();
5260 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5261
5262 // start the fast capture
5263 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5264 pid_t tid = mFastCapture->getTid();
5265 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5266 if (err != 0) {
5267 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5268 kPriorityFastCapture, getpid_cached, tid, err);
5269 }
5270
5271#ifdef AUDIO_WATCHDOG
5272 // FIXME
5273#endif
5274
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005275 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005276 }
5277failed: ;
5278
5279 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005280}
5281
5282
5283AudioFlinger::RecordThread::~RecordThread()
5284{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005285 if (mFastCapture != 0) {
5286 FastCaptureStateQueue *sq = mFastCapture->sq();
5287 FastCaptureState *state = sq->begin();
5288 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5289 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5290 if (old == -1) {
5291 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5292 }
5293 }
5294 state->mCommand = FastCaptureState::EXIT;
5295 sq->end();
5296 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5297 mFastCapture->join();
5298 mFastCapture.clear();
5299 }
5300 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005301 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005302 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005303}
5304
5305void AudioFlinger::RecordThread::onFirstRef()
5306{
Glenn Kastend7dca052015-03-05 16:05:54 -08005307 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005308}
5309
Eric Laurent81784c32012-11-19 14:55:58 -08005310bool AudioFlinger::RecordThread::threadLoop()
5311{
Eric Laurent81784c32012-11-19 14:55:58 -08005312 nsecs_t lastWarning = 0;
5313
5314 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005315
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005316reacquire_wakelock:
5317 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005318 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005319 {
5320 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005321 size_t size = mActiveTracks.size();
5322 activeTracksGen = mActiveTracksGen;
5323 if (size > 0) {
5324 // FIXME an arbitrary choice
5325 activeTrack = mActiveTracks[0];
5326 acquireWakeLock_l(activeTrack->uid());
5327 if (size > 1) {
5328 SortedVector<int> tmp;
5329 for (size_t i = 0; i < size; i++) {
5330 tmp.add(mActiveTracks[i]->uid());
5331 }
5332 updateWakeLockUids_l(tmp);
5333 }
5334 } else {
5335 acquireWakeLock_l(-1);
5336 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005337 }
5338
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005339 // used to request a deferred sleep, to be executed later while mutex is unlocked
5340 uint32_t sleepUs = 0;
5341
5342 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005343 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005344 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005345
Glenn Kasten5edadd42013-08-14 16:30:49 -07005346 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005347 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005348 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005349 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005350 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005351 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005352 }
5353
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005354 // activeTracks accumulates a copy of a subset of mActiveTracks
5355 Vector< sp<RecordTrack> > activeTracks;
5356
Glenn Kasten735f45f2014-08-18 15:51:59 -07005357 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005358 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005359
Glenn Kasten735f45f2014-08-18 15:51:59 -07005360 // reference to a fast track which is about to be removed
5361 sp<RecordTrack> fastTrackToRemove;
5362
Eric Laurent81784c32012-11-19 14:55:58 -08005363 { // scope for mLock
5364 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005365
Eric Laurent021cf962014-05-13 10:18:14 -07005366 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005367
Eric Laurent000a4192014-01-29 15:17:32 -08005368 // check exitPending here because checkForNewParameters_l() and
5369 // checkForNewParameters_l() can temporarily release mLock
5370 if (exitPending()) {
5371 break;
5372 }
5373
Glenn Kasten2b806402013-11-20 16:37:38 -08005374 // if no active track(s), then standby and release wakelock
5375 size_t size = mActiveTracks.size();
5376 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005377 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005378 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005379 releaseWakeLock_l();
5380 ALOGV("RecordThread: loop stopping");
5381 // go to sleep
5382 mWaitWorkCV.wait(mLock);
5383 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005384 goto reacquire_wakelock;
5385 }
5386
Glenn Kasten2b806402013-11-20 16:37:38 -08005387 if (mActiveTracksGen != activeTracksGen) {
5388 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005389 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005390 for (size_t i = 0; i < size; i++) {
5391 tmp.add(mActiveTracks[i]->uid());
5392 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005393 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005394 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005395
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005396 bool doBroadcast = false;
5397 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005398
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005399 activeTrack = mActiveTracks[i];
5400 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005401 if (activeTrack->isFastTrack()) {
5402 ALOG_ASSERT(fastTrackToRemove == 0);
5403 fastTrackToRemove = activeTrack;
5404 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005405 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005406 mActiveTracks.remove(activeTrack);
5407 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005408 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005409 continue;
5410 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005411
5412 TrackBase::track_state activeTrackState = activeTrack->mState;
5413 switch (activeTrackState) {
5414
5415 case TrackBase::PAUSING:
5416 mActiveTracks.remove(activeTrack);
5417 mActiveTracksGen++;
5418 doBroadcast = true;
5419 size--;
5420 continue;
5421
5422 case TrackBase::STARTING_1:
5423 sleepUs = 10000;
5424 i++;
5425 continue;
5426
5427 case TrackBase::STARTING_2:
5428 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005429 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005430 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005431 break;
5432
5433 case TrackBase::ACTIVE:
5434 break;
5435
5436 case TrackBase::IDLE:
5437 i++;
5438 continue;
5439
5440 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005441 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005442 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005443
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005444 activeTracks.add(activeTrack);
5445 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005446
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005447 if (activeTrack->isFastTrack()) {
5448 ALOG_ASSERT(!mFastTrackAvail);
5449 ALOG_ASSERT(fastTrack == 0);
5450 fastTrack = activeTrack;
5451 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005452 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005453 if (doBroadcast) {
5454 mStartStopCond.broadcast();
5455 }
5456
5457 // sleep if there are no active tracks to process
5458 if (activeTracks.size() == 0) {
5459 if (sleepUs == 0) {
5460 sleepUs = kRecordThreadSleepUs;
5461 }
5462 continue;
5463 }
5464 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005465
Eric Laurent81784c32012-11-19 14:55:58 -08005466 lockEffectChains_l(effectChains);
5467 }
5468
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005470
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005471 size_t size = effectChains.size();
5472 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005473 // thread mutex is not locked, but effect chain is locked
5474 effectChains[i]->process_l();
5475 }
5476
Glenn Kasten735f45f2014-08-18 15:51:59 -07005477 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005478 if (mFastCapture != 0) {
5479 FastCaptureStateQueue *sq = mFastCapture->sq();
5480 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005481 bool didModify = false;
5482 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005483 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5484 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5485 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5486 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5487 if (old == -1) {
5488 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5489 }
5490 }
5491 state->mCommand = FastCaptureState::READ_WRITE;
5492#if 0 // FIXME
5493 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005494 FastThreadDumpState::kSamplingNforLowRamDevice :
5495 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005496#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005497 didModify = true;
5498 }
5499 audio_track_cblk_t *cblkOld = state->mCblk;
5500 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5501 if (cblkNew != cblkOld) {
5502 state->mCblk = cblkNew;
5503 // block until acked if removing a fast track
5504 if (cblkOld != NULL) {
5505 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5506 }
5507 didModify = true;
5508 }
5509 sq->end(didModify);
5510 if (didModify) {
5511 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005512#if 0
5513 if (kUseFastCapture == FastCapture_Dynamic) {
5514 mNormalSource = mPipeSource;
5515 }
5516#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005517 }
5518 }
5519
Glenn Kasten735f45f2014-08-18 15:51:59 -07005520 // now run the fast track destructor with thread mutex unlocked
5521 fastTrackToRemove.clear();
5522
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005523 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5524 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5525 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5526 // If destination is non-contiguous, first read past the nominal end of buffer, then
5527 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005528
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005529 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005530 ssize_t framesRead;
5531
5532 // If an NBAIO source is present, use it to read the normal capture's data
5533 if (mPipeSource != 0) {
5534 size_t framesToRead = mBufferSize / mFrameSize;
5535 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5536 framesToRead, AudioBufferProvider::kInvalidPTS);
5537 if (framesRead == 0) {
5538 // since pipe is non-blocking, simulate blocking input
5539 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5540 }
5541 // otherwise use the HAL / AudioStreamIn directly
5542 } else {
5543 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5544 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5545 if (bytesRead < 0) {
5546 framesRead = bytesRead;
5547 } else {
5548 framesRead = bytesRead / mFrameSize;
5549 }
5550 }
5551
5552 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5553 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005554 // Force input into standby so that it tries to recover at next read attempt
5555 inputStandBy();
5556 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005557 }
5558 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005559 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005560 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005561 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005562
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005563 if (mTeeSink != 0) {
5564 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5565 }
5566 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005567 {
5568 size_t part1 = mRsmpInFramesP2 - rear;
5569 if ((size_t) framesRead > part1) {
5570 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5571 (framesRead - part1) * mFrameSize);
5572 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005573 }
5574 rear = mRsmpInRear += framesRead;
5575
5576 size = activeTracks.size();
5577 // loop over each active track
5578 for (size_t i = 0; i < size; i++) {
5579 activeTrack = activeTracks[i];
5580
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005581 // skip fast tracks, as those are handled directly by FastCapture
5582 if (activeTrack->isFastTrack()) {
5583 continue;
5584 }
5585
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005586 enum {
5587 OVERRUN_UNKNOWN,
5588 OVERRUN_TRUE,
5589 OVERRUN_FALSE
5590 } overrun = OVERRUN_UNKNOWN;
5591
5592 // loop over getNextBuffer to handle circular sink
5593 for (;;) {
5594
5595 activeTrack->mSink.frameCount = ~0;
5596 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5597 size_t framesOut = activeTrack->mSink.frameCount;
5598 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5599
5600 int32_t front = activeTrack->mRsmpInFront;
5601 ssize_t filled = rear - front;
5602 size_t framesIn;
5603
5604 if (filled < 0) {
5605 // should not happen, but treat like a massive overrun and re-sync
5606 framesIn = 0;
5607 activeTrack->mRsmpInFront = rear;
5608 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005609 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005610 framesIn = (size_t) filled;
5611 } else {
5612 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005613 framesIn = mRsmpInFrames;
5614 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005615 overrun = OVERRUN_TRUE;
5616 }
5617
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005618 if (framesOut == 0 || framesIn == 0) {
5619 break;
5620 }
5621
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005622 if (activeTrack->mResampler == NULL) {
5623 // no resampling
5624 if (framesIn > framesOut) {
5625 framesIn = framesOut;
5626 } else {
5627 framesOut = framesIn;
5628 }
5629 int8_t *dst = activeTrack->mSink.i8;
5630 while (framesIn > 0) {
5631 front &= mRsmpInFramesP2 - 1;
5632 size_t part1 = mRsmpInFramesP2 - front;
5633 if (part1 > framesIn) {
5634 part1 = framesIn;
5635 }
5636 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005637 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005638 memcpy(dst, src, part1 * mFrameSize);
5639 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005640 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005641 part1);
5642 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005643 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5644 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005645 }
5646 dst += part1 * activeTrack->mFrameSize;
5647 front += part1;
5648 framesIn -= part1;
5649 }
5650 activeTrack->mRsmpInFront += framesOut;
5651
5652 } else {
5653 // resampling
5654 // FIXME framesInNeeded should really be part of resampler API, and should
5655 // depend on the SRC ratio
5656 // to keep mRsmpInBuffer full so resampler always has sufficient input
5657 size_t framesInNeeded;
5658 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005659 // Do not precompute in/out because floating point is not associative
5660 // e.g. a*b/c != a*(b/c).
5661 const double in(mSampleRate);
5662 const double out(activeTrack->mSampleRate);
5663 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005664 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005665 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005666 // Although we theoretically have framesIn in circular buffer, some of those are
5667 // unreleased frames, and thus must be discounted for purpose of budgeting.
5668 size_t unreleased = activeTrack->mRsmpInUnrel;
5669 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005670 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005671 ALOGV("not enough to resample: have %u frames in but need %u in to "
5672 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005673 framesIn, framesInNeeded, framesOut, in / out);
5674 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005675 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5676 if (newFramesOut == 0) {
5677 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005678 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005679 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005680 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005681 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005682 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5683 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5684 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005685 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005686 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005687 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005688 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005689 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005690 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005691 }
5692
5693 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5694 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005695 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005696 delete[] activeTrack->mRsmpOutBuffer;
5697 // resampler always outputs stereo
5698 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5699 activeTrack->mRsmpOutFrameCount = framesOut;
5700 }
5701
5702 // resampler accumulates, but we only have one source track
5703 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5704 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005705 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005706 activeTrack->mResamplerBufferProvider
5707 /*this*/ /* AudioBufferProvider* */);
5708 // ditherAndClamp() works as long as all buffers returned by
5709 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005710 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005711 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005712 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5713 framesOut);
5714 // the resampler always outputs stereo samples:
5715 // do post stereo to mono conversion
5716 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005717 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005718 } else {
5719 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5720 activeTrack->mRsmpOutBuffer, framesOut);
5721 }
5722 // now done with mRsmpOutBuffer
5723
5724 }
5725
5726 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5727 overrun = OVERRUN_FALSE;
5728 }
5729
5730 if (activeTrack->mFramesToDrop == 0) {
5731 if (framesOut > 0) {
5732 activeTrack->mSink.frameCount = framesOut;
5733 activeTrack->releaseBuffer(&activeTrack->mSink);
5734 }
5735 } else {
5736 // FIXME could do a partial drop of framesOut
5737 if (activeTrack->mFramesToDrop > 0) {
5738 activeTrack->mFramesToDrop -= framesOut;
5739 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005740 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005741 }
5742 } else {
5743 activeTrack->mFramesToDrop += framesOut;
5744 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5745 activeTrack->mSyncStartEvent->isCancelled()) {
5746 ALOGW("Synced record %s, session %d, trigger session %d",
5747 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5748 activeTrack->sessionId(),
5749 (activeTrack->mSyncStartEvent != 0) ?
5750 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005751 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005752 }
5753 }
5754 }
5755
5756 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005757 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005758 }
5759 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005760
5761 switch (overrun) {
5762 case OVERRUN_TRUE:
5763 // client isn't retrieving buffers fast enough
5764 if (!activeTrack->setOverflow()) {
5765 nsecs_t now = systemTime();
5766 // FIXME should lastWarning per track?
5767 if ((now - lastWarning) > kWarningThrottleNs) {
5768 ALOGW("RecordThread: buffer overflow");
5769 lastWarning = now;
5770 }
5771 }
5772 break;
5773 case OVERRUN_FALSE:
5774 activeTrack->clearOverflow();
5775 break;
5776 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005777 break;
5778 }
5779
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005780 }
5781
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005782unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005783 // enable changes in effect chain
5784 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005785 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005786 }
5787
Glenn Kasten93e471f2013-08-19 08:40:07 -07005788 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005789
5790 {
5791 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005792 for (size_t i = 0; i < mTracks.size(); i++) {
5793 sp<RecordTrack> track = mTracks[i];
5794 track->invalidate();
5795 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005796 mActiveTracks.clear();
5797 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005798 mStartStopCond.broadcast();
5799 }
5800
5801 releaseWakeLock();
5802
5803 ALOGV("RecordThread %p exiting", this);
5804 return false;
5805}
5806
Glenn Kasten93e471f2013-08-19 08:40:07 -07005807void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005808{
5809 if (!mStandby) {
5810 inputStandBy();
5811 mStandby = true;
5812 }
5813}
5814
5815void AudioFlinger::RecordThread::inputStandBy()
5816{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005817 // Idle the fast capture if it's currently running
5818 if (mFastCapture != 0) {
5819 FastCaptureStateQueue *sq = mFastCapture->sq();
5820 FastCaptureState *state = sq->begin();
5821 if (!(state->mCommand & FastCaptureState::IDLE)) {
5822 state->mCommand = FastCaptureState::COLD_IDLE;
5823 state->mColdFutexAddr = &mFastCaptureFutex;
5824 state->mColdGen++;
5825 mFastCaptureFutex = 0;
5826 sq->end();
5827 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5828 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5829#if 0
5830 if (kUseFastCapture == FastCapture_Dynamic) {
5831 // FIXME
5832 }
5833#endif
5834#ifdef AUDIO_WATCHDOG
5835 // FIXME
5836#endif
5837 } else {
5838 sq->end(false /*didModify*/);
5839 }
5840 }
Eric Laurent81784c32012-11-19 14:55:58 -08005841 mInput->stream->common.standby(&mInput->stream->common);
5842}
5843
Glenn Kasten05997e22014-03-13 15:08:33 -07005844// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005845sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005846 const sp<AudioFlinger::Client>& client,
5847 uint32_t sampleRate,
5848 audio_format_t format,
5849 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005850 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005851 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005852 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005853 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005854 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005855 pid_t tid,
5856 status_t *status)
5857{
Glenn Kasten74935e42013-12-19 08:56:45 -08005858 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005859 sp<RecordTrack> track;
5860 status_t lStatus;
5861
Glenn Kasten90e58b12013-07-31 16:16:02 -07005862 // client expresses a preference for FAST, but we get the final say
5863 if (*flags & IAudioFlinger::TRACK_FAST) {
5864 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005865 // use case: callback handler
5866 (tid != -1) &&
5867 // frame count is not specified, or is exactly the pipe depth
5868 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005869 // PCM data
5870 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005871 // native format
5872 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005873 // native channel mask
5874 (channelMask == mChannelMask) &&
5875 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005876 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005877 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005878 hasFastCapture() &&
5879 // there are sufficient fast track slots available
5880 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005881 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005882 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005883 frameCount, mFrameCount);
5884 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005885 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5886 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005887 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005888 frameCount, mFrameCount, mPipeFramesP2,
5889 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5890 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005891 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005892 }
5893 }
5894
5895 // compute track buffer size in frames, and suggest the notification frame count
5896 if (*flags & IAudioFlinger::TRACK_FAST) {
5897 // fast track: frame count is exactly the pipe depth
5898 frameCount = mPipeFramesP2;
5899 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5900 *notificationFrames = mFrameCount;
5901 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005902 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5903 // or 20 ms if there is a fast capture
5904 // TODO This could be a roundupRatio inline, and const
5905 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5906 * sampleRate + mSampleRate - 1) / mSampleRate;
5907 // minimum number of notification periods is at least kMinNotifications,
5908 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5909 static const size_t kMinNotifications = 3;
5910 static const uint32_t kMinMs = 30;
5911 // TODO This could be a roundupRatio inline
5912 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5913 // TODO This could be a roundupRatio inline
5914 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5915 maxNotificationFrames;
5916 const size_t minFrameCount = maxNotificationFrames *
5917 max(kMinNotifications, minNotificationsByMs);
5918 frameCount = max(frameCount, minFrameCount);
5919 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5920 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005921 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005922 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005923 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005924
Glenn Kasten15e57982013-09-24 11:52:37 -07005925 lStatus = initCheck();
5926 if (lStatus != NO_ERROR) {
5927 ALOGE("createRecordTrack_l() audio driver not initialized");
5928 goto Exit;
5929 }
Eric Laurent81784c32012-11-19 14:55:58 -08005930
5931 { // scope for mLock
5932 Mutex::Autolock _l(mLock);
5933
5934 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005935 format, channelMask, frameCount, NULL, sessionId, uid,
5936 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005937
Glenn Kasten03003332013-08-06 15:40:54 -07005938 lStatus = track->initCheck();
5939 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005940 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005941 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005942 goto Exit;
5943 }
5944 mTracks.add(track);
5945
5946 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5947 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5948 mAudioFlinger->btNrecIsOff();
5949 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5950 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005951
5952 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5953 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5954 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5955 // so ask activity manager to do this on our behalf
5956 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5957 }
Eric Laurent81784c32012-11-19 14:55:58 -08005958 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005959
Eric Laurent81784c32012-11-19 14:55:58 -08005960 lStatus = NO_ERROR;
5961
5962Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005963 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005964 return track;
5965}
5966
5967status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5968 AudioSystem::sync_event_t event,
5969 int triggerSession)
5970{
5971 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5972 sp<ThreadBase> strongMe = this;
5973 status_t status = NO_ERROR;
5974
5975 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005976 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005977 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005978 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005979 triggerSession,
5980 recordTrack->sessionId(),
5981 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005982 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005983 // Sync event can be cancelled by the trigger session if the track is not in a
5984 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005985 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005986 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005987 } else {
5988 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005989 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005990 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005991 }
5992 }
5993
5994 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005995 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005996 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005997 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5998 if (recordTrack->mState == TrackBase::PAUSING) {
5999 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006000 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006001 } else {
6002 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006003 }
6004 return status;
6005 }
6006
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006007 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6008 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6009 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006010 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006011 mActiveTracks.add(recordTrack);
6012 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006013 status_t status = NO_ERROR;
6014 if (recordTrack->isExternalTrack()) {
6015 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006016 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006017 mLock.lock();
6018 // FIXME should verify that recordTrack is still in mActiveTracks
6019 if (status != NO_ERROR) {
6020 mActiveTracks.remove(recordTrack);
6021 mActiveTracksGen++;
6022 recordTrack->clearSyncStartEvent();
6023 ALOGV("RecordThread::start error %d", status);
6024 return status;
6025 }
Eric Laurent81784c32012-11-19 14:55:58 -08006026 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006027 // Catch up with current buffer indices if thread is already running.
6028 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6029 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6030 // see previously buffered data before it called start(), but with greater risk of overrun.
6031
6032 recordTrack->mRsmpInFront = mRsmpInRear;
6033 recordTrack->mRsmpInUnrel = 0;
6034 // FIXME why reset?
6035 if (recordTrack->mResampler != NULL) {
6036 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08006037 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006038 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006039 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006040 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006041 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006042 ALOGV("Record failed to start");
6043 status = BAD_VALUE;
6044 goto startError;
6045 }
Eric Laurent81784c32012-11-19 14:55:58 -08006046 return status;
6047 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006048
Eric Laurent81784c32012-11-19 14:55:58 -08006049startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006050 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006051 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006052 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006053 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006054 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006055 return status;
6056}
6057
Eric Laurent81784c32012-11-19 14:55:58 -08006058void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6059{
6060 sp<SyncEvent> strongEvent = event.promote();
6061
6062 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006063 sp<RefBase> ptr = strongEvent->cookie().promote();
6064 if (ptr != 0) {
6065 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6066 recordTrack->handleSyncStartEvent(strongEvent);
6067 }
Eric Laurent81784c32012-11-19 14:55:58 -08006068 }
6069}
6070
Glenn Kastena8356f62013-07-25 14:37:52 -07006071bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006072 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006073 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006074 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006075 return false;
6076 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006077 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006078 recordTrack->mState = TrackBase::PAUSING;
6079 // do not wait for mStartStopCond if exiting
6080 if (exitPending()) {
6081 return true;
6082 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006083 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006084 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006085 // if we have been restarted, recordTrack is in mActiveTracks here
6086 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006087 ALOGV("Record stopped OK");
6088 return true;
6089 }
6090 return false;
6091}
6092
Glenn Kasten0f11b512014-01-31 16:18:54 -08006093bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006094{
6095 return false;
6096}
6097
Glenn Kasten0f11b512014-01-31 16:18:54 -08006098status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006099{
6100#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6101 if (!isValidSyncEvent(event)) {
6102 return BAD_VALUE;
6103 }
6104
6105 int eventSession = event->triggerSession();
6106 status_t ret = NAME_NOT_FOUND;
6107
6108 Mutex::Autolock _l(mLock);
6109
6110 for (size_t i = 0; i < mTracks.size(); i++) {
6111 sp<RecordTrack> track = mTracks[i];
6112 if (eventSession == track->sessionId()) {
6113 (void) track->setSyncEvent(event);
6114 ret = NO_ERROR;
6115 }
6116 }
6117 return ret;
6118#else
6119 return BAD_VALUE;
6120#endif
6121}
6122
6123// destroyTrack_l() must be called with ThreadBase::mLock held
6124void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6125{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006126 track->terminate();
6127 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006128 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006129 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006130 removeTrack_l(track);
6131 }
6132}
6133
6134void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6135{
6136 mTracks.remove(track);
6137 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006138 if (track->isFastTrack()) {
6139 ALOG_ASSERT(!mFastTrackAvail);
6140 mFastTrackAvail = true;
6141 }
Eric Laurent81784c32012-11-19 14:55:58 -08006142}
6143
6144void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6145{
6146 dumpInternals(fd, args);
6147 dumpTracks(fd, args);
6148 dumpEffectChains(fd, args);
6149}
6150
6151void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6152{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006153 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006154
Glenn Kasten2b806402013-11-20 16:37:38 -08006155 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006156 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006157 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006158 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006159 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006160 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006161 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006162
Eric Laurent81784c32012-11-19 14:55:58 -08006163 dumpBase(fd, args);
6164}
6165
Glenn Kasten0f11b512014-01-31 16:18:54 -08006166void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006167{
6168 const size_t SIZE = 256;
6169 char buffer[SIZE];
6170 String8 result;
6171
Marco Nelissenb2208842014-02-07 14:00:50 -08006172 size_t numtracks = mTracks.size();
6173 size_t numactive = mActiveTracks.size();
6174 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006175 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006176 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006177 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006178 RecordTrack::appendDumpHeader(result);
6179 for (size_t i = 0; i < numtracks ; ++i) {
6180 sp<RecordTrack> track = mTracks[i];
6181 if (track != 0) {
6182 bool active = mActiveTracks.indexOf(track) >= 0;
6183 if (active) {
6184 numactiveseen++;
6185 }
6186 track->dump(buffer, SIZE, active);
6187 result.append(buffer);
6188 }
Eric Laurent81784c32012-11-19 14:55:58 -08006189 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006190 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006191 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006192 }
6193
Marco Nelissenb2208842014-02-07 14:00:50 -08006194 if (numactiveseen != numactive) {
6195 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6196 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006197 result.append(buffer);
6198 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006199 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006200 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006201 if (mTracks.indexOf(track) < 0) {
6202 track->dump(buffer, SIZE, true);
6203 result.append(buffer);
6204 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006205 }
Eric Laurent81784c32012-11-19 14:55:58 -08006206
6207 }
6208 write(fd, result.string(), result.size());
6209}
6210
6211// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6213 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006214{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006215 RecordTrack *activeTrack = mRecordTrack;
6216 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6217 if (threadBase == 0) {
6218 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006219 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006220 return NOT_ENOUGH_DATA;
6221 }
6222 RecordThread *recordThread = (RecordThread *) threadBase.get();
6223 int32_t rear = recordThread->mRsmpInRear;
6224 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006225 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006226 // FIXME should not be P2 (don't want to increase latency)
6227 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006228 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006229 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006230 front &= recordThread->mRsmpInFramesP2 - 1;
6231 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006232 if (part1 > (size_t) filled) {
6233 part1 = filled;
6234 }
6235 size_t ask = buffer->frameCount;
6236 ALOG_ASSERT(ask > 0);
6237 if (part1 > ask) {
6238 part1 = ask;
6239 }
6240 if (part1 == 0) {
6241 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006242 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006243 buffer->raw = NULL;
6244 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006245 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006246 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006247 }
6248
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006249 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006250 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006251 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006252 return NO_ERROR;
6253}
6254
6255// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006256void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6257 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006258{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006259 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006260 size_t stepCount = buffer->frameCount;
6261 if (stepCount == 0) {
6262 return;
6263 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006264 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6265 activeTrack->mRsmpInUnrel -= stepCount;
6266 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006267 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006268 buffer->frameCount = 0;
6269}
6270
Eric Laurent10351942014-05-08 18:49:52 -07006271bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6272 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006273{
6274 bool reconfig = false;
6275
Eric Laurent10351942014-05-08 18:49:52 -07006276 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006277
Eric Laurent10351942014-05-08 18:49:52 -07006278 audio_format_t reqFormat = mFormat;
6279 uint32_t samplingRate = mSampleRate;
6280 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6281
6282 AudioParameter param = AudioParameter(keyValuePair);
6283 int value;
6284 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6285 // channel count change can be requested. Do we mandate the first client defines the
6286 // HAL sampling rate and channel count or do we allow changes on the fly?
6287 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6288 samplingRate = value;
6289 reconfig = true;
6290 }
6291 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6292 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6293 status = BAD_VALUE;
6294 } else {
6295 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006296 reconfig = true;
6297 }
Eric Laurent10351942014-05-08 18:49:52 -07006298 }
6299 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6300 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6301 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6302 status = BAD_VALUE;
6303 } else {
6304 channelMask = mask;
6305 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006306 }
Eric Laurent10351942014-05-08 18:49:52 -07006307 }
6308 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6309 // do not accept frame count changes if tracks are open as the track buffer
6310 // size depends on frame count and correct behavior would not be guaranteed
6311 // if frame count is changed after track creation
6312 if (mActiveTracks.size() > 0) {
6313 status = INVALID_OPERATION;
6314 } else {
6315 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006316 }
Eric Laurent10351942014-05-08 18:49:52 -07006317 }
6318 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6319 // forward device change to effects that have requested to be
6320 // aware of attached audio device.
6321 for (size_t i = 0; i < mEffectChains.size(); i++) {
6322 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006323 }
Eric Laurent81784c32012-11-19 14:55:58 -08006324
Eric Laurent10351942014-05-08 18:49:52 -07006325 // store input device and output device but do not forward output device to audio HAL.
6326 // Note that status is ignored by the caller for output device
6327 // (see AudioFlinger::setParameters()
6328 if (audio_is_output_devices(value)) {
6329 mOutDevice = value;
6330 status = BAD_VALUE;
6331 } else {
6332 mInDevice = value;
6333 // disable AEC and NS if the device is a BT SCO headset supporting those
6334 // pre processings
6335 if (mTracks.size() > 0) {
6336 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6337 mAudioFlinger->btNrecIsOff();
6338 for (size_t i = 0; i < mTracks.size(); i++) {
6339 sp<RecordTrack> track = mTracks[i];
6340 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6341 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006342 }
6343 }
6344 }
Eric Laurent10351942014-05-08 18:49:52 -07006345 }
6346 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6347 mAudioSource != (audio_source_t)value) {
6348 // forward device change to effects that have requested to be
6349 // aware of attached audio device.
6350 for (size_t i = 0; i < mEffectChains.size(); i++) {
6351 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006352 }
Eric Laurent10351942014-05-08 18:49:52 -07006353 mAudioSource = (audio_source_t)value;
6354 }
Glenn Kastene198c362013-08-13 09:13:36 -07006355
Eric Laurent10351942014-05-08 18:49:52 -07006356 if (status == NO_ERROR) {
6357 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6358 keyValuePair.string());
6359 if (status == INVALID_OPERATION) {
6360 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006361 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6362 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006363 }
6364 if (reconfig) {
6365 if (status == BAD_VALUE &&
6366 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6367 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6368 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6369 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006370 audio_channel_count_from_in_mask(
6371 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006372 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6373 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6374 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006375 }
Eric Laurent10351942014-05-08 18:49:52 -07006376 if (status == NO_ERROR) {
6377 readInputParameters_l();
6378 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006379 }
6380 }
Eric Laurent81784c32012-11-19 14:55:58 -08006381 }
Eric Laurent10351942014-05-08 18:49:52 -07006382
Eric Laurent81784c32012-11-19 14:55:58 -08006383 return reconfig;
6384}
6385
6386String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6387{
Eric Laurent81784c32012-11-19 14:55:58 -08006388 Mutex::Autolock _l(mLock);
6389 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006390 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006391 }
6392
Glenn Kastend8ea6992013-07-16 14:17:15 -07006393 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6394 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006395 free(s);
6396 return out_s8;
6397}
6398
Eric Laurent021cf962014-05-13 10:18:14 -07006399void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006400 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006401 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006402
6403 switch (event) {
6404 case AudioSystem::INPUT_OPENED:
6405 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006406 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006407 desc.samplingRate = mSampleRate;
6408 desc.format = mFormat;
6409 desc.frameCount = mFrameCount;
6410 desc.latency = 0;
6411 param2 = &desc;
6412 break;
6413
6414 case AudioSystem::INPUT_CLOSED:
6415 default:
6416 break;
6417 }
Eric Laurent021cf962014-05-13 10:18:14 -07006418 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006419}
6420
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006421void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006422{
Eric Laurent81784c32012-11-19 14:55:58 -08006423 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6424 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006425 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006426 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6427 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006428 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006429 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006430 }
Eric Laurent665470b2014-07-03 16:37:08 -07006431 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006432 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6433 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006434 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006435 // 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 -07006436 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006437 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 // A larger value should allow more old data to be read after a track calls start(),
6439 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006440 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006441 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006442 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006443
6444 // TODO optimize audio capture buffer sizes ...
6445 // Here we calculate the size of the sliding buffer used as a source
6446 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6447 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6448 // be better to have it derived from the pipe depth in the long term.
6449 // The current value is higher than necessary. However it should not add to latency.
6450
Glenn Kasten85948432013-08-19 12:09:05 -07006451 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6452 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006453
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006454 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6455 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006456}
6457
Glenn Kasten5f972c02014-01-13 09:59:31 -08006458uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006459{
6460 Mutex::Autolock _l(mLock);
6461 if (initCheck() != NO_ERROR) {
6462 return 0;
6463 }
6464
6465 return mInput->stream->get_input_frames_lost(mInput->stream);
6466}
6467
6468uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6469{
6470 Mutex::Autolock _l(mLock);
6471 uint32_t result = 0;
6472 if (getEffectChain_l(sessionId) != 0) {
6473 result = EFFECT_SESSION;
6474 }
6475
6476 for (size_t i = 0; i < mTracks.size(); ++i) {
6477 if (sessionId == mTracks[i]->sessionId()) {
6478 result |= TRACK_SESSION;
6479 break;
6480 }
6481 }
6482
6483 return result;
6484}
6485
6486KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6487{
6488 KeyedVector<int, bool> ids;
6489 Mutex::Autolock _l(mLock);
6490 for (size_t j = 0; j < mTracks.size(); ++j) {
6491 sp<RecordThread::RecordTrack> track = mTracks[j];
6492 int sessionId = track->sessionId();
6493 if (ids.indexOfKey(sessionId) < 0) {
6494 ids.add(sessionId, true);
6495 }
6496 }
6497 return ids;
6498}
6499
6500AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6501{
6502 Mutex::Autolock _l(mLock);
6503 AudioStreamIn *input = mInput;
6504 mInput = NULL;
6505 return input;
6506}
6507
6508// this method must always be called either with ThreadBase mLock held or inside the thread loop
6509audio_stream_t* AudioFlinger::RecordThread::stream() const
6510{
6511 if (mInput == NULL) {
6512 return NULL;
6513 }
6514 return &mInput->stream->common;
6515}
6516
6517status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6518{
6519 // only one chain per input thread
6520 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006521 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006522 return INVALID_OPERATION;
6523 }
6524 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006525 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006526 chain->setInBuffer(NULL);
6527 chain->setOutBuffer(NULL);
6528
6529 checkSuspendOnAddEffectChain_l(chain);
6530
Eric Laurent1b928682014-10-02 19:41:47 -07006531 // make sure enabled pre processing effects state is communicated to the HAL as we
6532 // just moved them to a new input stream.
6533 chain->syncHalEffectsState();
6534
Eric Laurent81784c32012-11-19 14:55:58 -08006535 mEffectChains.add(chain);
6536
6537 return NO_ERROR;
6538}
6539
6540size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6541{
6542 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6543 ALOGW_IF(mEffectChains.size() != 1,
6544 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6545 chain.get(), mEffectChains.size(), this);
6546 if (mEffectChains.size() == 1) {
6547 mEffectChains.removeAt(0);
6548 }
6549 return 0;
6550}
6551
Eric Laurent1c333e22014-05-20 10:48:17 -07006552status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6553 audio_patch_handle_t *handle)
6554{
6555 status_t status = NO_ERROR;
6556 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6557 // store new device and send to effects
6558 mInDevice = patch->sources[0].ext.device.type;
6559 for (size_t i = 0; i < mEffectChains.size(); i++) {
6560 mEffectChains[i]->setDevice_l(mInDevice);
6561 }
6562
6563 // disable AEC and NS if the device is a BT SCO headset supporting those
6564 // pre processings
6565 if (mTracks.size() > 0) {
6566 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6567 mAudioFlinger->btNrecIsOff();
6568 for (size_t i = 0; i < mTracks.size(); i++) {
6569 sp<RecordTrack> track = mTracks[i];
6570 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6571 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6572 }
6573 }
6574
6575 // store new source and send to effects
6576 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6577 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6578 for (size_t i = 0; i < mEffectChains.size(); i++) {
6579 mEffectChains[i]->setAudioSource_l(mAudioSource);
6580 }
6581 }
6582
6583 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6584 status = hwDevice->create_audio_patch(hwDevice,
6585 patch->num_sources,
6586 patch->sources,
6587 patch->num_sinks,
6588 patch->sinks,
6589 handle);
6590 } else {
6591 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6592 }
6593 return status;
6594}
6595
6596status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6597{
6598 status_t status = NO_ERROR;
6599 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6600 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6601 status = hwDevice->release_audio_patch(hwDevice, handle);
6602 } else {
6603 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6604 }
6605 return status;
6606}
6607
Eric Laurent83b88082014-06-20 18:31:16 -07006608void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6609{
6610 Mutex::Autolock _l(mLock);
6611 mTracks.add(record);
6612}
6613
6614void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6615{
6616 Mutex::Autolock _l(mLock);
6617 destroyTrack_l(record);
6618}
6619
6620void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6621{
6622 ThreadBase::getAudioPortConfig(config);
6623 config->role = AUDIO_PORT_ROLE_SINK;
6624 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6625 config->ext.mix.usecase.source = mAudioSource;
6626}
Eric Laurent1c333e22014-05-20 10:48:17 -07006627
Glenn Kasten63238ef2015-03-02 15:50:29 -08006628} // namespace android