blob: c096bdd09925e557c17eaa7cee3b678b11cc5578 [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
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800744 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700745 dprintf(fd, " I/O handle: %d\n", mId);
746 dprintf(fd, " TID: %d\n", getTid());
747 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700748 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700749 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700750 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700751 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700752 dprintf(fd, " Channel count: %u\n", mChannelCount);
753 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800754 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700755 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
756 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700757 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800758 size_t numConfig = mConfigEvents.size();
759 if (numConfig) {
760 for (size_t i = 0; i < numConfig; i++) {
761 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700762 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800763 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700764 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800765 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700766 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800767 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800768 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
769 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
770 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800771
772 if (locked) {
773 mLock.unlock();
774 }
775}
776
777void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
778{
779 const size_t SIZE = 256;
780 char buffer[SIZE];
781 String8 result;
782
Marco Nelissenb2208842014-02-07 14:00:50 -0800783 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000784 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800785 write(fd, buffer, strlen(buffer));
786
Marco Nelissenb2208842014-02-07 14:00:50 -0800787 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800788 sp<EffectChain> chain = mEffectChains[i];
789 if (chain != 0) {
790 chain->dump(fd, args);
791 }
792 }
793}
794
Marco Nelissene14a5d62013-10-03 08:51:24 -0700795void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800796{
797 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700798 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800799}
800
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100801String16 AudioFlinger::ThreadBase::getWakeLockTag()
802{
803 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800804 case MIXER:
805 return String16("AudioMix");
806 case DIRECT:
807 return String16("AudioDirectOut");
808 case DUPLICATING:
809 return String16("AudioDup");
810 case RECORD:
811 return String16("AudioIn");
812 case OFFLOAD:
813 return String16("AudioOffload");
814 default:
815 ALOG_ASSERT(false);
816 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100817 }
818}
819
Marco Nelissene14a5d62013-10-03 08:51:24 -0700820void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800821{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800822 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800823 if (mPowerManager != 0) {
824 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700825 status_t status;
826 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700827 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700828 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100829 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700830 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700831 uid,
832 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700833 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700834 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700835 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100836 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700837 String16("media"),
838 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700839 }
Eric Laurent81784c32012-11-19 14:55:58 -0800840 if (status == NO_ERROR) {
841 mWakeLockToken = binder;
842 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800843 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800844 }
845}
846
847void AudioFlinger::ThreadBase::releaseWakeLock()
848{
849 Mutex::Autolock _l(mLock);
850 releaseWakeLock_l();
851}
852
853void AudioFlinger::ThreadBase::releaseWakeLock_l()
854{
855 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800856 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800857 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700858 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
859 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800860 }
861 mWakeLockToken.clear();
862 }
863}
864
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800865void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
866 Mutex::Autolock _l(mLock);
867 updateWakeLockUids_l(uids);
868}
869
870void AudioFlinger::ThreadBase::getPowerManager_l() {
871
872 if (mPowerManager == 0) {
873 // use checkService() to avoid blocking if power service is not up yet
874 sp<IBinder> binder =
875 defaultServiceManager()->checkService(String16("power"));
876 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800877 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800878 } else {
879 mPowerManager = interface_cast<IPowerManager>(binder);
880 binder->linkToDeath(mDeathRecipient);
881 }
882 }
883}
884
885void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
886
887 getPowerManager_l();
888 if (mWakeLockToken == NULL) {
889 ALOGE("no wake lock to update!");
890 return;
891 }
892 if (mPowerManager != 0) {
893 sp<IBinder> binder = new BBinder();
894 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700895 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
896 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800897 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800898 }
899}
900
Eric Laurent81784c32012-11-19 14:55:58 -0800901void AudioFlinger::ThreadBase::clearPowerManager()
902{
903 Mutex::Autolock _l(mLock);
904 releaseWakeLock_l();
905 mPowerManager.clear();
906}
907
Glenn Kasten0f11b512014-01-31 16:18:54 -0800908void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800909{
910 sp<ThreadBase> thread = mThread.promote();
911 if (thread != 0) {
912 thread->clearPowerManager();
913 }
914 ALOGW("power manager service died !!!");
915}
916
917void AudioFlinger::ThreadBase::setEffectSuspended(
918 const effect_uuid_t *type, bool suspend, int sessionId)
919{
920 Mutex::Autolock _l(mLock);
921 setEffectSuspended_l(type, suspend, sessionId);
922}
923
924void AudioFlinger::ThreadBase::setEffectSuspended_l(
925 const effect_uuid_t *type, bool suspend, int sessionId)
926{
927 sp<EffectChain> chain = getEffectChain_l(sessionId);
928 if (chain != 0) {
929 if (type != NULL) {
930 chain->setEffectSuspended_l(type, suspend);
931 } else {
932 chain->setEffectSuspendedAll_l(suspend);
933 }
934 }
935
936 updateSuspendedSessions_l(type, suspend, sessionId);
937}
938
939void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
940{
941 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
942 if (index < 0) {
943 return;
944 }
945
946 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
947 mSuspendedSessions.valueAt(index);
948
949 for (size_t i = 0; i < sessionEffects.size(); i++) {
950 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
951 for (int j = 0; j < desc->mRefCount; j++) {
952 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
953 chain->setEffectSuspendedAll_l(true);
954 } else {
955 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
956 desc->mType.timeLow);
957 chain->setEffectSuspended_l(&desc->mType, true);
958 }
959 }
960 }
961}
962
963void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
964 bool suspend,
965 int sessionId)
966{
967 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
968
969 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
970
971 if (suspend) {
972 if (index >= 0) {
973 sessionEffects = mSuspendedSessions.valueAt(index);
974 } else {
975 mSuspendedSessions.add(sessionId, sessionEffects);
976 }
977 } else {
978 if (index < 0) {
979 return;
980 }
981 sessionEffects = mSuspendedSessions.valueAt(index);
982 }
983
984
985 int key = EffectChain::kKeyForSuspendAll;
986 if (type != NULL) {
987 key = type->timeLow;
988 }
989 index = sessionEffects.indexOfKey(key);
990
991 sp<SuspendedSessionDesc> desc;
992 if (suspend) {
993 if (index >= 0) {
994 desc = sessionEffects.valueAt(index);
995 } else {
996 desc = new SuspendedSessionDesc();
997 if (type != NULL) {
998 desc->mType = *type;
999 }
1000 sessionEffects.add(key, desc);
1001 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1002 }
1003 desc->mRefCount++;
1004 } else {
1005 if (index < 0) {
1006 return;
1007 }
1008 desc = sessionEffects.valueAt(index);
1009 if (--desc->mRefCount == 0) {
1010 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1011 sessionEffects.removeItemsAt(index);
1012 if (sessionEffects.isEmpty()) {
1013 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1014 sessionId);
1015 mSuspendedSessions.removeItem(sessionId);
1016 }
1017 }
1018 }
1019 if (!sessionEffects.isEmpty()) {
1020 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1021 }
1022}
1023
1024void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1025 bool enabled,
1026 int sessionId)
1027{
1028 Mutex::Autolock _l(mLock);
1029 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1030}
1031
1032void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1033 bool enabled,
1034 int sessionId)
1035{
1036 if (mType != RECORD) {
1037 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1038 // another session. This gives the priority to well behaved effect control panels
1039 // and applications not using global effects.
1040 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1041 // global effects
1042 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1043 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1044 }
1045 }
1046
1047 sp<EffectChain> chain = getEffectChain_l(sessionId);
1048 if (chain != 0) {
1049 chain->checkSuspendOnEffectEnabled(effect, enabled);
1050 }
1051}
1052
1053// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1054sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1055 const sp<AudioFlinger::Client>& client,
1056 const sp<IEffectClient>& effectClient,
1057 int32_t priority,
1058 int sessionId,
1059 effect_descriptor_t *desc,
1060 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001061 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001062{
1063 sp<EffectModule> effect;
1064 sp<EffectHandle> handle;
1065 status_t lStatus;
1066 sp<EffectChain> chain;
1067 bool chainCreated = false;
1068 bool effectCreated = false;
1069 bool effectRegistered = false;
1070
1071 lStatus = initCheck();
1072 if (lStatus != NO_ERROR) {
1073 ALOGW("createEffect_l() Audio driver not initialized.");
1074 goto Exit;
1075 }
1076
Andy Hung98ef9782014-03-04 14:46:50 -08001077 // Reject any effect on Direct output threads for now, since the format of
1078 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1079 if (mType == DIRECT) {
1080 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001081 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001082 lStatus = BAD_VALUE;
1083 goto Exit;
1084 }
1085
Andy Hung389cfdb2014-08-07 17:49:53 -07001086 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001087 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001088 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1089 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1090 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001091 lStatus = BAD_VALUE;
1092 goto Exit;
1093 }
1094
Eric Laurent5baf2af2013-09-12 17:37:00 -07001095 // Allow global effects only on offloaded and mixer threads
1096 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1097 switch (mType) {
1098 case MIXER:
1099 case OFFLOAD:
1100 break;
1101 case DIRECT:
1102 case DUPLICATING:
1103 case RECORD:
1104 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001105 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1106 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001107 lStatus = BAD_VALUE;
1108 goto Exit;
1109 }
Eric Laurent81784c32012-11-19 14:55:58 -08001110 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001111
Eric Laurent81784c32012-11-19 14:55:58 -08001112 // Only Pre processor effects are allowed on input threads and only on input threads
1113 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1114 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1115 desc->name, desc->flags, mType);
1116 lStatus = BAD_VALUE;
1117 goto Exit;
1118 }
1119
1120 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1121
1122 { // scope for mLock
1123 Mutex::Autolock _l(mLock);
1124
1125 // check for existing effect chain with the requested audio session
1126 chain = getEffectChain_l(sessionId);
1127 if (chain == 0) {
1128 // create a new chain for this session
1129 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1130 chain = new EffectChain(this, sessionId);
1131 addEffectChain_l(chain);
1132 chain->setStrategy(getStrategyForSession_l(sessionId));
1133 chainCreated = true;
1134 } else {
1135 effect = chain->getEffectFromDesc_l(desc);
1136 }
1137
1138 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1139
1140 if (effect == 0) {
1141 int id = mAudioFlinger->nextUniqueId();
1142 // Check CPU and memory usage
1143 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1144 if (lStatus != NO_ERROR) {
1145 goto Exit;
1146 }
1147 effectRegistered = true;
1148 // create a new effect module if none present in the chain
1149 effect = new EffectModule(this, chain, desc, id, sessionId);
1150 lStatus = effect->status();
1151 if (lStatus != NO_ERROR) {
1152 goto Exit;
1153 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001154 effect->setOffloaded(mType == OFFLOAD, mId);
1155
Eric Laurent81784c32012-11-19 14:55:58 -08001156 lStatus = chain->addEffect_l(effect);
1157 if (lStatus != NO_ERROR) {
1158 goto Exit;
1159 }
1160 effectCreated = true;
1161
1162 effect->setDevice(mOutDevice);
1163 effect->setDevice(mInDevice);
1164 effect->setMode(mAudioFlinger->getMode());
1165 effect->setAudioSource(mAudioSource);
1166 }
1167 // create effect handle and connect it to effect module
1168 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001169 lStatus = handle->initCheck();
1170 if (lStatus == OK) {
1171 lStatus = effect->addHandle(handle.get());
1172 }
Eric Laurent81784c32012-11-19 14:55:58 -08001173 if (enabled != NULL) {
1174 *enabled = (int)effect->isEnabled();
1175 }
1176 }
1177
1178Exit:
1179 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1180 Mutex::Autolock _l(mLock);
1181 if (effectCreated) {
1182 chain->removeEffect_l(effect);
1183 }
1184 if (effectRegistered) {
1185 AudioSystem::unregisterEffect(effect->id());
1186 }
1187 if (chainCreated) {
1188 removeEffectChain_l(chain);
1189 }
1190 handle.clear();
1191 }
1192
Glenn Kasten9156ef32013-08-06 15:39:08 -07001193 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001194 return handle;
1195}
1196
1197sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1198{
1199 Mutex::Autolock _l(mLock);
1200 return getEffect_l(sessionId, effectId);
1201}
1202
1203sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1204{
1205 sp<EffectChain> chain = getEffectChain_l(sessionId);
1206 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1207}
1208
1209// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1210// PlaybackThread::mLock held
1211status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1212{
1213 // check for existing effect chain with the requested audio session
1214 int sessionId = effect->sessionId();
1215 sp<EffectChain> chain = getEffectChain_l(sessionId);
1216 bool chainCreated = false;
1217
Eric Laurent5baf2af2013-09-12 17:37:00 -07001218 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1219 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1220 this, effect->desc().name, effect->desc().flags);
1221
Eric Laurent81784c32012-11-19 14:55:58 -08001222 if (chain == 0) {
1223 // create a new chain for this session
1224 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1225 chain = new EffectChain(this, sessionId);
1226 addEffectChain_l(chain);
1227 chain->setStrategy(getStrategyForSession_l(sessionId));
1228 chainCreated = true;
1229 }
1230 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1231
1232 if (chain->getEffectFromId_l(effect->id()) != 0) {
1233 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1234 this, effect->desc().name, chain.get());
1235 return BAD_VALUE;
1236 }
1237
Eric Laurent5baf2af2013-09-12 17:37:00 -07001238 effect->setOffloaded(mType == OFFLOAD, mId);
1239
Eric Laurent81784c32012-11-19 14:55:58 -08001240 status_t status = chain->addEffect_l(effect);
1241 if (status != NO_ERROR) {
1242 if (chainCreated) {
1243 removeEffectChain_l(chain);
1244 }
1245 return status;
1246 }
1247
1248 effect->setDevice(mOutDevice);
1249 effect->setDevice(mInDevice);
1250 effect->setMode(mAudioFlinger->getMode());
1251 effect->setAudioSource(mAudioSource);
1252 return NO_ERROR;
1253}
1254
1255void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1256
1257 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1258 effect_descriptor_t desc = effect->desc();
1259 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1260 detachAuxEffect_l(effect->id());
1261 }
1262
1263 sp<EffectChain> chain = effect->chain().promote();
1264 if (chain != 0) {
1265 // remove effect chain if removing last effect
1266 if (chain->removeEffect_l(effect) == 0) {
1267 removeEffectChain_l(chain);
1268 }
1269 } else {
1270 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1271 }
1272}
1273
1274void AudioFlinger::ThreadBase::lockEffectChains_l(
1275 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1276{
1277 effectChains = mEffectChains;
1278 for (size_t i = 0; i < mEffectChains.size(); i++) {
1279 mEffectChains[i]->lock();
1280 }
1281}
1282
1283void AudioFlinger::ThreadBase::unlockEffectChains(
1284 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1285{
1286 for (size_t i = 0; i < effectChains.size(); i++) {
1287 effectChains[i]->unlock();
1288 }
1289}
1290
1291sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1292{
1293 Mutex::Autolock _l(mLock);
1294 return getEffectChain_l(sessionId);
1295}
1296
1297sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1298{
1299 size_t size = mEffectChains.size();
1300 for (size_t i = 0; i < size; i++) {
1301 if (mEffectChains[i]->sessionId() == sessionId) {
1302 return mEffectChains[i];
1303 }
1304 }
1305 return 0;
1306}
1307
1308void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1309{
1310 Mutex::Autolock _l(mLock);
1311 size_t size = mEffectChains.size();
1312 for (size_t i = 0; i < size; i++) {
1313 mEffectChains[i]->setMode_l(mode);
1314 }
1315}
1316
Eric Laurent83b88082014-06-20 18:31:16 -07001317void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1318{
1319 config->type = AUDIO_PORT_TYPE_MIX;
1320 config->ext.mix.handle = mId;
1321 config->sample_rate = mSampleRate;
1322 config->format = mFormat;
1323 config->channel_mask = mChannelMask;
1324 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1325 AUDIO_PORT_CONFIG_FORMAT;
1326}
1327
1328
Eric Laurent81784c32012-11-19 14:55:58 -08001329// ----------------------------------------------------------------------------
1330// Playback
1331// ----------------------------------------------------------------------------
1332
1333AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1334 AudioStreamOut* output,
1335 audio_io_handle_t id,
1336 audio_devices_t device,
1337 type_t type)
1338 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001339 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001340 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001341 mMixerBuffer(NULL),
1342 mMixerBufferSize(0),
1343 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1344 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001345 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001346 mEffectBuffer(NULL),
1347 mEffectBufferSize(0),
1348 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1349 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001350 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001351 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001352 // mStreamTypes[] initialized in constructor body
1353 mOutput(output),
1354 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1355 mMixerStatus(MIXER_IDLE),
1356 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1357 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001358 mBytesRemaining(0),
1359 mCurrentWriteLength(0),
1360 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001361 mWriteAckSequence(0),
1362 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001363 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001364 mScreenState(AudioFlinger::mScreenState),
1365 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001366 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001367 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001368 // mLatchD, mLatchQ,
1369 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001370{
Glenn Kastend7dca052015-03-05 16:05:54 -08001371 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1372 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001373
1374 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1375 // it would be safer to explicitly pass initial masterVolume/masterMute as
1376 // parameter.
1377 //
1378 // If the HAL we are using has support for master volume or master mute,
1379 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1380 // and the mute set to false).
1381 mMasterVolume = audioFlinger->masterVolume_l();
1382 mMasterMute = audioFlinger->masterMute_l();
1383 if (mOutput && mOutput->audioHwDev) {
1384 if (mOutput->audioHwDev->canSetMasterVolume()) {
1385 mMasterVolume = 1.0;
1386 }
1387
1388 if (mOutput->audioHwDev->canSetMasterMute()) {
1389 mMasterMute = false;
1390 }
1391 }
1392
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001393 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001394
Eric Laurent223fd5c2014-11-11 13:43:36 -08001395 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001396 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001397 stream = (audio_stream_type_t) (stream + 1)) {
1398 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1399 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1400 }
Eric Laurent81784c32012-11-19 14:55:58 -08001401}
1402
1403AudioFlinger::PlaybackThread::~PlaybackThread()
1404{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001405 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001406 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001407 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001408 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001409}
1410
1411void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1412{
1413 dumpInternals(fd, args);
1414 dumpTracks(fd, args);
1415 dumpEffectChains(fd, args);
1416}
1417
Glenn Kasten0f11b512014-01-31 16:18:54 -08001418void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001419{
1420 const size_t SIZE = 256;
1421 char buffer[SIZE];
1422 String8 result;
1423
Marco Nelissenb2208842014-02-07 14:00:50 -08001424 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001425 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1426 const stream_type_t *st = &mStreamTypes[i];
1427 if (i > 0) {
1428 result.appendFormat(", ");
1429 }
1430 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1431 if (st->mute) {
1432 result.append("M");
1433 }
1434 }
1435 result.append("\n");
1436 write(fd, result.string(), result.length());
1437 result.clear();
1438
Eric Laurent81784c32012-11-19 14:55:58 -08001439 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1440 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001441 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001442 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001443
1444 size_t numtracks = mTracks.size();
1445 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001446 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001447 size_t numactiveseen = 0;
1448 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001449 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001450 Track::appendDumpHeader(result);
1451 for (size_t i = 0; i < numtracks; ++i) {
1452 sp<Track> track = mTracks[i];
1453 if (track != 0) {
1454 bool active = mActiveTracks.indexOf(track) >= 0;
1455 if (active) {
1456 numactiveseen++;
1457 }
1458 track->dump(buffer, SIZE, active);
1459 result.append(buffer);
1460 }
1461 }
1462 } else {
1463 result.append("\n");
1464 }
1465 if (numactiveseen != numactive) {
1466 // some tracks in the active list were not in the tracks list
1467 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1468 " not in the track list\n");
1469 result.append(buffer);
1470 Track::appendDumpHeader(result);
1471 for (size_t i = 0; i < numactive; ++i) {
1472 sp<Track> track = mActiveTracks[i].promote();
1473 if (track != 0 && mTracks.indexOf(track) < 0) {
1474 track->dump(buffer, SIZE, true);
1475 result.append(buffer);
1476 }
1477 }
1478 }
1479
1480 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001481}
1482
1483void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1484{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001485 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001486
1487 dumpBase(fd, args);
1488
Elliott Hughes87cebad2014-05-22 10:14:43 -07001489 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1490 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1491 dprintf(fd, " Total writes: %d\n", mNumWrites);
1492 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1493 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1494 dprintf(fd, " Suspend count: %d\n", mSuspended);
1495 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1496 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1497 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1498 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001499 AudioStreamOut *output = mOutput;
1500 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1501 String8 flagsAsString = outputFlagsToString(flags);
1502 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001503}
1504
1505// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001506
1507void AudioFlinger::PlaybackThread::onFirstRef()
1508{
Glenn Kastend7dca052015-03-05 16:05:54 -08001509 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001510}
1511
1512// ThreadBase virtuals
1513void AudioFlinger::PlaybackThread::preExit()
1514{
1515 ALOGV(" preExit()");
1516 // FIXME this is using hard-coded strings but in the future, this functionality will be
1517 // converted to use audio HAL extensions required to support tunneling
1518 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1519}
1520
1521// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1522sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1523 const sp<AudioFlinger::Client>& client,
1524 audio_stream_type_t streamType,
1525 uint32_t sampleRate,
1526 audio_format_t format,
1527 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001528 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001529 const sp<IMemory>& sharedBuffer,
1530 int sessionId,
1531 IAudioFlinger::track_flags_t *flags,
1532 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001533 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001534 status_t *status)
1535{
Glenn Kasten74935e42013-12-19 08:56:45 -08001536 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001537 sp<Track> track;
1538 status_t lStatus;
1539
1540 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1541
1542 // client expresses a preference for FAST, but we get the final say
1543 if (*flags & IAudioFlinger::TRACK_FAST) {
1544 if (
1545 // not timed
1546 (!isTimed) &&
1547 // either of these use cases:
1548 (
1549 // use case 1: shared buffer with any frame count
1550 (
1551 (sharedBuffer != 0)
1552 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001553 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001554 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001555 // we formerly checked for a callback handler (non-0 tid),
1556 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001557 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001558 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001559 )
1560 ) &&
1561 // PCM data
1562 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001563 // identical channel mask to sink, or mono in and stereo sink
1564 (channelMask == mChannelMask ||
1565 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1566 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001567 // hardware sample rate
1568 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001569 // normal mixer has an associated fast mixer
1570 hasFastMixer() &&
1571 // there are sufficient fast track slots available
1572 (mFastTrackAvailMask != 0)
1573 // FIXME test that MixerThread for this fast track has a capable output HAL
1574 // FIXME add a permission test also?
1575 ) {
1576 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1577 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001578 // read the fast track multiplier property the first time it is needed
1579 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1580 if (ok != 0) {
1581 ALOGE("%s pthread_once failed: %d", __func__, ok);
1582 }
1583 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001584 }
1585 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1586 frameCount, mFrameCount);
1587 } else {
1588 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001589 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1590 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001591 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001592 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001593 audio_is_linear_pcm(format),
1594 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1595 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001596 }
1597 }
1598 // For normal PCM streaming tracks, update minimum frame count.
1599 // For compatibility with AudioTrack calculation, buffer depth is forced
1600 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1601 // This is probably too conservative, but legacy application code may depend on it.
1602 // If you change this calculation, also review the start threshold which is related.
1603 if (!(*flags & IAudioFlinger::TRACK_FAST)
1604 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001605 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1606 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1607 if (minBufCount < 2) {
1608 minBufCount = 2;
1609 }
Andy Hung0e48d252015-01-26 11:43:15 -08001610 size_t minFrameCount =
1611 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1612 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001613 frameCount = minFrameCount;
1614 }
Eric Laurent81784c32012-11-19 14:55:58 -08001615 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001616 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001617
Glenn Kastenc3df8382014-03-13 15:05:25 -07001618 switch (mType) {
1619
1620 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001621 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001622 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001623 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1624 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001625 sampleRate, format, channelMask, mOutput, mFormat);
1626 lStatus = BAD_VALUE;
1627 goto Exit;
1628 }
1629 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001630 break;
1631
1632 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001633 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001634 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1635 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001636 sampleRate, format, channelMask, mOutput, mFormat);
1637 lStatus = BAD_VALUE;
1638 goto Exit;
1639 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001640 break;
1641
1642 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001643 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001644 ALOGE("createTrack_l() Bad parameter: format %#x \""
1645 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001646 format, mOutput, mFormat);
1647 lStatus = BAD_VALUE;
1648 goto Exit;
1649 }
Andy Hungcd044842014-08-07 11:04:34 -07001650 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001651 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1652 lStatus = BAD_VALUE;
1653 goto Exit;
1654 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001655 break;
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657 }
1658
1659 lStatus = initCheck();
1660 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001661 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001662 goto Exit;
1663 }
1664
1665 { // scope for mLock
1666 Mutex::Autolock _l(mLock);
1667
1668 // all tracks in same audio session must share the same routing strategy otherwise
1669 // conflicts will happen when tracks are moved from one output to another by audio policy
1670 // manager
1671 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1672 for (size_t i = 0; i < mTracks.size(); ++i) {
1673 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001674 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001675 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1676 if (sessionId == t->sessionId() && strategy != actual) {
1677 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1678 strategy, actual);
1679 lStatus = BAD_VALUE;
1680 goto Exit;
1681 }
1682 }
1683 }
1684
1685 if (!isTimed) {
1686 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001687 channelMask, frameCount, NULL, sharedBuffer,
1688 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001689 } else {
1690 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001691 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001692 }
Glenn Kasten03003332013-08-06 15:40:54 -07001693
1694 // new Track always returns non-NULL,
1695 // but TimedTrack::create() is a factory that could fail by returning NULL
1696 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1697 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001698 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001699 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001700 goto Exit;
1701 }
1702 mTracks.add(track);
1703
1704 sp<EffectChain> chain = getEffectChain_l(sessionId);
1705 if (chain != 0) {
1706 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1707 track->setMainBuffer(chain->inBuffer());
1708 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1709 chain->incTrackCnt();
1710 }
1711
1712 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1713 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1714 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1715 // so ask activity manager to do this on our behalf
1716 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1717 }
1718 }
1719
1720 lStatus = NO_ERROR;
1721
1722Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001723 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001724 return track;
1725}
1726
1727uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1728{
1729 return latency;
1730}
1731
1732uint32_t AudioFlinger::PlaybackThread::latency() const
1733{
1734 Mutex::Autolock _l(mLock);
1735 return latency_l();
1736}
1737uint32_t AudioFlinger::PlaybackThread::latency_l() const
1738{
1739 if (initCheck() == NO_ERROR) {
1740 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1741 } else {
1742 return 0;
1743 }
1744}
1745
1746void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1747{
1748 Mutex::Autolock _l(mLock);
1749 // Don't apply master volume in SW if our HAL can do it for us.
1750 if (mOutput && mOutput->audioHwDev &&
1751 mOutput->audioHwDev->canSetMasterVolume()) {
1752 mMasterVolume = 1.0;
1753 } else {
1754 mMasterVolume = value;
1755 }
1756}
1757
1758void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1759{
1760 Mutex::Autolock _l(mLock);
1761 // Don't apply master mute in SW if our HAL can do it for us.
1762 if (mOutput && mOutput->audioHwDev &&
1763 mOutput->audioHwDev->canSetMasterMute()) {
1764 mMasterMute = false;
1765 } else {
1766 mMasterMute = muted;
1767 }
1768}
1769
1770void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1771{
1772 Mutex::Autolock _l(mLock);
1773 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001774 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001775}
1776
1777void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1778{
1779 Mutex::Autolock _l(mLock);
1780 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001781 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001782}
1783
1784float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1785{
1786 Mutex::Autolock _l(mLock);
1787 return mStreamTypes[stream].volume;
1788}
1789
1790// addTrack_l() must be called with ThreadBase::mLock held
1791status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1792{
1793 status_t status = ALREADY_EXISTS;
1794
1795 // set retry count for buffer fill
1796 track->mRetryCount = kMaxTrackStartupRetries;
1797 if (mActiveTracks.indexOf(track) < 0) {
1798 // the track is newly added, make sure it fills up all its
1799 // buffers before playing. This is to ensure the client will
1800 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001801 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001802 TrackBase::track_state state = track->mState;
1803 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001804 status = AudioSystem::startOutput(mId, track->streamType(),
1805 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001806 mLock.lock();
1807 // abort track was stopped/paused while we released the lock
1808 if (state != track->mState) {
1809 if (status == NO_ERROR) {
1810 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001811 AudioSystem::stopOutput(mId, track->streamType(),
1812 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001813 mLock.lock();
1814 }
1815 return INVALID_OPERATION;
1816 }
1817 // abort if start is rejected by audio policy manager
1818 if (status != NO_ERROR) {
1819 return PERMISSION_DENIED;
1820 }
1821#ifdef ADD_BATTERY_DATA
1822 // to track the speaker usage
1823 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1824#endif
1825 }
1826
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001827 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001828 track->mResetDone = false;
1829 track->mPresentationCompleteFrames = 0;
1830 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001831 mWakeLockUids.add(track->uid());
1832 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001833 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001834 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1835 if (chain != 0) {
1836 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1837 track->sessionId());
1838 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001839 }
1840
1841 status = NO_ERROR;
1842 }
1843
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001844 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001845 return status;
1846}
1847
Eric Laurentbfb1b832013-01-07 09:53:42 -08001848bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001849{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001851 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001852 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1853 track->mState = TrackBase::STOPPED;
1854 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001855 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001856 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001857 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001858 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001859
1860 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001861}
1862
1863void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1864{
1865 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1866 mTracks.remove(track);
1867 deleteTrackName_l(track->name());
1868 // redundant as track is about to be destroyed, for dumpsys only
1869 track->mName = -1;
1870 if (track->isFastTrack()) {
1871 int index = track->mFastIndex;
1872 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1873 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1874 mFastTrackAvailMask |= 1 << index;
1875 // redundant as track is about to be destroyed, for dumpsys only
1876 track->mFastIndex = -1;
1877 }
1878 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1879 if (chain != 0) {
1880 chain->decTrackCnt();
1881 }
1882}
1883
Eric Laurentede6c3b2013-09-19 14:37:46 -07001884void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001885{
1886 // Thread could be blocked waiting for async
1887 // so signal it to handle state changes immediately
1888 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1889 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1890 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001891 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001892}
1893
Eric Laurent81784c32012-11-19 14:55:58 -08001894String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1895{
Eric Laurent81784c32012-11-19 14:55:58 -08001896 Mutex::Autolock _l(mLock);
1897 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001898 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001899 }
1900
Glenn Kastend8ea6992013-07-16 14:17:15 -07001901 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1902 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001903 free(s);
1904 return out_s8;
1905}
1906
Eric Laurent021cf962014-05-13 10:18:14 -07001907void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001908 AudioSystem::OutputDescriptor desc;
1909 void *param2 = NULL;
1910
Eric Laurent021cf962014-05-13 10:18:14 -07001911 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001912 param);
1913
1914 switch (event) {
1915 case AudioSystem::OUTPUT_OPENED:
1916 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001917 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001918 desc.samplingRate = mSampleRate;
1919 desc.format = mFormat;
1920 desc.frameCount = mNormalFrameCount; // FIXME see
1921 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001922 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001923 param2 = &desc;
1924 break;
1925
1926 case AudioSystem::STREAM_CONFIG_CHANGED:
1927 param2 = &param;
1928 case AudioSystem::OUTPUT_CLOSED:
1929 default:
1930 break;
1931 }
Eric Laurent021cf962014-05-13 10:18:14 -07001932 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001933}
1934
Eric Laurentbfb1b832013-01-07 09:53:42 -08001935void AudioFlinger::PlaybackThread::writeCallback()
1936{
1937 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001938 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001939}
1940
1941void AudioFlinger::PlaybackThread::drainCallback()
1942{
1943 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001944 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001945}
1946
Eric Laurent3b4529e2013-09-05 18:09:19 -07001947void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001948{
1949 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001950 // reject out of sequence requests
1951 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1952 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001953 mWaitWorkCV.signal();
1954 }
1955}
1956
Eric Laurent3b4529e2013-09-05 18:09:19 -07001957void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958{
1959 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001960 // reject out of sequence requests
1961 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1962 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 mWaitWorkCV.signal();
1964 }
1965}
1966
1967// static
1968int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001969 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 void *cookie)
1971{
1972 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1973 ALOGV("asyncCallback() event %d", event);
1974 switch (event) {
1975 case STREAM_CBK_EVENT_WRITE_READY:
1976 me->writeCallback();
1977 break;
1978 case STREAM_CBK_EVENT_DRAIN_READY:
1979 me->drainCallback();
1980 break;
1981 default:
1982 ALOGW("asyncCallback() unknown event %d", event);
1983 break;
1984 }
1985 return 0;
1986}
1987
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001988void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001989{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001990 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001991 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1992 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001993 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001994 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001995 }
Andy Hung9a592762014-07-21 21:56:01 -07001996 if ((mType == MIXER || mType == DUPLICATING)
1997 && !isValidPcmSinkChannelMask(mChannelMask)) {
1998 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1999 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002000 }
Andy Hunge5412692014-05-16 11:25:07 -07002001 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002002 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2003 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002004 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002005 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002006 }
Andy Hung6146c082014-03-18 11:56:15 -07002007 if ((mType == MIXER || mType == DUPLICATING)
2008 && !isValidPcmSinkFormat(mFormat)) {
2009 LOG_FATAL("HAL format %#x not supported for mixed output",
2010 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002011 }
Phil Burk062e67a2015-02-11 13:40:50 -08002012 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002013 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2014 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002015 if (mFrameCount & 15) {
2016 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2017 mFrameCount);
2018 }
2019
Eric Laurentbfb1b832013-01-07 09:53:42 -08002020 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2021 (mOutput->stream->set_callback != NULL)) {
2022 if (mOutput->stream->set_callback(mOutput->stream,
2023 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2024 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002025 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002026 }
2027 }
2028
Eric Laurentd1f69b02014-12-15 14:33:13 -08002029 mHwSupportsPause = false;
2030 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2031 if (mOutput->stream->pause != NULL) {
2032 if (mOutput->stream->resume != NULL) {
2033 mHwSupportsPause = true;
2034 } else {
2035 ALOGW("direct output implements pause but not resume");
2036 }
2037 } else if (mOutput->stream->resume != NULL) {
2038 ALOGW("direct output implements resume but not pause");
2039 }
2040 }
2041
Andy Hungfbfc3952015-01-15 13:33:51 -08002042 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2043 // For best precision, we use float instead of the associated output
2044 // device format (typically PCM 16 bit).
2045
2046 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2047 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2048 mBufferSize = mFrameSize * mFrameCount;
2049
2050 // TODO: We currently use the associated output device channel mask and sample rate.
2051 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2052 // (if a valid mask) to avoid premature downmix.
2053 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2054 // instead of the output device sample rate to avoid loss of high frequency information.
2055 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2056 }
2057
Andy Hung09a50072014-02-27 14:30:47 -08002058 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002059 double multiplier = 1.0;
2060 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2061 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002062 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2063 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002064 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2065 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2066 maxNormalFrameCount = maxNormalFrameCount & ~15;
2067 if (maxNormalFrameCount < minNormalFrameCount) {
2068 maxNormalFrameCount = minNormalFrameCount;
2069 }
2070 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2071 if (multiplier <= 1.0) {
2072 multiplier = 1.0;
2073 } else if (multiplier <= 2.0) {
2074 if (2 * mFrameCount <= maxNormalFrameCount) {
2075 multiplier = 2.0;
2076 } else {
2077 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2078 }
2079 } else {
2080 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002081 // 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 -08002082 // track, but we sometimes have to do this to satisfy the maximum frame count
2083 // constraint)
2084 // FIXME this rounding up should not be done if no HAL SRC
2085 uint32_t truncMult = (uint32_t) multiplier;
2086 if ((truncMult & 1)) {
2087 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2088 ++truncMult;
2089 }
2090 }
2091 multiplier = (double) truncMult;
2092 }
2093 }
2094 mNormalFrameCount = multiplier * mFrameCount;
2095 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002096 if (mType == MIXER || mType == DUPLICATING) {
2097 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2098 }
Andy Hung09a50072014-02-27 14:30:47 -08002099 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002100 mNormalFrameCount);
2101
Andy Hung010a1a12014-03-13 13:57:33 -07002102 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2103 // Originally this was int16_t[] array, need to remove legacy implications.
2104 free(mSinkBuffer);
2105 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002106 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2107 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2108 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002109 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002110
Andy Hung69aed5f2014-02-25 17:24:40 -08002111 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2112 // drives the output.
2113 free(mMixerBuffer);
2114 mMixerBuffer = NULL;
2115 if (mMixerBufferEnabled) {
2116 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2117 mMixerBufferSize = mNormalFrameCount * mChannelCount
2118 * audio_bytes_per_sample(mMixerBufferFormat);
2119 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2120 }
Andy Hung98ef9782014-03-04 14:46:50 -08002121 free(mEffectBuffer);
2122 mEffectBuffer = NULL;
2123 if (mEffectBufferEnabled) {
2124 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2125 mEffectBufferSize = mNormalFrameCount * mChannelCount
2126 * audio_bytes_per_sample(mEffectBufferFormat);
2127 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2128 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002129
Eric Laurent81784c32012-11-19 14:55:58 -08002130 // force reconfiguration of effect chains and engines to take new buffer size and audio
2131 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002132 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002133 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2134 // matter.
2135 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2136 Vector< sp<EffectChain> > effectChains = mEffectChains;
2137 for (size_t i = 0; i < effectChains.size(); i ++) {
2138 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2139 }
2140}
2141
2142
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002143status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002144{
2145 if (halFrames == NULL || dspFrames == NULL) {
2146 return BAD_VALUE;
2147 }
2148 Mutex::Autolock _l(mLock);
2149 if (initCheck() != NO_ERROR) {
2150 return INVALID_OPERATION;
2151 }
2152 size_t framesWritten = mBytesWritten / mFrameSize;
2153 *halFrames = framesWritten;
2154
2155 if (isSuspended()) {
2156 // return an estimation of rendered frames when the output is suspended
2157 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2158 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2159 return NO_ERROR;
2160 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002161 status_t status;
2162 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002163 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002164 *dspFrames = (size_t)frames;
2165 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002166 }
2167}
2168
2169uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2170{
2171 Mutex::Autolock _l(mLock);
2172 uint32_t result = 0;
2173 if (getEffectChain_l(sessionId) != 0) {
2174 result = EFFECT_SESSION;
2175 }
2176
2177 for (size_t i = 0; i < mTracks.size(); ++i) {
2178 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002179 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002180 result |= TRACK_SESSION;
2181 break;
2182 }
2183 }
2184
2185 return result;
2186}
2187
2188uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2189{
2190 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2191 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2192 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2193 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2194 }
2195 for (size_t i = 0; i < mTracks.size(); i++) {
2196 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002197 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002198 return AudioSystem::getStrategyForStream(track->streamType());
2199 }
2200 }
2201 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2202}
2203
2204
Phil Burk062e67a2015-02-11 13:40:50 -08002205AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002206{
2207 Mutex::Autolock _l(mLock);
2208 return mOutput;
2209}
2210
Phil Burk062e67a2015-02-11 13:40:50 -08002211AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002212{
2213 Mutex::Autolock _l(mLock);
2214 AudioStreamOut *output = mOutput;
2215 mOutput = NULL;
2216 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2217 // must push a NULL and wait for ack
2218 mOutputSink.clear();
2219 mPipeSink.clear();
2220 mNormalSink.clear();
2221 return output;
2222}
2223
2224// this method must always be called either with ThreadBase mLock held or inside the thread loop
2225audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2226{
2227 if (mOutput == NULL) {
2228 return NULL;
2229 }
2230 return &mOutput->stream->common;
2231}
2232
2233uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2234{
2235 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2236}
2237
2238status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2239{
2240 if (!isValidSyncEvent(event)) {
2241 return BAD_VALUE;
2242 }
2243
2244 Mutex::Autolock _l(mLock);
2245
2246 for (size_t i = 0; i < mTracks.size(); ++i) {
2247 sp<Track> track = mTracks[i];
2248 if (event->triggerSession() == track->sessionId()) {
2249 (void) track->setSyncEvent(event);
2250 return NO_ERROR;
2251 }
2252 }
2253
2254 return NAME_NOT_FOUND;
2255}
2256
2257bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2258{
2259 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2260}
2261
2262void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2263 const Vector< sp<Track> >& tracksToRemove)
2264{
2265 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002266 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002267 for (size_t i = 0 ; i < count ; i++) {
2268 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002269 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002270 AudioSystem::stopOutput(mId, track->streamType(),
2271 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272#ifdef ADD_BATTERY_DATA
2273 // to track the speaker usage
2274 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2275#endif
2276 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002277 AudioSystem::releaseOutput(mId, track->streamType(),
2278 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279 }
Eric Laurent81784c32012-11-19 14:55:58 -08002280 }
2281 }
2282 }
Eric Laurent81784c32012-11-19 14:55:58 -08002283}
2284
2285void AudioFlinger::PlaybackThread::checkSilentMode_l()
2286{
2287 if (!mMasterMute) {
2288 char value[PROPERTY_VALUE_MAX];
2289 if (property_get("ro.audio.silent", value, "0") > 0) {
2290 char *endptr;
2291 unsigned long ul = strtoul(value, &endptr, 0);
2292 if (*endptr == '\0' && ul != 0) {
2293 ALOGD("Silence is golden");
2294 // The setprop command will not allow a property to be changed after
2295 // the first time it is set, so we don't have to worry about un-muting.
2296 setMasterMute_l(true);
2297 }
2298 }
2299 }
2300}
2301
2302// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002304{
2305 // FIXME rewrite to reduce number of system calls
2306 mLastWriteTime = systemTime();
2307 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002308 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002309 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002310
2311 // If an NBAIO sink is present, use it to write the normal mixer's submix
2312 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002313
Andy Hung010a1a12014-03-13 13:57:33 -07002314 const size_t count = mBytesRemaining / mFrameSize;
2315
Simon Wilson2d590962012-11-29 15:18:50 -08002316 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002317 // update the setpoint when AudioFlinger::mScreenState changes
2318 uint32_t screenState = AudioFlinger::mScreenState;
2319 if (screenState != mScreenState) {
2320 mScreenState = screenState;
2321 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2322 if (pipe != NULL) {
2323 pipe->setAvgFrames((mScreenState & 1) ?
2324 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2325 }
2326 }
Andy Hung010a1a12014-03-13 13:57:33 -07002327 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002328 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002329 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002330 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002331 } else {
2332 bytesWritten = framesWritten;
2333 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002334 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002335 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002336 if (status == NO_ERROR) {
2337 size_t totalFramesWritten = mNormalSink->framesWritten();
2338 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2339 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002340 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002341 mLatchDValid = true;
2342 }
2343 }
Eric Laurent81784c32012-11-19 14:55:58 -08002344 // otherwise use the HAL / AudioStreamOut directly
2345 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002347
Eric Laurentbfb1b832013-01-07 09:53:42 -08002348 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002349 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2350 mWriteAckSequence += 2;
2351 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002353 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002355 // FIXME We should have an implementation of timestamps for direct output threads.
2356 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002357 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002358 if (mUseAsyncWrite &&
2359 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2360 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002361 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002362 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002363 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 }
Eric Laurent81784c32012-11-19 14:55:58 -08002365 }
2366
Eric Laurent81784c32012-11-19 14:55:58 -08002367 mNumWrites++;
2368 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002369 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 return bytesWritten;
2371}
2372
2373void AudioFlinger::PlaybackThread::threadLoop_drain()
2374{
2375 if (mOutput->stream->drain) {
2376 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2377 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002378 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2379 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002381 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002382 }
2383 mOutput->stream->drain(mOutput->stream,
2384 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2385 : AUDIO_DRAIN_ALL);
2386 }
2387}
2388
2389void AudioFlinger::PlaybackThread::threadLoop_exit()
2390{
Eric Laurent275e8e92014-11-30 15:14:47 -08002391 {
2392 Mutex::Autolock _l(mLock);
2393 for (size_t i = 0; i < mTracks.size(); i++) {
2394 sp<Track> track = mTracks[i];
2395 track->invalidate();
2396 }
2397 }
Eric Laurent81784c32012-11-19 14:55:58 -08002398}
2399
2400/*
2401The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002402 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002403 - activeSleepTime from activeSleepTimeUs()
2404 - idleSleepTime from idleSleepTimeUs()
2405 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2406 - maxPeriod from frame count and sample rate (MIXER only)
2407
2408The parameters that affect these derived values are:
2409 - frame count
2410 - frame size
2411 - sample rate
2412 - device type: A2DP or not
2413 - device latency
2414 - format: PCM or not
2415 - active sleep time
2416 - idle sleep time
2417*/
2418
2419void AudioFlinger::PlaybackThread::cacheParameters_l()
2420{
Andy Hung25c2dac2014-02-27 14:56:00 -08002421 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002422 activeSleepTime = activeSleepTimeUs();
2423 idleSleepTime = idleSleepTimeUs();
2424}
2425
2426void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2427{
Glenn Kasten7c027242012-12-26 14:43:16 -08002428 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002429 this, streamType, mTracks.size());
2430 Mutex::Autolock _l(mLock);
2431
2432 size_t size = mTracks.size();
2433 for (size_t i = 0; i < size; i++) {
2434 sp<Track> t = mTracks[i];
2435 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002436 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002437 }
2438 }
2439}
2440
2441status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2442{
2443 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002444 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2445 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002446 bool ownsBuffer = false;
2447
2448 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2449 if (session > 0) {
2450 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002451 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002452 if (mType != DIRECT) {
2453 size_t numSamples = mNormalFrameCount * mChannelCount;
2454 buffer = new int16_t[numSamples];
2455 memset(buffer, 0, numSamples * sizeof(int16_t));
2456 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2457 ownsBuffer = true;
2458 }
2459
2460 // Attach all tracks with same session ID to this chain.
2461 for (size_t i = 0; i < mTracks.size(); ++i) {
2462 sp<Track> track = mTracks[i];
2463 if (session == track->sessionId()) {
2464 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2465 buffer);
2466 track->setMainBuffer(buffer);
2467 chain->incTrackCnt();
2468 }
2469 }
2470
2471 // indicate all active tracks in the chain
2472 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2473 sp<Track> track = mActiveTracks[i].promote();
2474 if (track == 0) {
2475 continue;
2476 }
2477 if (session == track->sessionId()) {
2478 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2479 chain->incActiveTrackCnt();
2480 }
2481 }
2482 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002483 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002484 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002485 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2486 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002487 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2488 // chains list in order to be processed last as it contains output stage effects
2489 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2490 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2491 // after track specific effects and before output stage
2492 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2493 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2494 // Effect chain for other sessions are inserted at beginning of effect
2495 // chains list to be processed before output mix effects. Relative order between other
2496 // sessions is not important
2497 size_t size = mEffectChains.size();
2498 size_t i = 0;
2499 for (i = 0; i < size; i++) {
2500 if (mEffectChains[i]->sessionId() < session) {
2501 break;
2502 }
2503 }
2504 mEffectChains.insertAt(chain, i);
2505 checkSuspendOnAddEffectChain_l(chain);
2506
2507 return NO_ERROR;
2508}
2509
2510size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2511{
2512 int session = chain->sessionId();
2513
2514 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2515
2516 for (size_t i = 0; i < mEffectChains.size(); i++) {
2517 if (chain == mEffectChains[i]) {
2518 mEffectChains.removeAt(i);
2519 // detach all active tracks from the chain
2520 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2521 sp<Track> track = mActiveTracks[i].promote();
2522 if (track == 0) {
2523 continue;
2524 }
2525 if (session == track->sessionId()) {
2526 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2527 chain.get(), session);
2528 chain->decActiveTrackCnt();
2529 }
2530 }
2531
2532 // detach all tracks with same session ID from this chain
2533 for (size_t i = 0; i < mTracks.size(); ++i) {
2534 sp<Track> track = mTracks[i];
2535 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002536 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002537 chain->decTrackCnt();
2538 }
2539 }
2540 break;
2541 }
2542 }
2543 return mEffectChains.size();
2544}
2545
2546status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2547 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2548{
2549 Mutex::Autolock _l(mLock);
2550 return attachAuxEffect_l(track, EffectId);
2551}
2552
2553status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2554 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2555{
2556 status_t status = NO_ERROR;
2557
2558 if (EffectId == 0) {
2559 track->setAuxBuffer(0, NULL);
2560 } else {
2561 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2562 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2563 if (effect != 0) {
2564 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2565 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2566 } else {
2567 status = INVALID_OPERATION;
2568 }
2569 } else {
2570 status = BAD_VALUE;
2571 }
2572 }
2573 return status;
2574}
2575
2576void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2577{
2578 for (size_t i = 0; i < mTracks.size(); ++i) {
2579 sp<Track> track = mTracks[i];
2580 if (track->auxEffectId() == effectId) {
2581 attachAuxEffect_l(track, 0);
2582 }
2583 }
2584}
2585
2586bool AudioFlinger::PlaybackThread::threadLoop()
2587{
2588 Vector< sp<Track> > tracksToRemove;
2589
2590 standbyTime = systemTime();
2591
2592 // MIXER
2593 nsecs_t lastWarning = 0;
2594
2595 // DUPLICATING
2596 // FIXME could this be made local to while loop?
2597 writeFrames = 0;
2598
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002599 int lastGeneration = 0;
2600
Eric Laurent81784c32012-11-19 14:55:58 -08002601 cacheParameters_l();
2602 sleepTime = idleSleepTime;
2603
2604 if (mType == MIXER) {
2605 sleepTimeShift = 0;
2606 }
2607
2608 CpuStats cpuStats;
2609 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2610
2611 acquireWakeLock();
2612
Glenn Kasten9e58b552013-01-18 15:09:48 -08002613 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2614 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2615 // and then that string will be logged at the next convenient opportunity.
2616 const char *logString = NULL;
2617
Eric Laurent664539d2013-09-23 18:24:31 -07002618 checkSilentMode_l();
2619
Eric Laurent81784c32012-11-19 14:55:58 -08002620 while (!exitPending())
2621 {
2622 cpuStats.sample(myName);
2623
2624 Vector< sp<EffectChain> > effectChains;
2625
Eric Laurent81784c32012-11-19 14:55:58 -08002626 { // scope for mLock
2627
2628 Mutex::Autolock _l(mLock);
2629
Eric Laurent021cf962014-05-13 10:18:14 -07002630 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002631
Glenn Kasten9e58b552013-01-18 15:09:48 -08002632 if (logString != NULL) {
2633 mNBLogWriter->logTimestamp();
2634 mNBLogWriter->log(logString);
2635 logString = NULL;
2636 }
2637
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002638 // Gather the framesReleased counters for all active tracks,
2639 // and latch them atomically with the timestamp.
2640 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2641 mLatchD.mFramesReleased.clear();
2642 size_t size = mActiveTracks.size();
2643 for (size_t i = 0; i < size; i++) {
2644 sp<Track> t = mActiveTracks[i].promote();
2645 if (t != 0) {
2646 mLatchD.mFramesReleased.add(t.get(),
2647 t->mAudioTrackServerProxy->framesReleased());
2648 }
2649 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002650 if (mLatchDValid) {
2651 mLatchQ = mLatchD;
2652 mLatchDValid = false;
2653 mLatchQValid = true;
2654 }
2655
Eric Laurent81784c32012-11-19 14:55:58 -08002656 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 if (mSignalPending) {
2658 // A signal was raised while we were unlocked
2659 mSignalPending = false;
2660 } else if (waitingAsyncCallback_l()) {
2661 if (exitPending()) {
2662 break;
2663 }
2664 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002665 mWakeLockUids.clear();
2666 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 ALOGV("wait async completion");
2668 mWaitWorkCV.wait(mLock);
2669 ALOGV("async completion/wake");
2670 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002671 standbyTime = systemTime() + standbyDelay;
2672 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002673
2674 continue;
2675 }
2676 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 isSuspended()) {
2678 // put audio hardware into standby after short delay
2679 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002680
2681 threadLoop_standby();
2682
2683 mStandby = true;
2684 }
2685
2686 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2687 // we're about to wait, flush the binder command buffer
2688 IPCThreadState::self()->flushCommands();
2689
2690 clearOutputTracks();
2691
2692 if (exitPending()) {
2693 break;
2694 }
2695
2696 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002697 mWakeLockUids.clear();
2698 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002699 // wait until we have something to do...
2700 ALOGV("%s going to sleep", myName.string());
2701 mWaitWorkCV.wait(mLock);
2702 ALOGV("%s waking up", myName.string());
2703 acquireWakeLock_l();
2704
2705 mMixerStatus = MIXER_IDLE;
2706 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2707 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002708 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002709 checkSilentMode_l();
2710
2711 standbyTime = systemTime() + standbyDelay;
2712 sleepTime = idleSleepTime;
2713 if (mType == MIXER) {
2714 sleepTimeShift = 0;
2715 }
2716
2717 continue;
2718 }
2719 }
Eric Laurent81784c32012-11-19 14:55:58 -08002720 // mMixerStatusIgnoringFastTracks is also updated internally
2721 mMixerStatus = prepareTracks_l(&tracksToRemove);
2722
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002723 // compare with previously applied list
2724 if (lastGeneration != mActiveTracksGeneration) {
2725 // update wakelock
2726 updateWakeLockUids_l(mWakeLockUids);
2727 lastGeneration = mActiveTracksGeneration;
2728 }
2729
Eric Laurent81784c32012-11-19 14:55:58 -08002730 // prevent any changes in effect chain list and in each effect chain
2731 // during mixing and effect process as the audio buffers could be deleted
2732 // or modified if an effect is created or deleted
2733 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002734 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002735
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 if (mBytesRemaining == 0) {
2737 mCurrentWriteLength = 0;
2738 if (mMixerStatus == MIXER_TRACKS_READY) {
2739 // threadLoop_mix() sets mCurrentWriteLength
2740 threadLoop_mix();
2741 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2742 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2743 // threadLoop_sleepTime sets sleepTime to 0 if data
2744 // must be written to HAL
2745 threadLoop_sleepTime();
2746 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002747 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748 }
2749 }
Andy Hung98ef9782014-03-04 14:46:50 -08002750 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2751 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2752 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2753 // or mSinkBuffer (if there are no effects).
2754 //
2755 // This is done pre-effects computation; if effects change to
2756 // support higher precision, this needs to move.
2757 //
2758 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2759 // TODO use sleepTime == 0 as an additional condition.
2760 if (mMixerBufferValid) {
2761 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2762 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2763
2764 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2765 mNormalFrameCount * mChannelCount);
2766 }
2767
Eric Laurentbfb1b832013-01-07 09:53:42 -08002768 mBytesRemaining = mCurrentWriteLength;
2769 if (isSuspended()) {
2770 sleepTime = suspendSleepTimeUs();
2771 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002772 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002773 mBytesRemaining = 0;
2774 }
Eric Laurent81784c32012-11-19 14:55:58 -08002775
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002777 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778 for (size_t i = 0; i < effectChains.size(); i ++) {
2779 effectChains[i]->process_l();
2780 }
Eric Laurent81784c32012-11-19 14:55:58 -08002781 }
2782 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002783 // Process effect chains for offloaded thread even if no audio
2784 // was read from audio track: process only updates effect state
2785 // and thus does have to be synchronized with audio writes but may have
2786 // to be called while waiting for async write callback
2787 if (mType == OFFLOAD) {
2788 for (size_t i = 0; i < effectChains.size(); i ++) {
2789 effectChains[i]->process_l();
2790 }
2791 }
Eric Laurent81784c32012-11-19 14:55:58 -08002792
Andy Hung98ef9782014-03-04 14:46:50 -08002793 // Only if the Effects buffer is enabled and there is data in the
2794 // Effects buffer (buffer valid), we need to
2795 // copy into the sink buffer.
2796 // TODO use sleepTime == 0 as an additional condition.
2797 if (mEffectBufferValid) {
2798 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2799 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2800 mNormalFrameCount * mChannelCount);
2801 }
2802
Eric Laurent81784c32012-11-19 14:55:58 -08002803 // enable changes in effect chain
2804 unlockEffectChains(effectChains);
2805
Eric Laurentbfb1b832013-01-07 09:53:42 -08002806 if (!waitingAsyncCallback()) {
2807 // sleepTime == 0 means we must write to audio hardware
2808 if (sleepTime == 0) {
2809 if (mBytesRemaining) {
2810 ssize_t ret = threadLoop_write();
2811 if (ret < 0) {
2812 mBytesRemaining = 0;
2813 } else {
2814 mBytesWritten += ret;
2815 mBytesRemaining -= ret;
2816 }
2817 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2818 (mMixerStatus == MIXER_DRAIN_ALL)) {
2819 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002820 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002821 if (mType == MIXER) {
2822 // write blocked detection
2823 nsecs_t now = systemTime();
2824 nsecs_t delta = now - mLastWriteTime;
2825 if (!mStandby && delta > maxPeriod) {
2826 mNumDelayedWrites++;
2827 if ((now - lastWarning) > kWarningThrottleNs) {
2828 ATRACE_NAME("underrun");
2829 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2830 ns2ms(delta), mNumDelayedWrites, this);
2831 lastWarning = now;
2832 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002833 }
2834 }
Eric Laurent81784c32012-11-19 14:55:58 -08002835
Eric Laurentbfb1b832013-01-07 09:53:42 -08002836 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002837 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002838 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002839 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002840 }
Eric Laurent81784c32012-11-19 14:55:58 -08002841 }
2842
2843 // Finally let go of removed track(s), without the lock held
2844 // since we can't guarantee the destructors won't acquire that
2845 // same lock. This will also mutate and push a new fast mixer state.
2846 threadLoop_removeTracks(tracksToRemove);
2847 tracksToRemove.clear();
2848
2849 // FIXME I don't understand the need for this here;
2850 // it was in the original code but maybe the
2851 // assignment in saveOutputTracks() makes this unnecessary?
2852 clearOutputTracks();
2853
2854 // Effect chains will be actually deleted here if they were removed from
2855 // mEffectChains list during mixing or effects processing
2856 effectChains.clear();
2857
2858 // FIXME Note that the above .clear() is no longer necessary since effectChains
2859 // is now local to this block, but will keep it for now (at least until merge done).
2860 }
2861
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862 threadLoop_exit();
2863
Eric Laurentcf817a22014-08-04 20:36:31 -07002864 if (!mStandby) {
2865 threadLoop_standby();
2866 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002867 }
2868
2869 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002870 mWakeLockUids.clear();
2871 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002872
2873 ALOGV("Thread %p type %d exiting", this, mType);
2874 return false;
2875}
2876
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877// removeTracks_l() must be called with ThreadBase::mLock held
2878void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2879{
2880 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002881 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 for (size_t i=0 ; i<count ; i++) {
2883 const sp<Track>& track = tracksToRemove.itemAt(i);
2884 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002885 mWakeLockUids.remove(track->uid());
2886 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2888 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2889 if (chain != 0) {
2890 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2891 track->sessionId());
2892 chain->decActiveTrackCnt();
2893 }
2894 if (track->isTerminated()) {
2895 removeTrack_l(track);
2896 }
2897 }
2898 }
2899
2900}
Eric Laurent81784c32012-11-19 14:55:58 -08002901
Eric Laurentaccc1472013-09-20 09:36:34 -07002902status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2903{
2904 if (mNormalSink != 0) {
2905 return mNormalSink->getTimestamp(timestamp);
2906 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002907 if ((mType == OFFLOAD || mType == DIRECT)
2908 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002909 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002910 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002911 if (ret == 0) {
2912 timestamp.mPosition = (uint32_t)position64;
2913 return NO_ERROR;
2914 }
2915 }
2916 return INVALID_OPERATION;
2917}
Eric Laurent1c333e22014-05-20 10:48:17 -07002918
2919status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2920 audio_patch_handle_t *handle)
2921{
2922 status_t status = NO_ERROR;
2923 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2924 // store new device and send to effects
2925 audio_devices_t type = AUDIO_DEVICE_NONE;
2926 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2927 type |= patch->sinks[i].ext.device.type;
2928 }
2929 mOutDevice = type;
2930 for (size_t i = 0; i < mEffectChains.size(); i++) {
2931 mEffectChains[i]->setDevice_l(mOutDevice);
2932 }
2933
2934 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2935 status = hwDevice->create_audio_patch(hwDevice,
2936 patch->num_sources,
2937 patch->sources,
2938 patch->num_sinks,
2939 patch->sinks,
2940 handle);
2941 } else {
2942 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2943 }
2944 return status;
2945}
2946
2947status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2948{
2949 status_t status = NO_ERROR;
2950 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2951 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2952 status = hwDevice->release_audio_patch(hwDevice, handle);
2953 } else {
2954 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2955 }
2956 return status;
2957}
2958
Eric Laurent83b88082014-06-20 18:31:16 -07002959void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2960{
2961 Mutex::Autolock _l(mLock);
2962 mTracks.add(track);
2963}
2964
2965void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2966{
2967 Mutex::Autolock _l(mLock);
2968 destroyTrack_l(track);
2969}
2970
2971void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2972{
2973 ThreadBase::getAudioPortConfig(config);
2974 config->role = AUDIO_PORT_ROLE_SOURCE;
2975 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2976 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2977}
2978
Eric Laurent81784c32012-11-19 14:55:58 -08002979// ----------------------------------------------------------------------------
2980
2981AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2982 audio_io_handle_t id, audio_devices_t device, type_t type)
2983 : PlaybackThread(audioFlinger, output, id, device, type),
2984 // mAudioMixer below
2985 // mFastMixer below
2986 mFastMixerFutex(0)
2987 // mOutputSink below
2988 // mPipeSink below
2989 // mNormalSink below
2990{
2991 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002992 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002993 "mFrameCount=%d, mNormalFrameCount=%d",
2994 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2995 mNormalFrameCount);
2996 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2997
Andy Hungfbfc3952015-01-15 13:33:51 -08002998 if (type == DUPLICATING) {
2999 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3000 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3001 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3002 return;
3003 }
Eric Laurent81784c32012-11-19 14:55:58 -08003004 // create an NBAIO sink for the HAL output stream, and negotiate
3005 mOutputSink = new AudioStreamOutSink(output->stream);
3006 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003007 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003008 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3009 ALOG_ASSERT(index == 0);
3010
3011 // initialize fast mixer depending on configuration
3012 bool initFastMixer;
3013 switch (kUseFastMixer) {
3014 case FastMixer_Never:
3015 initFastMixer = false;
3016 break;
3017 case FastMixer_Always:
3018 initFastMixer = true;
3019 break;
3020 case FastMixer_Static:
3021 case FastMixer_Dynamic:
3022 initFastMixer = mFrameCount < mNormalFrameCount;
3023 break;
3024 }
3025 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003026 audio_format_t fastMixerFormat;
3027 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3028 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3029 } else {
3030 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3031 }
3032 if (mFormat != fastMixerFormat) {
3033 // change our Sink format to accept our intermediate precision
3034 mFormat = fastMixerFormat;
3035 free(mSinkBuffer);
3036 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3037 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3038 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3039 }
Eric Laurent81784c32012-11-19 14:55:58 -08003040
3041 // create a MonoPipe to connect our submix to FastMixer
3042 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003043 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003044 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003045 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003046 format.mFormat = fastMixerFormat;
3047 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3048
Eric Laurent81784c32012-11-19 14:55:58 -08003049 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3050 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3051 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3052 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3053 const NBAIO_Format offers[1] = {format};
3054 size_t numCounterOffers = 0;
3055 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3056 ALOG_ASSERT(index == 0);
3057 monoPipe->setAvgFrames((mScreenState & 1) ?
3058 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3059 mPipeSink = monoPipe;
3060
Glenn Kasten46909e72013-02-26 09:20:22 -08003061#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003062 if (mTeeSinkOutputEnabled) {
3063 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003064 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3065 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003066 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003067 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003068 ALOG_ASSERT(index == 0);
3069 mTeeSink = teeSink;
3070 PipeReader *teeSource = new PipeReader(*teeSink);
3071 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003072 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003073 ALOG_ASSERT(index == 0);
3074 mTeeSource = teeSource;
3075 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003076#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003077
3078 // create fast mixer and configure it initially with just one fast track for our submix
3079 mFastMixer = new FastMixer();
3080 FastMixerStateQueue *sq = mFastMixer->sq();
3081#ifdef STATE_QUEUE_DUMP
3082 sq->setObserverDump(&mStateQueueObserverDump);
3083 sq->setMutatorDump(&mStateQueueMutatorDump);
3084#endif
3085 FastMixerState *state = sq->begin();
3086 FastTrack *fastTrack = &state->mFastTracks[0];
3087 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3088 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3089 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003090 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3091 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003092 fastTrack->mGeneration++;
3093 state->mFastTracksGen++;
3094 state->mTrackMask = 1;
3095 // fast mixer will use the HAL output sink
3096 state->mOutputSink = mOutputSink.get();
3097 state->mOutputSinkGen++;
3098 state->mFrameCount = mFrameCount;
3099 state->mCommand = FastMixerState::COLD_IDLE;
3100 // already done in constructor initialization list
3101 //mFastMixerFutex = 0;
3102 state->mColdFutexAddr = &mFastMixerFutex;
3103 state->mColdGen++;
3104 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003105#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003106 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003107#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003108 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3109 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003110 sq->end();
3111 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3112
3113 // start the fast mixer
3114 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3115 pid_t tid = mFastMixer->getTid();
3116 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3117 if (err != 0) {
3118 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3119 kPriorityFastMixer, getpid_cached, tid, err);
3120 }
3121
3122#ifdef AUDIO_WATCHDOG
3123 // create and start the watchdog
3124 mAudioWatchdog = new AudioWatchdog();
3125 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3126 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3127 tid = mAudioWatchdog->getTid();
3128 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3129 if (err != 0) {
3130 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3131 kPriorityFastMixer, getpid_cached, tid, err);
3132 }
3133#endif
3134
Eric Laurent81784c32012-11-19 14:55:58 -08003135 }
3136
3137 switch (kUseFastMixer) {
3138 case FastMixer_Never:
3139 case FastMixer_Dynamic:
3140 mNormalSink = mOutputSink;
3141 break;
3142 case FastMixer_Always:
3143 mNormalSink = mPipeSink;
3144 break;
3145 case FastMixer_Static:
3146 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3147 break;
3148 }
3149}
3150
3151AudioFlinger::MixerThread::~MixerThread()
3152{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003153 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003154 FastMixerStateQueue *sq = mFastMixer->sq();
3155 FastMixerState *state = sq->begin();
3156 if (state->mCommand == FastMixerState::COLD_IDLE) {
3157 int32_t old = android_atomic_inc(&mFastMixerFutex);
3158 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003159 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003160 }
3161 }
3162 state->mCommand = FastMixerState::EXIT;
3163 sq->end();
3164 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3165 mFastMixer->join();
3166 // Though the fast mixer thread has exited, it's state queue is still valid.
3167 // We'll use that extract the final state which contains one remaining fast track
3168 // corresponding to our sub-mix.
3169 state = sq->begin();
3170 ALOG_ASSERT(state->mTrackMask == 1);
3171 FastTrack *fastTrack = &state->mFastTracks[0];
3172 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3173 delete fastTrack->mBufferProvider;
3174 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003175 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003176#ifdef AUDIO_WATCHDOG
3177 if (mAudioWatchdog != 0) {
3178 mAudioWatchdog->requestExit();
3179 mAudioWatchdog->requestExitAndWait();
3180 mAudioWatchdog.clear();
3181 }
3182#endif
3183 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003184 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003185 delete mAudioMixer;
3186}
3187
3188
3189uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3190{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003191 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003192 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3193 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3194 }
3195 return latency;
3196}
3197
3198
3199void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3200{
3201 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3202}
3203
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003205{
3206 // FIXME we should only do one push per cycle; confirm this is true
3207 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003208 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003209 FastMixerStateQueue *sq = mFastMixer->sq();
3210 FastMixerState *state = sq->begin();
3211 if (state->mCommand != FastMixerState::MIX_WRITE &&
3212 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3213 if (state->mCommand == FastMixerState::COLD_IDLE) {
3214 int32_t old = android_atomic_inc(&mFastMixerFutex);
3215 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003216 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003217 }
3218#ifdef AUDIO_WATCHDOG
3219 if (mAudioWatchdog != 0) {
3220 mAudioWatchdog->resume();
3221 }
3222#endif
3223 }
3224 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003225#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003226 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003227 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003228#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003229 sq->end();
3230 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3231 if (kUseFastMixer == FastMixer_Dynamic) {
3232 mNormalSink = mPipeSink;
3233 }
3234 } else {
3235 sq->end(false /*didModify*/);
3236 }
3237 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003239}
3240
3241void AudioFlinger::MixerThread::threadLoop_standby()
3242{
3243 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003244 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003245 FastMixerStateQueue *sq = mFastMixer->sq();
3246 FastMixerState *state = sq->begin();
3247 if (!(state->mCommand & FastMixerState::IDLE)) {
3248 state->mCommand = FastMixerState::COLD_IDLE;
3249 state->mColdFutexAddr = &mFastMixerFutex;
3250 state->mColdGen++;
3251 mFastMixerFutex = 0;
3252 sq->end();
3253 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3254 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3255 if (kUseFastMixer == FastMixer_Dynamic) {
3256 mNormalSink = mOutputSink;
3257 }
3258#ifdef AUDIO_WATCHDOG
3259 if (mAudioWatchdog != 0) {
3260 mAudioWatchdog->pause();
3261 }
3262#endif
3263 } else {
3264 sq->end(false /*didModify*/);
3265 }
3266 }
3267 PlaybackThread::threadLoop_standby();
3268}
3269
Eric Laurentbfb1b832013-01-07 09:53:42 -08003270bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3271{
3272 return false;
3273}
3274
3275bool AudioFlinger::PlaybackThread::shouldStandby_l()
3276{
3277 return !mStandby;
3278}
3279
3280bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3281{
3282 Mutex::Autolock _l(mLock);
3283 return waitingAsyncCallback_l();
3284}
3285
Eric Laurent81784c32012-11-19 14:55:58 -08003286// shared by MIXER and DIRECT, overridden by DUPLICATING
3287void AudioFlinger::PlaybackThread::threadLoop_standby()
3288{
3289 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003290 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003291 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003292 // discard any pending drain or write ack by incrementing sequence
3293 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3294 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003296 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3297 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003298 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003299 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003300}
3301
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003302void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3303{
3304 ALOGV("signal playback thread");
3305 broadcast_l();
3306}
3307
Eric Laurent81784c32012-11-19 14:55:58 -08003308void AudioFlinger::MixerThread::threadLoop_mix()
3309{
3310 // obtain the presentation timestamp of the next output buffer
3311 int64_t pts;
3312 status_t status = INVALID_OPERATION;
3313
3314 if (mNormalSink != 0) {
3315 status = mNormalSink->getNextWriteTimestamp(&pts);
3316 } else {
3317 status = mOutputSink->getNextWriteTimestamp(&pts);
3318 }
3319
3320 if (status != NO_ERROR) {
3321 pts = AudioBufferProvider::kInvalidPTS;
3322 }
3323
3324 // mix buffers...
3325 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003326 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003327 // increase sleep time progressively when application underrun condition clears.
3328 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3329 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3330 // such that we would underrun the audio HAL.
3331 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3332 sleepTimeShift--;
3333 }
3334 sleepTime = 0;
3335 standbyTime = systemTime() + standbyDelay;
3336 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003337
Eric Laurent81784c32012-11-19 14:55:58 -08003338}
3339
3340void AudioFlinger::MixerThread::threadLoop_sleepTime()
3341{
3342 // If no tracks are ready, sleep once for the duration of an output
3343 // buffer size, then write 0s to the output
3344 if (sleepTime == 0) {
3345 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3346 sleepTime = activeSleepTime >> sleepTimeShift;
3347 if (sleepTime < kMinThreadSleepTimeUs) {
3348 sleepTime = kMinThreadSleepTimeUs;
3349 }
3350 // reduce sleep time in case of consecutive application underruns to avoid
3351 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3352 // duration we would end up writing less data than needed by the audio HAL if
3353 // the condition persists.
3354 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3355 sleepTimeShift++;
3356 }
3357 } else {
3358 sleepTime = idleSleepTime;
3359 }
3360 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003361 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3362 // before effects processing or output.
3363 if (mMixerBufferValid) {
3364 memset(mMixerBuffer, 0, mMixerBufferSize);
3365 } else {
3366 memset(mSinkBuffer, 0, mSinkBufferSize);
3367 }
Eric Laurent81784c32012-11-19 14:55:58 -08003368 sleepTime = 0;
3369 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3370 "anticipated start");
3371 }
3372 // TODO add standby time extension fct of effect tail
3373}
3374
3375// prepareTracks_l() must be called with ThreadBase::mLock held
3376AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3377 Vector< sp<Track> > *tracksToRemove)
3378{
3379
3380 mixer_state mixerStatus = MIXER_IDLE;
3381 // find out which tracks need to be processed
3382 size_t count = mActiveTracks.size();
3383 size_t mixedTracks = 0;
3384 size_t tracksWithEffect = 0;
3385 // counts only _active_ fast tracks
3386 size_t fastTracks = 0;
3387 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3388
3389 float masterVolume = mMasterVolume;
3390 bool masterMute = mMasterMute;
3391
3392 if (masterMute) {
3393 masterVolume = 0;
3394 }
3395 // Delegate master volume control to effect in output mix effect chain if needed
3396 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3397 if (chain != 0) {
3398 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3399 chain->setVolume_l(&v, &v);
3400 masterVolume = (float)((v + (1 << 23)) >> 24);
3401 chain.clear();
3402 }
3403
3404 // prepare a new state to push
3405 FastMixerStateQueue *sq = NULL;
3406 FastMixerState *state = NULL;
3407 bool didModify = false;
3408 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003409 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003410 sq = mFastMixer->sq();
3411 state = sq->begin();
3412 }
3413
Andy Hung69aed5f2014-02-25 17:24:40 -08003414 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003415 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003416
Eric Laurent81784c32012-11-19 14:55:58 -08003417 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003418 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003419 if (t == 0) {
3420 continue;
3421 }
3422
3423 // this const just means the local variable doesn't change
3424 Track* const track = t.get();
3425
3426 // process fast tracks
3427 if (track->isFastTrack()) {
3428
3429 // It's theoretically possible (though unlikely) for a fast track to be created
3430 // and then removed within the same normal mix cycle. This is not a problem, as
3431 // the track never becomes active so it's fast mixer slot is never touched.
3432 // The converse, of removing an (active) track and then creating a new track
3433 // at the identical fast mixer slot within the same normal mix cycle,
3434 // is impossible because the slot isn't marked available until the end of each cycle.
3435 int j = track->mFastIndex;
3436 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3437 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3438 FastTrack *fastTrack = &state->mFastTracks[j];
3439
3440 // Determine whether the track is currently in underrun condition,
3441 // and whether it had a recent underrun.
3442 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3443 FastTrackUnderruns underruns = ftDump->mUnderruns;
3444 uint32_t recentFull = (underruns.mBitFields.mFull -
3445 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3446 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3447 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3448 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3449 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3450 uint32_t recentUnderruns = recentPartial + recentEmpty;
3451 track->mObservedUnderruns = underruns;
3452 // don't count underruns that occur while stopping or pausing
3453 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003454 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3455 recentUnderruns > 0) {
3456 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3457 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003458 }
3459
3460 // This is similar to the state machine for normal tracks,
3461 // with a few modifications for fast tracks.
3462 bool isActive = true;
3463 switch (track->mState) {
3464 case TrackBase::STOPPING_1:
3465 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003467 track->mState = TrackBase::STOPPING_2;
3468 }
3469 break;
3470 case TrackBase::PAUSING:
3471 // ramp down is not yet implemented
3472 track->setPaused();
3473 break;
3474 case TrackBase::RESUMING:
3475 // ramp up is not yet implemented
3476 track->mState = TrackBase::ACTIVE;
3477 break;
3478 case TrackBase::ACTIVE:
3479 if (recentFull > 0 || recentPartial > 0) {
3480 // track has provided at least some frames recently: reset retry count
3481 track->mRetryCount = kMaxTrackRetries;
3482 }
3483 if (recentUnderruns == 0) {
3484 // no recent underruns: stay active
3485 break;
3486 }
3487 // there has recently been an underrun of some kind
3488 if (track->sharedBuffer() == 0) {
3489 // were any of the recent underruns "empty" (no frames available)?
3490 if (recentEmpty == 0) {
3491 // no, then ignore the partial underruns as they are allowed indefinitely
3492 break;
3493 }
3494 // there has recently been an "empty" underrun: decrement the retry counter
3495 if (--(track->mRetryCount) > 0) {
3496 break;
3497 }
3498 // indicate to client process that the track was disabled because of underrun;
3499 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003500 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003501 // remove from active list, but state remains ACTIVE [confusing but true]
3502 isActive = false;
3503 break;
3504 }
3505 // fall through
3506 case TrackBase::STOPPING_2:
3507 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003508 case TrackBase::STOPPED:
3509 case TrackBase::FLUSHED: // flush() while active
3510 // Check for presentation complete if track is inactive
3511 // We have consumed all the buffers of this track.
3512 // This would be incomplete if we auto-paused on underrun
3513 {
3514 size_t audioHALFrames =
3515 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3516 size_t framesWritten = mBytesWritten / mFrameSize;
3517 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3518 // track stays in active list until presentation is complete
3519 break;
3520 }
3521 }
3522 if (track->isStopping_2()) {
3523 track->mState = TrackBase::STOPPED;
3524 }
3525 if (track->isStopped()) {
3526 // Can't reset directly, as fast mixer is still polling this track
3527 // track->reset();
3528 // So instead mark this track as needing to be reset after push with ack
3529 resetMask |= 1 << i;
3530 }
3531 isActive = false;
3532 break;
3533 case TrackBase::IDLE:
3534 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003535 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003536 }
3537
3538 if (isActive) {
3539 // was it previously inactive?
3540 if (!(state->mTrackMask & (1 << j))) {
3541 ExtendedAudioBufferProvider *eabp = track;
3542 VolumeProvider *vp = track;
3543 fastTrack->mBufferProvider = eabp;
3544 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003545 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003546 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003547 fastTrack->mGeneration++;
3548 state->mTrackMask |= 1 << j;
3549 didModify = true;
3550 // no acknowledgement required for newly active tracks
3551 }
3552 // cache the combined master volume and stream type volume for fast mixer; this
3553 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003554 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003555 ++fastTracks;
3556 } else {
3557 // was it previously active?
3558 if (state->mTrackMask & (1 << j)) {
3559 fastTrack->mBufferProvider = NULL;
3560 fastTrack->mGeneration++;
3561 state->mTrackMask &= ~(1 << j);
3562 didModify = true;
3563 // If any fast tracks were removed, we must wait for acknowledgement
3564 // because we're about to decrement the last sp<> on those tracks.
3565 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3566 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003567 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003568 }
3569 tracksToRemove->add(track);
3570 // Avoids a misleading display in dumpsys
3571 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3572 }
3573 continue;
3574 }
3575
3576 { // local variable scope to avoid goto warning
3577
3578 audio_track_cblk_t* cblk = track->cblk();
3579
3580 // The first time a track is added we wait
3581 // for all its buffers to be filled before processing it
3582 int name = track->name();
3583 // make sure that we have enough frames to mix one full buffer.
3584 // enforce this condition only once to enable draining the buffer in case the client
3585 // app does not call stop() and relies on underrun to stop:
3586 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3587 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003588 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003589 uint32_t sr = track->sampleRate();
3590 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003591 desiredFrames = mNormalFrameCount;
3592 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003593 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003594 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003595 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003596 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003597#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003598 // the minimum track buffer size is normally twice the number of frames necessary
3599 // to fill one buffer and the resampler should not leave more than one buffer worth
3600 // of unreleased frames after each pass, but just in case...
3601 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003602#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003603 }
Eric Laurent81784c32012-11-19 14:55:58 -08003604 uint32_t minFrames = 1;
3605 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3606 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003607 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003608 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003609
3610 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003611 if (ATRACE_ENABLED()) {
3612 // I wish we had formatted trace names
3613 char traceName[16];
3614 strcpy(traceName, "nRdy");
3615 int name = track->name();
3616 if (AudioMixer::TRACK0 <= name &&
3617 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3618 name -= AudioMixer::TRACK0;
3619 traceName[4] = (name / 10) + '0';
3620 traceName[5] = (name % 10) + '0';
3621 } else {
3622 traceName[4] = '?';
3623 traceName[5] = '?';
3624 }
3625 traceName[6] = '\0';
3626 ATRACE_INT(traceName, framesReady);
3627 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003628 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003629 !track->isPaused() && !track->isTerminated())
3630 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003631 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003632
3633 mixedTracks++;
3634
Andy Hung69aed5f2014-02-25 17:24:40 -08003635 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3636 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003637 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003638 if (track->mainBuffer() != mSinkBuffer &&
3639 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003640 if (mEffectBufferEnabled) {
3641 mEffectBufferValid = true; // Later can set directly.
3642 }
Eric Laurent81784c32012-11-19 14:55:58 -08003643 chain = getEffectChain_l(track->sessionId());
3644 // Delegate volume control to effect in track effect chain if needed
3645 if (chain != 0) {
3646 tracksWithEffect++;
3647 } else {
3648 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3649 "session %d",
3650 name, track->sessionId());
3651 }
3652 }
3653
3654
3655 int param = AudioMixer::VOLUME;
3656 if (track->mFillingUpStatus == Track::FS_FILLED) {
3657 // no ramp for the first volume setting
3658 track->mFillingUpStatus = Track::FS_ACTIVE;
3659 if (track->mState == TrackBase::RESUMING) {
3660 track->mState = TrackBase::ACTIVE;
3661 param = AudioMixer::RAMP_VOLUME;
3662 }
3663 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003664 // FIXME should not make a decision based on mServer
3665 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003666 // If the track is stopped before the first frame was mixed,
3667 // do not apply ramp
3668 param = AudioMixer::RAMP_VOLUME;
3669 }
3670
3671 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003672 uint32_t vl, vr; // in U8.24 integer format
3673 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003674 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003675 vl = vr = 0;
3676 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003677 if (track->isPausing()) {
3678 track->setPaused();
3679 }
3680 } else {
3681
3682 // read original volumes with volume control
3683 float typeVolume = mStreamTypes[track->streamType()].volume;
3684 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003685 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003686 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003687 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3688 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003689 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003690 if (vlf > GAIN_FLOAT_UNITY) {
3691 ALOGV("Track left volume out of range: %.3g", vlf);
3692 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003693 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003694 if (vrf > GAIN_FLOAT_UNITY) {
3695 ALOGV("Track right volume out of range: %.3g", vrf);
3696 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003697 }
3698 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003699 vlf *= v;
3700 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003701 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003702 // then derive vl and vr as U8.24 versions for the effect chain
3703 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3704 vl = (uint32_t) (scaleto8_24 * vlf);
3705 vr = (uint32_t) (scaleto8_24 * vrf);
3706 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003707 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003708 // send level comes from shared memory and so may be corrupt
3709 if (sendLevel > MAX_GAIN_INT) {
3710 ALOGV("Track send level out of range: %04X", sendLevel);
3711 sendLevel = MAX_GAIN_INT;
3712 }
Andy Hung6be49402014-05-30 10:42:03 -07003713 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3714 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003715 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003716
Eric Laurent81784c32012-11-19 14:55:58 -08003717 // Delegate volume control to effect in track effect chain if needed
3718 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3719 // Do not ramp volume if volume is controlled by effect
3720 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003721 // Update remaining floating point volume levels
3722 vlf = (float)vl / (1 << 24);
3723 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003724 track->mHasVolumeController = true;
3725 } else {
3726 // force no volume ramp when volume controller was just disabled or removed
3727 // from effect chain to avoid volume spike
3728 if (track->mHasVolumeController) {
3729 param = AudioMixer::VOLUME;
3730 }
3731 track->mHasVolumeController = false;
3732 }
3733
Eric Laurent81784c32012-11-19 14:55:58 -08003734 // XXX: these things DON'T need to be done each time
3735 mAudioMixer->setBufferProvider(name, track);
3736 mAudioMixer->enable(name);
3737
Andy Hung6be49402014-05-30 10:42:03 -07003738 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3739 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3740 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003741 mAudioMixer->setParameter(
3742 name,
3743 AudioMixer::TRACK,
3744 AudioMixer::FORMAT, (void *)track->format());
3745 mAudioMixer->setParameter(
3746 name,
3747 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003748 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003749 mAudioMixer->setParameter(
3750 name,
3751 AudioMixer::TRACK,
3752 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003753 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003754 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003755 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003756 if (reqSampleRate == 0) {
3757 reqSampleRate = mSampleRate;
3758 } else if (reqSampleRate > maxSampleRate) {
3759 reqSampleRate = maxSampleRate;
3760 }
Eric Laurent81784c32012-11-19 14:55:58 -08003761 mAudioMixer->setParameter(
3762 name,
3763 AudioMixer::RESAMPLE,
3764 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003765 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003766 /*
3767 * Select the appropriate output buffer for the track.
3768 *
Andy Hung98ef9782014-03-04 14:46:50 -08003769 * Tracks with effects go into their own effects chain buffer
3770 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003771 *
3772 * Other tracks can use mMixerBuffer for higher precision
3773 * channel accumulation. If this buffer is enabled
3774 * (mMixerBufferEnabled true), then selected tracks will accumulate
3775 * into it.
3776 *
3777 */
3778 if (mMixerBufferEnabled
3779 && (track->mainBuffer() == mSinkBuffer
3780 || track->mainBuffer() == mMixerBuffer)) {
3781 mAudioMixer->setParameter(
3782 name,
3783 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003784 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003785 mAudioMixer->setParameter(
3786 name,
3787 AudioMixer::TRACK,
3788 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3789 // TODO: override track->mainBuffer()?
3790 mMixerBufferValid = true;
3791 } else {
3792 mAudioMixer->setParameter(
3793 name,
3794 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003795 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003796 mAudioMixer->setParameter(
3797 name,
3798 AudioMixer::TRACK,
3799 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3800 }
Eric Laurent81784c32012-11-19 14:55:58 -08003801 mAudioMixer->setParameter(
3802 name,
3803 AudioMixer::TRACK,
3804 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3805
3806 // reset retry count
3807 track->mRetryCount = kMaxTrackRetries;
3808
3809 // If one track is ready, set the mixer ready if:
3810 // - the mixer was not ready during previous round OR
3811 // - no other track is not ready
3812 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3813 mixerStatus != MIXER_TRACKS_ENABLED) {
3814 mixerStatus = MIXER_TRACKS_READY;
3815 }
3816 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003817 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003818 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003819 }
Eric Laurent81784c32012-11-19 14:55:58 -08003820 // clear effect chain input buffer if an active track underruns to avoid sending
3821 // previous audio buffer again to effects
3822 chain = getEffectChain_l(track->sessionId());
3823 if (chain != 0) {
3824 chain->clearInputBuffer();
3825 }
3826
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003827 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003828 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3829 track->isStopped() || track->isPaused()) {
3830 // We have consumed all the buffers of this track.
3831 // Remove it from the list of active tracks.
3832 // TODO: use actual buffer filling status instead of latency when available from
3833 // audio HAL
3834 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3835 size_t framesWritten = mBytesWritten / mFrameSize;
3836 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3837 if (track->isStopped()) {
3838 track->reset();
3839 }
3840 tracksToRemove->add(track);
3841 }
3842 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003843 // No buffers for this track. Give it a few chances to
3844 // fill a buffer, then remove it from active list.
3845 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003846 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003847 tracksToRemove->add(track);
3848 // indicate to client process that the track was disabled because of underrun;
3849 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003850 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003851 // If one track is not ready, mark the mixer also not ready if:
3852 // - the mixer was ready during previous round OR
3853 // - no other track is ready
3854 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3855 mixerStatus != MIXER_TRACKS_READY) {
3856 mixerStatus = MIXER_TRACKS_ENABLED;
3857 }
3858 }
3859 mAudioMixer->disable(name);
3860 }
3861
3862 } // local variable scope to avoid goto warning
3863track_is_ready: ;
3864
3865 }
3866
3867 // Push the new FastMixer state if necessary
3868 bool pauseAudioWatchdog = false;
3869 if (didModify) {
3870 state->mFastTracksGen++;
3871 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3872 if (kUseFastMixer == FastMixer_Dynamic &&
3873 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3874 state->mCommand = FastMixerState::COLD_IDLE;
3875 state->mColdFutexAddr = &mFastMixerFutex;
3876 state->mColdGen++;
3877 mFastMixerFutex = 0;
3878 if (kUseFastMixer == FastMixer_Dynamic) {
3879 mNormalSink = mOutputSink;
3880 }
3881 // If we go into cold idle, need to wait for acknowledgement
3882 // so that fast mixer stops doing I/O.
3883 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3884 pauseAudioWatchdog = true;
3885 }
Eric Laurent81784c32012-11-19 14:55:58 -08003886 }
3887 if (sq != NULL) {
3888 sq->end(didModify);
3889 sq->push(block);
3890 }
3891#ifdef AUDIO_WATCHDOG
3892 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3893 mAudioWatchdog->pause();
3894 }
3895#endif
3896
3897 // Now perform the deferred reset on fast tracks that have stopped
3898 while (resetMask != 0) {
3899 size_t i = __builtin_ctz(resetMask);
3900 ALOG_ASSERT(i < count);
3901 resetMask &= ~(1 << i);
3902 sp<Track> t = mActiveTracks[i].promote();
3903 if (t == 0) {
3904 continue;
3905 }
3906 Track* track = t.get();
3907 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3908 track->reset();
3909 }
3910
3911 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003912 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003913
Eric Laurent97d547d2014-09-02 14:45:53 -07003914 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3915 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003916 }
3917
3918 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003919 // as long as there are effects we should clear the effects buffer, to avoid
3920 // passing a non-clean buffer to the effect chain
3921 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003922 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003923 // sink or mix buffer must be cleared if all tracks are connected to an
3924 // effect chain as in this case the mixer will not write to the sink or mix buffer
3925 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003926 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3927 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003928 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003929 if (mMixerBufferValid) {
3930 memset(mMixerBuffer, 0, mMixerBufferSize);
3931 // TODO: In testing, mSinkBuffer below need not be cleared because
3932 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3933 // after mixing.
3934 //
3935 // To enforce this guarantee:
3936 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3937 // (mixedTracks == 0 && fastTracks > 0))
3938 // must imply MIXER_TRACKS_READY.
3939 // Later, we may clear buffers regardless, and skip much of this logic.
3940 }
Andy Hung98ef9782014-03-04 14:46:50 -08003941 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003942 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003943 }
3944
3945 // if any fast tracks, then status is ready
3946 mMixerStatusIgnoringFastTracks = mixerStatus;
3947 if (fastTracks > 0) {
3948 mixerStatus = MIXER_TRACKS_READY;
3949 }
3950 return mixerStatus;
3951}
3952
3953// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003954int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3955 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003956{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003957 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003958}
3959
3960// deleteTrackName_l() must be called with ThreadBase::mLock held
3961void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3962{
3963 ALOGV("remove track (%d) and delete from mixer", name);
3964 mAudioMixer->deleteTrackName(name);
3965}
3966
Eric Laurent10351942014-05-08 18:49:52 -07003967// checkForNewParameter_l() must be called with ThreadBase::mLock held
3968bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3969 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003970{
Eric Laurent81784c32012-11-19 14:55:58 -08003971 bool reconfig = false;
3972
Eric Laurent10351942014-05-08 18:49:52 -07003973 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003974
Eric Laurent10351942014-05-08 18:49:52 -07003975 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3976 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003977 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003978 FastMixerStateQueue *sq = mFastMixer->sq();
3979 FastMixerState *state = sq->begin();
3980 if (!(state->mCommand & FastMixerState::IDLE)) {
3981 previousCommand = state->mCommand;
3982 state->mCommand = FastMixerState::HOT_IDLE;
3983 sq->end();
3984 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3985 } else {
3986 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003987 }
Eric Laurent10351942014-05-08 18:49:52 -07003988 }
Eric Laurent81784c32012-11-19 14:55:58 -08003989
Eric Laurent10351942014-05-08 18:49:52 -07003990 AudioParameter param = AudioParameter(keyValuePair);
3991 int value;
3992 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3993 reconfig = true;
3994 }
3995 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003996 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003997 status = BAD_VALUE;
3998 } else {
3999 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004000 reconfig = true;
4001 }
Eric Laurent10351942014-05-08 18:49:52 -07004002 }
4003 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004004 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004005 status = BAD_VALUE;
4006 } else {
4007 // no need to save value, since it's constant
4008 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004009 }
Eric Laurent10351942014-05-08 18:49:52 -07004010 }
4011 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4012 // do not accept frame count changes if tracks are open as the track buffer
4013 // size depends on frame count and correct behavior would not be guaranteed
4014 // if frame count is changed after track creation
4015 if (!mTracks.isEmpty()) {
4016 status = INVALID_OPERATION;
4017 } else {
4018 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004019 }
Eric Laurent10351942014-05-08 18:49:52 -07004020 }
4021 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004022#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004023 // when changing the audio output device, call addBatteryData to notify
4024 // the change
4025 if (mOutDevice != value) {
4026 uint32_t params = 0;
4027 // check whether speaker is on
4028 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4029 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004030 }
Eric Laurent10351942014-05-08 18:49:52 -07004031
4032 audio_devices_t deviceWithoutSpeaker
4033 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4034 // check if any other device (except speaker) is on
4035 if (value & deviceWithoutSpeaker ) {
4036 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4037 }
4038
4039 if (params != 0) {
4040 addBatteryData(params);
4041 }
4042 }
Eric Laurent81784c32012-11-19 14:55:58 -08004043#endif
4044
Eric Laurent10351942014-05-08 18:49:52 -07004045 // forward device change to effects that have requested to be
4046 // aware of attached audio device.
4047 if (value != AUDIO_DEVICE_NONE) {
4048 mOutDevice = value;
4049 for (size_t i = 0; i < mEffectChains.size(); i++) {
4050 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004051 }
4052 }
Eric Laurent10351942014-05-08 18:49:52 -07004053 }
Eric Laurent81784c32012-11-19 14:55:58 -08004054
Eric Laurent10351942014-05-08 18:49:52 -07004055 if (status == NO_ERROR) {
4056 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4057 keyValuePair.string());
4058 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004059 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004060 mStandby = true;
4061 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004062 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004063 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004064 }
Eric Laurent10351942014-05-08 18:49:52 -07004065 if (status == NO_ERROR && reconfig) {
4066 readOutputParameters_l();
4067 delete mAudioMixer;
4068 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4069 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004070 int name = getTrackName_l(mTracks[i]->mChannelMask,
4071 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004072 if (name < 0) {
4073 break;
4074 }
4075 mTracks[i]->mName = name;
4076 }
4077 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4078 }
Eric Laurent81784c32012-11-19 14:55:58 -08004079 }
4080
4081 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004082 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004083 FastMixerStateQueue *sq = mFastMixer->sq();
4084 FastMixerState *state = sq->begin();
4085 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4086 state->mCommand = previousCommand;
4087 sq->end();
4088 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4089 }
4090
4091 return reconfig;
4092}
4093
4094
4095void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4096{
4097 const size_t SIZE = 256;
4098 char buffer[SIZE];
4099 String8 result;
4100
4101 PlaybackThread::dumpInternals(fd, args);
4102
Elliott Hughes87cebad2014-05-22 10:14:43 -07004103 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004104
4105 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004106 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004107 copy.dump(fd);
4108
4109#ifdef STATE_QUEUE_DUMP
4110 // Similar for state queue
4111 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4112 observerCopy.dump(fd);
4113 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4114 mutatorCopy.dump(fd);
4115#endif
4116
Glenn Kasten46909e72013-02-26 09:20:22 -08004117#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004118 // Write the tee output to a .wav file
4119 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004120#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004121
4122#ifdef AUDIO_WATCHDOG
4123 if (mAudioWatchdog != 0) {
4124 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4125 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4126 wdCopy.dump(fd);
4127 }
4128#endif
4129}
4130
4131uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4132{
4133 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4134}
4135
4136uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4137{
4138 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4139}
4140
4141void AudioFlinger::MixerThread::cacheParameters_l()
4142{
4143 PlaybackThread::cacheParameters_l();
4144
4145 // FIXME: Relaxed timing because of a certain device that can't meet latency
4146 // Should be reduced to 2x after the vendor fixes the driver issue
4147 // increase threshold again due to low power audio mode. The way this warning
4148 // threshold is calculated and its usefulness should be reconsidered anyway.
4149 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4150}
4151
4152// ----------------------------------------------------------------------------
4153
4154AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4155 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4156 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4157 // mLeftVolFloat, mRightVolFloat
4158{
4159}
4160
Eric Laurentbfb1b832013-01-07 09:53:42 -08004161AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4162 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4163 ThreadBase::type_t type)
4164 : PlaybackThread(audioFlinger, output, id, device, type)
4165 // mLeftVolFloat, mRightVolFloat
4166{
4167}
4168
Eric Laurent81784c32012-11-19 14:55:58 -08004169AudioFlinger::DirectOutputThread::~DirectOutputThread()
4170{
4171}
4172
Eric Laurentbfb1b832013-01-07 09:53:42 -08004173void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4174{
4175 audio_track_cblk_t* cblk = track->cblk();
4176 float left, right;
4177
4178 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4179 left = right = 0;
4180 } else {
4181 float typeVolume = mStreamTypes[track->streamType()].volume;
4182 float v = mMasterVolume * typeVolume;
4183 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004184 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4185 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4186 if (left > GAIN_FLOAT_UNITY) {
4187 left = GAIN_FLOAT_UNITY;
4188 }
4189 left *= v;
4190 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4191 if (right > GAIN_FLOAT_UNITY) {
4192 right = GAIN_FLOAT_UNITY;
4193 }
4194 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004195 }
4196
4197 if (lastTrack) {
4198 if (left != mLeftVolFloat || right != mRightVolFloat) {
4199 mLeftVolFloat = left;
4200 mRightVolFloat = right;
4201
4202 // Convert volumes from float to 8.24
4203 uint32_t vl = (uint32_t)(left * (1 << 24));
4204 uint32_t vr = (uint32_t)(right * (1 << 24));
4205
4206 // Delegate volume control to effect in track effect chain if needed
4207 // only one effect chain can be present on DirectOutputThread, so if
4208 // there is one, the track is connected to it
4209 if (!mEffectChains.isEmpty()) {
4210 mEffectChains[0]->setVolume_l(&vl, &vr);
4211 left = (float)vl / (1 << 24);
4212 right = (float)vr / (1 << 24);
4213 }
4214 if (mOutput->stream->set_volume) {
4215 mOutput->stream->set_volume(mOutput->stream, left, right);
4216 }
4217 }
4218 }
4219}
4220
4221
Eric Laurent81784c32012-11-19 14:55:58 -08004222AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4223 Vector< sp<Track> > *tracksToRemove
4224)
4225{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004226 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004227 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004228 bool doHwPause = false;
4229 bool doHwResume = false;
4230 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004231
4232 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004233 for (size_t i = 0; i < count; i++) {
4234 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004235 // The track died recently
4236 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004237 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004238 }
4239
4240 Track* const track = t.get();
4241 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004242 // Only consider last track started for volume and mixer state control.
4243 // In theory an older track could underrun and restart after the new one starts
4244 // but as we only care about the transition phase between two tracks on a
4245 // direct output, it is not a problem to ignore the underrun case.
4246 sp<Track> l = mLatestActiveTrack.promote();
4247 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004248
Eric Laurentd1f69b02014-12-15 14:33:13 -08004249 if (mHwSupportsPause && track->isPausing()) {
4250 track->setPaused();
4251 if (last && !mHwPaused) {
4252 doHwPause = true;
4253 mHwPaused = true;
4254 }
4255 tracksToRemove->add(track);
4256 } else if (track->isFlushPending()) {
4257 track->flushAck();
4258 if (last) {
4259 flushPending = true;
4260 }
4261 } else if (mHwSupportsPause && track->isResumePending()){
4262 track->resumeAck();
4263 if (last) {
4264 if (mHwPaused) {
4265 doHwResume = true;
4266 mHwPaused = false;
4267 }
4268 }
4269 }
4270
Eric Laurent81784c32012-11-19 14:55:58 -08004271 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004272 // for all its buffers to be filled before processing it.
4273 // Allow draining the buffer in case the client
4274 // app does not call stop() and relies on underrun to stop:
4275 // hence the test on (track->mRetryCount > 1).
4276 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004277 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004278 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4279 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004280 minFrames = mNormalFrameCount;
4281 } else {
4282 minFrames = 1;
4283 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004284
Eric Laurentab5cdba2014-06-09 17:22:27 -07004285 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4286 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004287 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004288 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004289
4290 if (track->mFillingUpStatus == Track::FS_FILLED) {
4291 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004292 // make sure processVolume_l() will apply new volume even if 0
4293 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004294 if (!mHwSupportsPause) {
4295 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004296 }
4297 }
4298
4299 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004300 processVolume_l(track, last);
4301 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004302 // reset retry count
4303 track->mRetryCount = kMaxTrackRetriesDirect;
4304 mActiveTrack = t;
4305 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004306 if (usesHwAvSync() && mHwPaused) {
4307 doHwResume = true;
4308 mHwPaused = false;
4309 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004310 }
Eric Laurent81784c32012-11-19 14:55:58 -08004311 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004312 // clear effect chain input buffer if the last active track started underruns
4313 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004314 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004315 mEffectChains[0]->clearInputBuffer();
4316 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004317 if (track->isStopping_1()) {
4318 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004319 if (last && mHwPaused) {
4320 doHwResume = true;
4321 mHwPaused = false;
4322 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004323 }
4324 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4325 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004326 // We have consumed all the buffers of this track.
4327 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004328 size_t audioHALFrames;
4329 if (audio_is_linear_pcm(mFormat)) {
4330 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4331 } else {
4332 audioHALFrames = 0;
4333 }
4334
Eric Laurent81784c32012-11-19 14:55:58 -08004335 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004336 if (mStandby || !last ||
4337 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004338 if (track->isStopping_2()) {
4339 track->mState = TrackBase::STOPPED;
4340 }
Eric Laurent81784c32012-11-19 14:55:58 -08004341 if (track->isStopped()) {
4342 track->reset();
4343 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004344 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004345 }
4346 } else {
4347 // No buffers for this track. Give it a few chances to
4348 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004349 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004350 if (--(track->mRetryCount) <= 0) {
4351 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004352 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004353 // indicate to client process that the track was disabled because of underrun;
4354 // it will then automatically call start() when data is available
4355 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004357 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004358 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4359 doHwPause = true;
4360 mHwPaused = true;
4361 }
Eric Laurent81784c32012-11-19 14:55:58 -08004362 }
4363 }
4364 }
4365 }
4366
Eric Laurentd1f69b02014-12-15 14:33:13 -08004367 // if an active track did not command a flush, check for pending flush on stopped tracks
4368 if (!flushPending) {
4369 for (size_t i = 0; i < mTracks.size(); i++) {
4370 if (mTracks[i]->isFlushPending()) {
4371 mTracks[i]->flushAck();
4372 flushPending = true;
4373 }
4374 }
4375 }
4376
4377 // make sure the pause/flush/resume sequence is executed in the right order.
4378 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4379 // before flush and then resume HW. This can happen in case of pause/flush/resume
4380 // if resume is received before pause is executed.
4381 if (mHwSupportsPause && !mStandby &&
4382 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4383 mOutput->stream->pause(mOutput->stream);
4384 }
4385 if (flushPending) {
4386 flushHw_l();
4387 }
4388 if (mHwSupportsPause && !mStandby && doHwResume) {
4389 mOutput->stream->resume(mOutput->stream);
4390 }
Eric Laurent81784c32012-11-19 14:55:58 -08004391 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004392 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004393
4394 return mixerStatus;
4395}
4396
4397void AudioFlinger::DirectOutputThread::threadLoop_mix()
4398{
Eric Laurent81784c32012-11-19 14:55:58 -08004399 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004400 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004401 // output audio to hardware
4402 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004403 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004404 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004405 status_t status = mActiveTrack->getNextBuffer(&buffer);
4406 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004407 memset(curBuf, 0, frameCount * mFrameSize);
4408 break;
4409 }
4410 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4411 frameCount -= buffer.frameCount;
4412 curBuf += buffer.frameCount * mFrameSize;
4413 mActiveTrack->releaseBuffer(&buffer);
4414 }
Andy Hung2098f272014-02-27 14:00:06 -08004415 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004416 sleepTime = 0;
4417 standbyTime = systemTime() + standbyDelay;
4418 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004419}
4420
4421void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4422{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004423 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004424 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004425 sleepTime = idleSleepTime;
4426 return;
4427 }
Eric Laurent81784c32012-11-19 14:55:58 -08004428 if (sleepTime == 0) {
4429 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4430 sleepTime = activeSleepTime;
4431 } else {
4432 sleepTime = idleSleepTime;
4433 }
4434 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004435 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004436 sleepTime = 0;
4437 }
4438}
4439
Eric Laurentd1f69b02014-12-15 14:33:13 -08004440void AudioFlinger::DirectOutputThread::threadLoop_exit()
4441{
4442 {
4443 Mutex::Autolock _l(mLock);
4444 bool flushPending = false;
4445 for (size_t i = 0; i < mTracks.size(); i++) {
4446 if (mTracks[i]->isFlushPending()) {
4447 mTracks[i]->flushAck();
4448 flushPending = true;
4449 }
4450 }
4451 if (flushPending) {
4452 flushHw_l();
4453 }
4454 }
4455 PlaybackThread::threadLoop_exit();
4456}
4457
4458// must be called with thread mutex locked
4459bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4460{
4461 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004462 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004463
4464 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4465 // after a timeout and we will enter standby then.
4466 if (mTracks.size() > 0) {
4467 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004468 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4469 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004470 }
4471
Eric Laurentb369caf2015-03-30 20:51:47 -07004472 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004473}
4474
Eric Laurent81784c32012-11-19 14:55:58 -08004475// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004476int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004477 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004478{
4479 return 0;
4480}
4481
4482// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004483void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004484{
4485}
4486
Eric Laurent10351942014-05-08 18:49:52 -07004487// checkForNewParameter_l() must be called with ThreadBase::mLock held
4488bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4489 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004490{
4491 bool reconfig = false;
4492
Eric Laurent10351942014-05-08 18:49:52 -07004493 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004494
Eric Laurent10351942014-05-08 18:49:52 -07004495 AudioParameter param = AudioParameter(keyValuePair);
4496 int value;
4497 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4498 // forward device change to effects that have requested to be
4499 // aware of attached audio device.
4500 if (value != AUDIO_DEVICE_NONE) {
4501 mOutDevice = value;
4502 for (size_t i = 0; i < mEffectChains.size(); i++) {
4503 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004504 }
4505 }
Eric Laurent81784c32012-11-19 14:55:58 -08004506 }
Eric Laurent10351942014-05-08 18:49:52 -07004507 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4508 // do not accept frame count changes if tracks are open as the track buffer
4509 // size depends on frame count and correct behavior would not be garantied
4510 // if frame count is changed after track creation
4511 if (!mTracks.isEmpty()) {
4512 status = INVALID_OPERATION;
4513 } else {
4514 reconfig = true;
4515 }
4516 }
4517 if (status == NO_ERROR) {
4518 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4519 keyValuePair.string());
4520 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004521 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004522 mStandby = true;
4523 mBytesWritten = 0;
4524 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4525 keyValuePair.string());
4526 }
4527 if (status == NO_ERROR && reconfig) {
4528 readOutputParameters_l();
4529 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4530 }
4531 }
4532
Eric Laurent81784c32012-11-19 14:55:58 -08004533 return reconfig;
4534}
4535
4536uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4537{
4538 uint32_t time;
4539 if (audio_is_linear_pcm(mFormat)) {
4540 time = PlaybackThread::activeSleepTimeUs();
4541 } else {
4542 time = 10000;
4543 }
4544 return time;
4545}
4546
4547uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4548{
4549 uint32_t time;
4550 if (audio_is_linear_pcm(mFormat)) {
4551 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4552 } else {
4553 time = 10000;
4554 }
4555 return time;
4556}
4557
4558uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4559{
4560 uint32_t time;
4561 if (audio_is_linear_pcm(mFormat)) {
4562 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4563 } else {
4564 time = 10000;
4565 }
4566 return time;
4567}
4568
4569void AudioFlinger::DirectOutputThread::cacheParameters_l()
4570{
4571 PlaybackThread::cacheParameters_l();
4572
4573 // use shorter standby delay as on normal output to release
4574 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004575 // no delay on outputs with HW A/V sync
4576 if (usesHwAvSync()) {
4577 standbyDelay = 0;
4578 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004579 standbyDelay = microseconds(activeSleepTime*2);
4580 } else {
4581 standbyDelay = kOffloadStandbyDelayNs;
4582 }
Eric Laurent81784c32012-11-19 14:55:58 -08004583}
4584
Eric Laurente659ef42014-09-29 13:06:46 -07004585void AudioFlinger::DirectOutputThread::flushHw_l()
4586{
Phil Burk062e67a2015-02-11 13:40:50 -08004587 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004588 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004589}
4590
Eric Laurent81784c32012-11-19 14:55:58 -08004591// ----------------------------------------------------------------------------
4592
Eric Laurentbfb1b832013-01-07 09:53:42 -08004593AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004594 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004595 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004596 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004597 mWriteAckSequence(0),
4598 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004599{
4600}
4601
4602AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4603{
4604}
4605
4606void AudioFlinger::AsyncCallbackThread::onFirstRef()
4607{
4608 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4609}
4610
4611bool AudioFlinger::AsyncCallbackThread::threadLoop()
4612{
4613 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004614 uint32_t writeAckSequence;
4615 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004616
4617 {
4618 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004619 while (!((mWriteAckSequence & 1) ||
4620 (mDrainSequence & 1) ||
4621 exitPending())) {
4622 mWaitWorkCV.wait(mLock);
4623 }
4624
Eric Laurentbfb1b832013-01-07 09:53:42 -08004625 if (exitPending()) {
4626 break;
4627 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004628 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4629 mWriteAckSequence, mDrainSequence);
4630 writeAckSequence = mWriteAckSequence;
4631 mWriteAckSequence &= ~1;
4632 drainSequence = mDrainSequence;
4633 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004634 }
4635 {
Eric Laurent4de95592013-09-26 15:28:21 -07004636 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4637 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004638 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004639 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004640 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004641 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004642 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004643 }
4644 }
4645 }
4646 }
4647 return false;
4648}
4649
4650void AudioFlinger::AsyncCallbackThread::exit()
4651{
4652 ALOGV("AsyncCallbackThread::exit");
4653 Mutex::Autolock _l(mLock);
4654 requestExit();
4655 mWaitWorkCV.broadcast();
4656}
4657
Eric Laurent3b4529e2013-09-05 18:09:19 -07004658void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659{
4660 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004661 // bit 0 is cleared
4662 mWriteAckSequence = sequence << 1;
4663}
4664
4665void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4666{
4667 Mutex::Autolock _l(mLock);
4668 // ignore unexpected callbacks
4669 if (mWriteAckSequence & 2) {
4670 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671 mWaitWorkCV.signal();
4672 }
4673}
4674
Eric Laurent3b4529e2013-09-05 18:09:19 -07004675void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004676{
4677 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004678 // bit 0 is cleared
4679 mDrainSequence = sequence << 1;
4680}
4681
4682void AudioFlinger::AsyncCallbackThread::resetDraining()
4683{
4684 Mutex::Autolock _l(mLock);
4685 // ignore unexpected callbacks
4686 if (mDrainSequence & 2) {
4687 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004688 mWaitWorkCV.signal();
4689 }
4690}
4691
4692
4693// ----------------------------------------------------------------------------
4694AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4695 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4696 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004697 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004698{
Eric Laurentfd477972013-10-25 18:10:40 -07004699 //FIXME: mStandby should be set to true by ThreadBase constructor
4700 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004701}
4702
Eric Laurentbfb1b832013-01-07 09:53:42 -08004703void AudioFlinger::OffloadThread::threadLoop_exit()
4704{
4705 if (mFlushPending || mHwPaused) {
4706 // If a flush is pending or track was paused, just discard buffered data
4707 flushHw_l();
4708 } else {
4709 mMixerStatus = MIXER_DRAIN_ALL;
4710 threadLoop_drain();
4711 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004712 if (mUseAsyncWrite) {
4713 ALOG_ASSERT(mCallbackThread != 0);
4714 mCallbackThread->exit();
4715 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004716 PlaybackThread::threadLoop_exit();
4717}
4718
4719AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4720 Vector< sp<Track> > *tracksToRemove
4721)
4722{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723 size_t count = mActiveTracks.size();
4724
4725 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004726 bool doHwPause = false;
4727 bool doHwResume = false;
4728
Eric Laurentede6c3b2013-09-19 14:37:46 -07004729 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4730
Eric Laurentbfb1b832013-01-07 09:53:42 -08004731 // find out which tracks need to be processed
4732 for (size_t i = 0; i < count; i++) {
4733 sp<Track> t = mActiveTracks[i].promote();
4734 // The track died recently
4735 if (t == 0) {
4736 continue;
4737 }
4738 Track* const track = t.get();
4739 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004740 // Only consider last track started for volume and mixer state control.
4741 // In theory an older track could underrun and restart after the new one starts
4742 // but as we only care about the transition phase between two tracks on a
4743 // direct output, it is not a problem to ignore the underrun case.
4744 sp<Track> l = mLatestActiveTrack.promote();
4745 bool last = l.get() == track;
4746
Haynes Mathew George7844f672014-01-15 12:32:55 -08004747 if (track->isInvalid()) {
4748 ALOGW("An invalidated track shouldn't be in active list");
4749 tracksToRemove->add(track);
4750 continue;
4751 }
4752
4753 if (track->mState == TrackBase::IDLE) {
4754 ALOGW("An idle track shouldn't be in active list");
4755 continue;
4756 }
4757
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758 if (track->isPausing()) {
4759 track->setPaused();
4760 if (last) {
4761 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004762 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004763 mHwPaused = true;
4764 }
4765 // If we were part way through writing the mixbuffer to
4766 // the HAL we must save this until we resume
4767 // BUG - this will be wrong if a different track is made active,
4768 // in that case we want to discard the pending data in the
4769 // mixbuffer and tell the client to present it again when the
4770 // track is resumed
4771 mPausedWriteLength = mCurrentWriteLength;
4772 mPausedBytesRemaining = mBytesRemaining;
4773 mBytesRemaining = 0; // stop writing
4774 }
4775 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004776 } else if (track->isFlushPending()) {
4777 track->flushAck();
4778 if (last) {
4779 mFlushPending = true;
4780 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004781 } else if (track->isResumePending()){
4782 track->resumeAck();
4783 if (last) {
4784 if (mPausedBytesRemaining) {
4785 // Need to continue write that was interrupted
4786 mCurrentWriteLength = mPausedWriteLength;
4787 mBytesRemaining = mPausedBytesRemaining;
4788 mPausedBytesRemaining = 0;
4789 }
4790 if (mHwPaused) {
4791 doHwResume = true;
4792 mHwPaused = false;
4793 // threadLoop_mix() will handle the case that we need to
4794 // resume an interrupted write
4795 }
4796 // enable write to audio HAL
4797 sleepTime = 0;
4798
4799 // Do not handle new data in this iteration even if track->framesReady()
4800 mixerStatus = MIXER_TRACKS_ENABLED;
4801 }
4802 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004803 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004804 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004805 if (track->mFillingUpStatus == Track::FS_FILLED) {
4806 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004807 // make sure processVolume_l() will apply new volume even if 0
4808 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004809 }
4810
4811 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004812 sp<Track> previousTrack = mPreviousTrack.promote();
4813 if (previousTrack != 0) {
4814 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004815 // Flush any data still being written from last track
4816 mBytesRemaining = 0;
4817 if (mPausedBytesRemaining) {
4818 // Last track was paused so we also need to flush saved
4819 // mixbuffer state and invalidate track so that it will
4820 // re-submit that unwritten data when it is next resumed
4821 mPausedBytesRemaining = 0;
4822 // Invalidate is a bit drastic - would be more efficient
4823 // to have a flag to tell client that some of the
4824 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004825 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004826 }
4827 // flush data already sent to the DSP if changing audio session as audio
4828 // comes from a different source. Also invalidate previous track to force a
4829 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004830 if (previousTrack->sessionId() != track->sessionId()) {
4831 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004832 }
4833 }
4834 }
4835 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004836 // reset retry count
4837 track->mRetryCount = kMaxTrackRetriesOffload;
4838 mActiveTrack = t;
4839 mixerStatus = MIXER_TRACKS_READY;
4840 }
4841 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004842 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004843 if (track->isStopping_1()) {
4844 // Hardware buffer can hold a large amount of audio so we must
4845 // wait for all current track's data to drain before we say
4846 // that the track is stopped.
4847 if (mBytesRemaining == 0) {
4848 // Only start draining when all data in mixbuffer
4849 // has been written
4850 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4851 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004852 // do not drain if no data was ever sent to HAL (mStandby == true)
4853 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004854 // do not modify drain sequence if we are already draining. This happens
4855 // when resuming from pause after drain.
4856 if ((mDrainSequence & 1) == 0) {
4857 sleepTime = 0;
4858 standbyTime = systemTime() + standbyDelay;
4859 mixerStatus = MIXER_DRAIN_TRACK;
4860 mDrainSequence += 2;
4861 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004862 if (mHwPaused) {
4863 // It is possible to move from PAUSED to STOPPING_1 without
4864 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004865 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004866 mHwPaused = false;
4867 }
4868 }
4869 }
4870 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004871 // Drain has completed or we are in standby, signal presentation complete
4872 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004873 track->mState = TrackBase::STOPPED;
4874 size_t audioHALFrames =
4875 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4876 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08004877 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004878 track->presentationComplete(framesWritten, audioHALFrames);
4879 track->reset();
4880 tracksToRemove->add(track);
4881 }
4882 } else {
4883 // No buffers for this track. Give it a few chances to
4884 // fill a buffer, then remove it from active list.
4885 if (--(track->mRetryCount) <= 0) {
4886 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4887 track->name());
4888 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004889 // indicate to client process that the track was disabled because of underrun;
4890 // it will then automatically call start() when data is available
4891 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004892 } else if (last){
4893 mixerStatus = MIXER_TRACKS_ENABLED;
4894 }
4895 }
4896 }
4897 // compute volume for this track
4898 processVolume_l(track, last);
4899 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004900
Eric Laurentea0fade2013-10-04 16:23:48 -07004901 // make sure the pause/flush/resume sequence is executed in the right order.
4902 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4903 // before flush and then resume HW. This can happen in case of pause/flush/resume
4904 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004905 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004906 mOutput->stream->pause(mOutput->stream);
4907 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004908 if (mFlushPending) {
4909 flushHw_l();
4910 mFlushPending = false;
4911 }
Eric Laurentfd477972013-10-25 18:10:40 -07004912 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004913 mOutput->stream->resume(mOutput->stream);
4914 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004915
Eric Laurentbfb1b832013-01-07 09:53:42 -08004916 // remove all the tracks that need to be...
4917 removeTracks_l(*tracksToRemove);
4918
4919 return mixerStatus;
4920}
4921
Eric Laurentbfb1b832013-01-07 09:53:42 -08004922// must be called with thread mutex locked
4923bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4924{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004925 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4926 mWriteAckSequence, mDrainSequence);
4927 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004928 return true;
4929 }
4930 return false;
4931}
4932
Eric Laurentbfb1b832013-01-07 09:53:42 -08004933bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4934{
4935 Mutex::Autolock _l(mLock);
4936 return waitingAsyncCallback_l();
4937}
4938
4939void AudioFlinger::OffloadThread::flushHw_l()
4940{
Eric Laurente659ef42014-09-29 13:06:46 -07004941 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004942 // Flush anything still waiting in the mixbuffer
4943 mCurrentWriteLength = 0;
4944 mBytesRemaining = 0;
4945 mPausedWriteLength = 0;
4946 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004947
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004949 // discard any pending drain or write ack by incrementing sequence
4950 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4951 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004952 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004953 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4954 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004955 }
4956}
4957
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004958void AudioFlinger::OffloadThread::onAddNewTrack_l()
4959{
4960 sp<Track> previousTrack = mPreviousTrack.promote();
4961 sp<Track> latestTrack = mLatestActiveTrack.promote();
4962
4963 if (previousTrack != 0 && latestTrack != 0 &&
4964 (previousTrack->sessionId() != latestTrack->sessionId())) {
4965 mFlushPending = true;
4966 }
4967 PlaybackThread::onAddNewTrack_l();
4968}
4969
Eric Laurentbfb1b832013-01-07 09:53:42 -08004970// ----------------------------------------------------------------------------
4971
Eric Laurent81784c32012-11-19 14:55:58 -08004972AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4973 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4974 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4975 DUPLICATING),
4976 mWaitTimeMs(UINT_MAX)
4977{
4978 addOutputTrack(mainThread);
4979}
4980
4981AudioFlinger::DuplicatingThread::~DuplicatingThread()
4982{
4983 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4984 mOutputTracks[i]->destroy();
4985 }
4986}
4987
4988void AudioFlinger::DuplicatingThread::threadLoop_mix()
4989{
4990 // mix buffers...
4991 if (outputsReady(outputTracks)) {
4992 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4993 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004994 if (mMixerBufferValid) {
4995 memset(mMixerBuffer, 0, mMixerBufferSize);
4996 } else {
4997 memset(mSinkBuffer, 0, mSinkBufferSize);
4998 }
Eric Laurent81784c32012-11-19 14:55:58 -08004999 }
5000 sleepTime = 0;
5001 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005002 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005003 standbyTime = systemTime() + standbyDelay;
5004}
5005
5006void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5007{
5008 if (sleepTime == 0) {
5009 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5010 sleepTime = activeSleepTime;
5011 } else {
5012 sleepTime = idleSleepTime;
5013 }
5014 } else if (mBytesWritten != 0) {
5015 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5016 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005017 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005018 } else {
5019 // flush remaining overflow buffers in output tracks
5020 writeFrames = 0;
5021 }
5022 sleepTime = 0;
5023 }
5024}
5025
Eric Laurentbfb1b832013-01-07 09:53:42 -08005026ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005027{
5028 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005029 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005030 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005031 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005032 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005033}
5034
5035void AudioFlinger::DuplicatingThread::threadLoop_standby()
5036{
5037 // DuplicatingThread implements standby by stopping all tracks
5038 for (size_t i = 0; i < outputTracks.size(); i++) {
5039 outputTracks[i]->stop();
5040 }
5041}
5042
5043void AudioFlinger::DuplicatingThread::saveOutputTracks()
5044{
5045 outputTracks = mOutputTracks;
5046}
5047
5048void AudioFlinger::DuplicatingThread::clearOutputTracks()
5049{
5050 outputTracks.clear();
5051}
5052
5053void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5054{
5055 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005056 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5057 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5058 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5059 const size_t frameCount =
5060 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5061 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5062 // from different OutputTracks and their associated MixerThreads (e.g. one may
5063 // nearly empty and the other may be dropping data).
5064
5065 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005066 this,
5067 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005068 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005069 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005070 frameCount,
5071 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005072 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005073 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005074 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005075 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005076 updateWaitTime_l();
5077 }
5078}
5079
5080void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5081{
5082 Mutex::Autolock _l(mLock);
5083 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5084 if (mOutputTracks[i]->thread() == thread) {
5085 mOutputTracks[i]->destroy();
5086 mOutputTracks.removeAt(i);
5087 updateWaitTime_l();
5088 return;
5089 }
5090 }
5091 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5092}
5093
5094// caller must hold mLock
5095void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5096{
5097 mWaitTimeMs = UINT_MAX;
5098 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5099 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5100 if (strong != 0) {
5101 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5102 if (waitTimeMs < mWaitTimeMs) {
5103 mWaitTimeMs = waitTimeMs;
5104 }
5105 }
5106 }
5107}
5108
5109
5110bool AudioFlinger::DuplicatingThread::outputsReady(
5111 const SortedVector< sp<OutputTrack> > &outputTracks)
5112{
5113 for (size_t i = 0; i < outputTracks.size(); i++) {
5114 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5115 if (thread == 0) {
5116 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5117 outputTracks[i].get());
5118 return false;
5119 }
5120 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5121 // see note at standby() declaration
5122 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5123 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5124 thread.get());
5125 return false;
5126 }
5127 }
5128 return true;
5129}
5130
5131uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5132{
5133 return (mWaitTimeMs * 1000) / 2;
5134}
5135
5136void AudioFlinger::DuplicatingThread::cacheParameters_l()
5137{
5138 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5139 updateWaitTime_l();
5140
5141 MixerThread::cacheParameters_l();
5142}
5143
5144// ----------------------------------------------------------------------------
5145// Record
5146// ----------------------------------------------------------------------------
5147
5148AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5149 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005150 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005151 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005152 audio_devices_t inDevice
5153#ifdef TEE_SINK
5154 , const sp<NBAIO_Sink>& teeSink
5155#endif
5156 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005157 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005158 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005159 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005160 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005161#ifdef TEE_SINK
5162 , mTeeSink(teeSink)
5163#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005164 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5165 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005166 // mFastCapture below
5167 , mFastCaptureFutex(0)
5168 // mInputSource
5169 // mPipeSink
5170 // mPipeSource
5171 , mPipeFramesP2(0)
5172 // mPipeMemory
5173 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005174 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005175{
Glenn Kastend7dca052015-03-05 16:05:54 -08005176 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5177 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005178
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005179 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005180
5181 // create an NBAIO source for the HAL input stream, and negotiate
5182 mInputSource = new AudioStreamInSource(input->stream);
5183 size_t numCounterOffers = 0;
5184 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5185 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5186 ALOG_ASSERT(index == 0);
5187
5188 // initialize fast capture depending on configuration
5189 bool initFastCapture;
5190 switch (kUseFastCapture) {
5191 case FastCapture_Never:
5192 initFastCapture = false;
5193 break;
5194 case FastCapture_Always:
5195 initFastCapture = true;
5196 break;
5197 case FastCapture_Static:
5198 uint32_t primaryOutputSampleRate;
5199 {
5200 AutoMutex _l(audioFlinger->mHardwareLock);
5201 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5202 }
5203 initFastCapture =
5204 // either capture sample rate is same as (a reasonable) primary output sample rate
5205 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5206 (mSampleRate == primaryOutputSampleRate)) ||
5207 // or primary output sample rate is unknown, and capture sample rate is reasonable
5208 ((primaryOutputSampleRate == 0) &&
5209 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005210 // and the buffer size is < 12 ms
5211 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005212 break;
5213 // case FastCapture_Dynamic:
5214 }
5215
5216 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005217 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005218 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005219 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005220 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5221 void *pipeBuffer;
5222 const sp<MemoryDealer> roHeap(readOnlyHeap());
5223 sp<IMemory> pipeMemory;
5224 if ((roHeap == 0) ||
5225 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5226 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5227 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5228 goto failed;
5229 }
5230 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5231 memset(pipeBuffer, 0, pipeSize);
5232 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5233 const NBAIO_Format offers[1] = {format};
5234 size_t numCounterOffers = 0;
5235 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5236 ALOG_ASSERT(index == 0);
5237 mPipeSink = pipe;
5238 PipeReader *pipeReader = new PipeReader(*pipe);
5239 numCounterOffers = 0;
5240 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5241 ALOG_ASSERT(index == 0);
5242 mPipeSource = pipeReader;
5243 mPipeFramesP2 = pipeFramesP2;
5244 mPipeMemory = pipeMemory;
5245
5246 // create fast capture
5247 mFastCapture = new FastCapture();
5248 FastCaptureStateQueue *sq = mFastCapture->sq();
5249#ifdef STATE_QUEUE_DUMP
5250 // FIXME
5251#endif
5252 FastCaptureState *state = sq->begin();
5253 state->mCblk = NULL;
5254 state->mInputSource = mInputSource.get();
5255 state->mInputSourceGen++;
5256 state->mPipeSink = pipe;
5257 state->mPipeSinkGen++;
5258 state->mFrameCount = mFrameCount;
5259 state->mCommand = FastCaptureState::COLD_IDLE;
5260 // already done in constructor initialization list
5261 //mFastCaptureFutex = 0;
5262 state->mColdFutexAddr = &mFastCaptureFutex;
5263 state->mColdGen++;
5264 state->mDumpState = &mFastCaptureDumpState;
5265#ifdef TEE_SINK
5266 // FIXME
5267#endif
5268 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5269 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5270 sq->end();
5271 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5272
5273 // start the fast capture
5274 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5275 pid_t tid = mFastCapture->getTid();
5276 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5277 if (err != 0) {
5278 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5279 kPriorityFastCapture, getpid_cached, tid, err);
5280 }
5281
5282#ifdef AUDIO_WATCHDOG
5283 // FIXME
5284#endif
5285
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005286 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005287 }
5288failed: ;
5289
5290 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005291}
5292
Eric Laurent81784c32012-11-19 14:55:58 -08005293AudioFlinger::RecordThread::~RecordThread()
5294{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005295 if (mFastCapture != 0) {
5296 FastCaptureStateQueue *sq = mFastCapture->sq();
5297 FastCaptureState *state = sq->begin();
5298 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5299 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5300 if (old == -1) {
5301 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5302 }
5303 }
5304 state->mCommand = FastCaptureState::EXIT;
5305 sq->end();
5306 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5307 mFastCapture->join();
5308 mFastCapture.clear();
5309 }
5310 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005311 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005312 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005313}
5314
5315void AudioFlinger::RecordThread::onFirstRef()
5316{
Glenn Kastend7dca052015-03-05 16:05:54 -08005317 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005318}
5319
Eric Laurent81784c32012-11-19 14:55:58 -08005320bool AudioFlinger::RecordThread::threadLoop()
5321{
Eric Laurent81784c32012-11-19 14:55:58 -08005322 nsecs_t lastWarning = 0;
5323
5324 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005325
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005326reacquire_wakelock:
5327 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005328 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005329 {
5330 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005331 size_t size = mActiveTracks.size();
5332 activeTracksGen = mActiveTracksGen;
5333 if (size > 0) {
5334 // FIXME an arbitrary choice
5335 activeTrack = mActiveTracks[0];
5336 acquireWakeLock_l(activeTrack->uid());
5337 if (size > 1) {
5338 SortedVector<int> tmp;
5339 for (size_t i = 0; i < size; i++) {
5340 tmp.add(mActiveTracks[i]->uid());
5341 }
5342 updateWakeLockUids_l(tmp);
5343 }
5344 } else {
5345 acquireWakeLock_l(-1);
5346 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005347 }
5348
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005349 // used to request a deferred sleep, to be executed later while mutex is unlocked
5350 uint32_t sleepUs = 0;
5351
5352 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005353 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005354 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005355
Glenn Kasten5edadd42013-08-14 16:30:49 -07005356 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005357 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005358 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005359 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005360 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005361 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005362 }
5363
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005364 // activeTracks accumulates a copy of a subset of mActiveTracks
5365 Vector< sp<RecordTrack> > activeTracks;
5366
Glenn Kasten735f45f2014-08-18 15:51:59 -07005367 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005368 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005369
Glenn Kasten735f45f2014-08-18 15:51:59 -07005370 // reference to a fast track which is about to be removed
5371 sp<RecordTrack> fastTrackToRemove;
5372
Eric Laurent81784c32012-11-19 14:55:58 -08005373 { // scope for mLock
5374 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005375
Eric Laurent021cf962014-05-13 10:18:14 -07005376 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005377
Eric Laurent000a4192014-01-29 15:17:32 -08005378 // check exitPending here because checkForNewParameters_l() and
5379 // checkForNewParameters_l() can temporarily release mLock
5380 if (exitPending()) {
5381 break;
5382 }
5383
Glenn Kasten2b806402013-11-20 16:37:38 -08005384 // if no active track(s), then standby and release wakelock
5385 size_t size = mActiveTracks.size();
5386 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005387 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005388 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005389 releaseWakeLock_l();
5390 ALOGV("RecordThread: loop stopping");
5391 // go to sleep
5392 mWaitWorkCV.wait(mLock);
5393 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005394 goto reacquire_wakelock;
5395 }
5396
Glenn Kasten2b806402013-11-20 16:37:38 -08005397 if (mActiveTracksGen != activeTracksGen) {
5398 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005399 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005400 for (size_t i = 0; i < size; i++) {
5401 tmp.add(mActiveTracks[i]->uid());
5402 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005403 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005404 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005405
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005406 bool doBroadcast = false;
5407 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005408
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005409 activeTrack = mActiveTracks[i];
5410 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005411 if (activeTrack->isFastTrack()) {
5412 ALOG_ASSERT(fastTrackToRemove == 0);
5413 fastTrackToRemove = activeTrack;
5414 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005415 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005416 mActiveTracks.remove(activeTrack);
5417 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005418 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005419 continue;
5420 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005421
5422 TrackBase::track_state activeTrackState = activeTrack->mState;
5423 switch (activeTrackState) {
5424
5425 case TrackBase::PAUSING:
5426 mActiveTracks.remove(activeTrack);
5427 mActiveTracksGen++;
5428 doBroadcast = true;
5429 size--;
5430 continue;
5431
5432 case TrackBase::STARTING_1:
5433 sleepUs = 10000;
5434 i++;
5435 continue;
5436
5437 case TrackBase::STARTING_2:
5438 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005439 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005440 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005441 break;
5442
5443 case TrackBase::ACTIVE:
5444 break;
5445
5446 case TrackBase::IDLE:
5447 i++;
5448 continue;
5449
5450 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005451 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005452 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005453
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005454 activeTracks.add(activeTrack);
5455 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005456
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005457 if (activeTrack->isFastTrack()) {
5458 ALOG_ASSERT(!mFastTrackAvail);
5459 ALOG_ASSERT(fastTrack == 0);
5460 fastTrack = activeTrack;
5461 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005462 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005463 if (doBroadcast) {
5464 mStartStopCond.broadcast();
5465 }
5466
5467 // sleep if there are no active tracks to process
5468 if (activeTracks.size() == 0) {
5469 if (sleepUs == 0) {
5470 sleepUs = kRecordThreadSleepUs;
5471 }
5472 continue;
5473 }
5474 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005475
Eric Laurent81784c32012-11-19 14:55:58 -08005476 lockEffectChains_l(effectChains);
5477 }
5478
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005479 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005480
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005481 size_t size = effectChains.size();
5482 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005483 // thread mutex is not locked, but effect chain is locked
5484 effectChains[i]->process_l();
5485 }
5486
Glenn Kasten735f45f2014-08-18 15:51:59 -07005487 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005488 if (mFastCapture != 0) {
5489 FastCaptureStateQueue *sq = mFastCapture->sq();
5490 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005491 bool didModify = false;
5492 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005493 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5494 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5495 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5496 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5497 if (old == -1) {
5498 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5499 }
5500 }
5501 state->mCommand = FastCaptureState::READ_WRITE;
5502#if 0 // FIXME
5503 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005504 FastThreadDumpState::kSamplingNforLowRamDevice :
5505 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005506#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005507 didModify = true;
5508 }
5509 audio_track_cblk_t *cblkOld = state->mCblk;
5510 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5511 if (cblkNew != cblkOld) {
5512 state->mCblk = cblkNew;
5513 // block until acked if removing a fast track
5514 if (cblkOld != NULL) {
5515 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5516 }
5517 didModify = true;
5518 }
5519 sq->end(didModify);
5520 if (didModify) {
5521 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005522#if 0
5523 if (kUseFastCapture == FastCapture_Dynamic) {
5524 mNormalSource = mPipeSource;
5525 }
5526#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005527 }
5528 }
5529
Glenn Kasten735f45f2014-08-18 15:51:59 -07005530 // now run the fast track destructor with thread mutex unlocked
5531 fastTrackToRemove.clear();
5532
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005533 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5534 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5535 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5536 // If destination is non-contiguous, first read past the nominal end of buffer, then
5537 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005538
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005539 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005540 ssize_t framesRead;
5541
5542 // If an NBAIO source is present, use it to read the normal capture's data
5543 if (mPipeSource != 0) {
5544 size_t framesToRead = mBufferSize / mFrameSize;
5545 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5546 framesToRead, AudioBufferProvider::kInvalidPTS);
5547 if (framesRead == 0) {
5548 // since pipe is non-blocking, simulate blocking input
5549 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5550 }
5551 // otherwise use the HAL / AudioStreamIn directly
5552 } else {
5553 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5554 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5555 if (bytesRead < 0) {
5556 framesRead = bytesRead;
5557 } else {
5558 framesRead = bytesRead / mFrameSize;
5559 }
5560 }
5561
5562 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5563 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005564 // Force input into standby so that it tries to recover at next read attempt
5565 inputStandBy();
5566 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005567 }
5568 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005569 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005571 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005572
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005573 if (mTeeSink != 0) {
5574 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5575 }
5576 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005577 {
5578 size_t part1 = mRsmpInFramesP2 - rear;
5579 if ((size_t) framesRead > part1) {
5580 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5581 (framesRead - part1) * mFrameSize);
5582 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005583 }
5584 rear = mRsmpInRear += framesRead;
5585
5586 size = activeTracks.size();
5587 // loop over each active track
5588 for (size_t i = 0; i < size; i++) {
5589 activeTrack = activeTracks[i];
5590
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005591 // skip fast tracks, as those are handled directly by FastCapture
5592 if (activeTrack->isFastTrack()) {
5593 continue;
5594 }
5595
Andy Hung73c02e42015-03-29 01:13:58 -07005596 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005597 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5598
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005599 enum {
5600 OVERRUN_UNKNOWN,
5601 OVERRUN_TRUE,
5602 OVERRUN_FALSE
5603 } overrun = OVERRUN_UNKNOWN;
5604
5605 // loop over getNextBuffer to handle circular sink
5606 for (;;) {
5607
5608 activeTrack->mSink.frameCount = ~0;
5609 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5610 size_t framesOut = activeTrack->mSink.frameCount;
5611 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5612
Andy Hung73c02e42015-03-29 01:13:58 -07005613 // check available frames and handle overrun conditions
5614 // if the record track isn't draining fast enough.
5615 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005616 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005617 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5618 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005619 overrun = OVERRUN_TRUE;
5620 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005621 if (framesOut == 0 || framesIn == 0) {
5622 break;
5623 }
5624
Andy Hung97a893e2015-03-29 01:03:07 -07005625 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5626 framesOut = activeTrack->mRecordBufferConverter->convert(
5627 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005628
5629 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5630 overrun = OVERRUN_FALSE;
5631 }
5632
5633 if (activeTrack->mFramesToDrop == 0) {
5634 if (framesOut > 0) {
5635 activeTrack->mSink.frameCount = framesOut;
5636 activeTrack->releaseBuffer(&activeTrack->mSink);
5637 }
5638 } else {
5639 // FIXME could do a partial drop of framesOut
5640 if (activeTrack->mFramesToDrop > 0) {
5641 activeTrack->mFramesToDrop -= framesOut;
5642 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005643 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005644 }
5645 } else {
5646 activeTrack->mFramesToDrop += framesOut;
5647 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5648 activeTrack->mSyncStartEvent->isCancelled()) {
5649 ALOGW("Synced record %s, session %d, trigger session %d",
5650 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5651 activeTrack->sessionId(),
5652 (activeTrack->mSyncStartEvent != 0) ?
5653 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005654 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005655 }
5656 }
5657 }
5658
5659 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005660 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005661 }
5662 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005663
5664 switch (overrun) {
5665 case OVERRUN_TRUE:
5666 // client isn't retrieving buffers fast enough
5667 if (!activeTrack->setOverflow()) {
5668 nsecs_t now = systemTime();
5669 // FIXME should lastWarning per track?
5670 if ((now - lastWarning) > kWarningThrottleNs) {
5671 ALOGW("RecordThread: buffer overflow");
5672 lastWarning = now;
5673 }
5674 }
5675 break;
5676 case OVERRUN_FALSE:
5677 activeTrack->clearOverflow();
5678 break;
5679 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005680 break;
5681 }
5682
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005683 }
5684
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005685unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005686 // enable changes in effect chain
5687 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005688 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005689 }
5690
Glenn Kasten93e471f2013-08-19 08:40:07 -07005691 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005692
5693 {
5694 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005695 for (size_t i = 0; i < mTracks.size(); i++) {
5696 sp<RecordTrack> track = mTracks[i];
5697 track->invalidate();
5698 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005699 mActiveTracks.clear();
5700 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005701 mStartStopCond.broadcast();
5702 }
5703
5704 releaseWakeLock();
5705
5706 ALOGV("RecordThread %p exiting", this);
5707 return false;
5708}
5709
Glenn Kasten93e471f2013-08-19 08:40:07 -07005710void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005711{
5712 if (!mStandby) {
5713 inputStandBy();
5714 mStandby = true;
5715 }
5716}
5717
5718void AudioFlinger::RecordThread::inputStandBy()
5719{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005720 // Idle the fast capture if it's currently running
5721 if (mFastCapture != 0) {
5722 FastCaptureStateQueue *sq = mFastCapture->sq();
5723 FastCaptureState *state = sq->begin();
5724 if (!(state->mCommand & FastCaptureState::IDLE)) {
5725 state->mCommand = FastCaptureState::COLD_IDLE;
5726 state->mColdFutexAddr = &mFastCaptureFutex;
5727 state->mColdGen++;
5728 mFastCaptureFutex = 0;
5729 sq->end();
5730 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5731 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5732#if 0
5733 if (kUseFastCapture == FastCapture_Dynamic) {
5734 // FIXME
5735 }
5736#endif
5737#ifdef AUDIO_WATCHDOG
5738 // FIXME
5739#endif
5740 } else {
5741 sq->end(false /*didModify*/);
5742 }
5743 }
Eric Laurent81784c32012-11-19 14:55:58 -08005744 mInput->stream->common.standby(&mInput->stream->common);
5745}
5746
Glenn Kasten05997e22014-03-13 15:08:33 -07005747// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005748sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005749 const sp<AudioFlinger::Client>& client,
5750 uint32_t sampleRate,
5751 audio_format_t format,
5752 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005753 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005754 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005755 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005756 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005757 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005758 pid_t tid,
5759 status_t *status)
5760{
Glenn Kasten74935e42013-12-19 08:56:45 -08005761 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005762 sp<RecordTrack> track;
5763 status_t lStatus;
5764
Glenn Kasten90e58b12013-07-31 16:16:02 -07005765 // client expresses a preference for FAST, but we get the final say
5766 if (*flags & IAudioFlinger::TRACK_FAST) {
5767 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005768 // we formerly checked for a callback handler (non-0 tid),
5769 // but that is no longer required for TRANSFER_OBTAIN mode
5770 //
Glenn Kasten74105912014-07-03 12:28:53 -07005771 // frame count is not specified, or is exactly the pipe depth
5772 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005773 // PCM data
5774 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005775 // native format
5776 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005777 // native channel mask
5778 (channelMask == mChannelMask) &&
5779 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005780 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005781 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005782 hasFastCapture() &&
5783 // there are sufficient fast track slots available
5784 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005785 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005786 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005787 frameCount, mFrameCount);
5788 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005789 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5790 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005791 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005792 frameCount, mFrameCount, mPipeFramesP2,
5793 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5794 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005795 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005796 }
5797 }
5798
5799 // compute track buffer size in frames, and suggest the notification frame count
5800 if (*flags & IAudioFlinger::TRACK_FAST) {
5801 // fast track: frame count is exactly the pipe depth
5802 frameCount = mPipeFramesP2;
5803 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5804 *notificationFrames = mFrameCount;
5805 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005806 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5807 // or 20 ms if there is a fast capture
5808 // TODO This could be a roundupRatio inline, and const
5809 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5810 * sampleRate + mSampleRate - 1) / mSampleRate;
5811 // minimum number of notification periods is at least kMinNotifications,
5812 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5813 static const size_t kMinNotifications = 3;
5814 static const uint32_t kMinMs = 30;
5815 // TODO This could be a roundupRatio inline
5816 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5817 // TODO This could be a roundupRatio inline
5818 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5819 maxNotificationFrames;
5820 const size_t minFrameCount = maxNotificationFrames *
5821 max(kMinNotifications, minNotificationsByMs);
5822 frameCount = max(frameCount, minFrameCount);
5823 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5824 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005825 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005826 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005827 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005828
Glenn Kasten15e57982013-09-24 11:52:37 -07005829 lStatus = initCheck();
5830 if (lStatus != NO_ERROR) {
5831 ALOGE("createRecordTrack_l() audio driver not initialized");
5832 goto Exit;
5833 }
Eric Laurent81784c32012-11-19 14:55:58 -08005834
5835 { // scope for mLock
5836 Mutex::Autolock _l(mLock);
5837
5838 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005839 format, channelMask, frameCount, NULL, sessionId, uid,
5840 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005841
Glenn Kasten03003332013-08-06 15:40:54 -07005842 lStatus = track->initCheck();
5843 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005844 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005845 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005846 goto Exit;
5847 }
5848 mTracks.add(track);
5849
5850 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5851 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5852 mAudioFlinger->btNrecIsOff();
5853 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5854 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005855
5856 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5857 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5858 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5859 // so ask activity manager to do this on our behalf
5860 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5861 }
Eric Laurent81784c32012-11-19 14:55:58 -08005862 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005863
Eric Laurent81784c32012-11-19 14:55:58 -08005864 lStatus = NO_ERROR;
5865
5866Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005867 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005868 return track;
5869}
5870
5871status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5872 AudioSystem::sync_event_t event,
5873 int triggerSession)
5874{
5875 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5876 sp<ThreadBase> strongMe = this;
5877 status_t status = NO_ERROR;
5878
5879 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005880 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005881 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005882 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005883 triggerSession,
5884 recordTrack->sessionId(),
5885 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005886 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005887 // Sync event can be cancelled by the trigger session if the track is not in a
5888 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005889 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005890 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005891 } else {
5892 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005893 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005894 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005895 }
5896 }
5897
5898 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005899 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005900 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005901 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5902 if (recordTrack->mState == TrackBase::PAUSING) {
5903 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005904 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005905 } else {
5906 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005907 }
5908 return status;
5909 }
5910
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005911 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5912 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5913 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005914 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005915 mActiveTracks.add(recordTrack);
5916 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005917 status_t status = NO_ERROR;
5918 if (recordTrack->isExternalTrack()) {
5919 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005920 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005921 mLock.lock();
5922 // FIXME should verify that recordTrack is still in mActiveTracks
5923 if (status != NO_ERROR) {
5924 mActiveTracks.remove(recordTrack);
5925 mActiveTracksGen++;
5926 recordTrack->clearSyncStartEvent();
5927 ALOGV("RecordThread::start error %d", status);
5928 return status;
5929 }
Eric Laurent81784c32012-11-19 14:55:58 -08005930 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005931 // Catch up with current buffer indices if thread is already running.
5932 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5933 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5934 // see previously buffered data before it called start(), but with greater risk of overrun.
5935
Andy Hung73c02e42015-03-29 01:13:58 -07005936 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07005937 // clear any converter state as new data will be discontinuous
5938 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005939 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005940 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005941 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005942 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005943 ALOGV("Record failed to start");
5944 status = BAD_VALUE;
5945 goto startError;
5946 }
Eric Laurent81784c32012-11-19 14:55:58 -08005947 return status;
5948 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005949
Eric Laurent81784c32012-11-19 14:55:58 -08005950startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005951 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005952 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005953 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005954 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005955 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005956 return status;
5957}
5958
Eric Laurent81784c32012-11-19 14:55:58 -08005959void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5960{
5961 sp<SyncEvent> strongEvent = event.promote();
5962
5963 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005964 sp<RefBase> ptr = strongEvent->cookie().promote();
5965 if (ptr != 0) {
5966 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5967 recordTrack->handleSyncStartEvent(strongEvent);
5968 }
Eric Laurent81784c32012-11-19 14:55:58 -08005969 }
5970}
5971
Glenn Kastena8356f62013-07-25 14:37:52 -07005972bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08005973 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07005974 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005975 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08005976 return false;
5977 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005978 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08005979 recordTrack->mState = TrackBase::PAUSING;
5980 // do not wait for mStartStopCond if exiting
5981 if (exitPending()) {
5982 return true;
5983 }
Glenn Kasten47c20702013-08-13 15:37:35 -07005984 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08005985 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005986 // if we have been restarted, recordTrack is in mActiveTracks here
5987 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005988 ALOGV("Record stopped OK");
5989 return true;
5990 }
5991 return false;
5992}
5993
Glenn Kasten0f11b512014-01-31 16:18:54 -08005994bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08005995{
5996 return false;
5997}
5998
Glenn Kasten0f11b512014-01-31 16:18:54 -08005999status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006000{
6001#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6002 if (!isValidSyncEvent(event)) {
6003 return BAD_VALUE;
6004 }
6005
6006 int eventSession = event->triggerSession();
6007 status_t ret = NAME_NOT_FOUND;
6008
6009 Mutex::Autolock _l(mLock);
6010
6011 for (size_t i = 0; i < mTracks.size(); i++) {
6012 sp<RecordTrack> track = mTracks[i];
6013 if (eventSession == track->sessionId()) {
6014 (void) track->setSyncEvent(event);
6015 ret = NO_ERROR;
6016 }
6017 }
6018 return ret;
6019#else
6020 return BAD_VALUE;
6021#endif
6022}
6023
6024// destroyTrack_l() must be called with ThreadBase::mLock held
6025void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6026{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006027 track->terminate();
6028 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006029 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006030 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006031 removeTrack_l(track);
6032 }
6033}
6034
6035void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6036{
6037 mTracks.remove(track);
6038 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006039 if (track->isFastTrack()) {
6040 ALOG_ASSERT(!mFastTrackAvail);
6041 mFastTrackAvail = true;
6042 }
Eric Laurent81784c32012-11-19 14:55:58 -08006043}
6044
6045void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6046{
6047 dumpInternals(fd, args);
6048 dumpTracks(fd, args);
6049 dumpEffectChains(fd, args);
6050}
6051
6052void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6053{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006054 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006055
Glenn Kasten44182c22015-03-05 17:12:23 -08006056 dumpBase(fd, args);
6057
6058 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006059 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006060 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006061 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006062 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006063
6064 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6065 const FastCaptureDumpState copy(mFastCaptureDumpState);
6066 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006067}
6068
Glenn Kasten0f11b512014-01-31 16:18:54 -08006069void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006070{
6071 const size_t SIZE = 256;
6072 char buffer[SIZE];
6073 String8 result;
6074
Marco Nelissenb2208842014-02-07 14:00:50 -08006075 size_t numtracks = mTracks.size();
6076 size_t numactive = mActiveTracks.size();
6077 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006078 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006079 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006080 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006081 RecordTrack::appendDumpHeader(result);
6082 for (size_t i = 0; i < numtracks ; ++i) {
6083 sp<RecordTrack> track = mTracks[i];
6084 if (track != 0) {
6085 bool active = mActiveTracks.indexOf(track) >= 0;
6086 if (active) {
6087 numactiveseen++;
6088 }
6089 track->dump(buffer, SIZE, active);
6090 result.append(buffer);
6091 }
Eric Laurent81784c32012-11-19 14:55:58 -08006092 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006093 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006094 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006095 }
6096
Marco Nelissenb2208842014-02-07 14:00:50 -08006097 if (numactiveseen != numactive) {
6098 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6099 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006100 result.append(buffer);
6101 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006102 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006103 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006104 if (mTracks.indexOf(track) < 0) {
6105 track->dump(buffer, SIZE, true);
6106 result.append(buffer);
6107 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006108 }
Eric Laurent81784c32012-11-19 14:55:58 -08006109
6110 }
6111 write(fd, result.string(), result.size());
6112}
6113
Andy Hung73c02e42015-03-29 01:13:58 -07006114
6115void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6116{
6117 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6118 RecordThread *recordThread = (RecordThread *) threadBase.get();
6119 mRsmpInFront = recordThread->mRsmpInRear;
6120 mRsmpInUnrel = 0;
6121}
6122
6123void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6124 size_t *framesAvailable, bool *hasOverrun)
6125{
6126 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6127 RecordThread *recordThread = (RecordThread *) threadBase.get();
6128 const int32_t rear = recordThread->mRsmpInRear;
6129 const int32_t front = mRsmpInFront;
6130 const ssize_t filled = rear - front;
6131
6132 size_t framesIn;
6133 bool overrun = false;
6134 if (filled < 0) {
6135 // should not happen, but treat like a massive overrun and re-sync
6136 framesIn = 0;
6137 mRsmpInFront = rear;
6138 overrun = true;
6139 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6140 framesIn = (size_t) filled;
6141 } else {
6142 // client is not keeping up with server, but give it latest data
6143 framesIn = recordThread->mRsmpInFrames;
6144 mRsmpInFront = /* front = */ rear - framesIn;
6145 overrun = true;
6146 }
6147 if (framesAvailable != NULL) {
6148 *framesAvailable = framesIn;
6149 }
6150 if (hasOverrun != NULL) {
6151 *hasOverrun = overrun;
6152 }
6153}
6154
Eric Laurent81784c32012-11-19 14:55:58 -08006155// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6157 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006158{
Andy Hung73c02e42015-03-29 01:13:58 -07006159 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006160 if (threadBase == 0) {
6161 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006162 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006163 return NOT_ENOUGH_DATA;
6164 }
6165 RecordThread *recordThread = (RecordThread *) threadBase.get();
6166 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006167 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006168 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006169 // FIXME should not be P2 (don't want to increase latency)
6170 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006171 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006172 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006173 front &= recordThread->mRsmpInFramesP2 - 1;
6174 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006175 if (part1 > (size_t) filled) {
6176 part1 = filled;
6177 }
6178 size_t ask = buffer->frameCount;
6179 ALOG_ASSERT(ask > 0);
6180 if (part1 > ask) {
6181 part1 = ask;
6182 }
6183 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006184 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006185 buffer->raw = NULL;
6186 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006187 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006188 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006189 }
6190
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006192 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006193 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006194 return NO_ERROR;
6195}
6196
6197// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006198void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6199 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006200{
Glenn Kasten85948432013-08-19 12:09:05 -07006201 size_t stepCount = buffer->frameCount;
6202 if (stepCount == 0) {
6203 return;
6204 }
Andy Hung73c02e42015-03-29 01:13:58 -07006205 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6206 mRsmpInUnrel -= stepCount;
6207 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006208 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006209 buffer->frameCount = 0;
6210}
6211
Andy Hung97a893e2015-03-29 01:03:07 -07006212AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6213 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6214 uint32_t srcSampleRate,
6215 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6216 uint32_t dstSampleRate) :
6217 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6218 // mSrcFormat
6219 // mSrcSampleRate
6220 // mDstChannelMask
6221 // mDstFormat
6222 // mDstSampleRate
6223 // mSrcChannelCount
6224 // mDstChannelCount
6225 // mDstFrameSize
6226 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
6227 mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpOutFrameCount(0)
6228{
6229 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6230 dstChannelMask, dstFormat, dstSampleRate);
6231}
6232
6233AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6234 free(mBuf);
6235 delete mResampler;
6236 free(mRsmpOutBuffer);
6237}
6238
6239size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6240 AudioBufferProvider *provider, size_t frames)
6241{
6242 if (mSrcSampleRate == mDstSampleRate) {
6243 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6244 mSrcSampleRate, mSrcFormat, mDstFormat);
6245
6246 AudioBufferProvider::Buffer buffer;
6247 for (size_t i = frames; i > 0; ) {
6248 buffer.frameCount = i;
6249 status_t status = provider->getNextBuffer(&buffer, 0);
6250 if (status != OK || buffer.frameCount == 0) {
6251 frames -= i; // cannot fill request.
6252 break;
6253 }
6254 // convert to destination buffer
6255 convert(dst, buffer.raw, buffer.frameCount);
6256
6257 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6258 i -= buffer.frameCount;
6259 provider->releaseBuffer(&buffer);
6260 }
6261 } else {
6262 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6263 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6264
6265 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
6266 if (mRsmpOutFrameCount < frames) {
6267 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
6268 free(mRsmpOutBuffer);
6269 // resampler always outputs stereo (FOR NOW)
6270 (void)posix_memalign(&mRsmpOutBuffer, 32, frames * FCC_2 * sizeof(int32_t) /*Q4.27*/);
6271 mRsmpOutFrameCount = frames;
6272 }
6273 // resampler accumulates, but we only have one source track
6274 memset(mRsmpOutBuffer, 0, frames * FCC_2 * sizeof(int32_t));
6275 frames = mResampler->resample((int32_t*)mRsmpOutBuffer, frames, provider);
6276
6277 // convert to destination buffer
6278 convert(dst, mRsmpOutBuffer, frames);
6279 }
6280 return frames;
6281}
6282
6283status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6284 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6285 uint32_t srcSampleRate,
6286 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6287 uint32_t dstSampleRate)
6288{
6289 // quick evaluation if there is any change.
6290 if (mSrcFormat == srcFormat
6291 && mSrcChannelMask == srcChannelMask
6292 && mSrcSampleRate == srcSampleRate
6293 && mDstFormat == dstFormat
6294 && mDstChannelMask == dstChannelMask
6295 && mDstSampleRate == dstSampleRate) {
6296 return NO_ERROR;
6297 }
6298
6299 const bool valid =
6300 audio_is_input_channel(srcChannelMask)
6301 && audio_is_input_channel(dstChannelMask)
6302 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6303 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6304 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6305 ; // no upsampling checks for now
6306 if (!valid) {
6307 return BAD_VALUE;
6308 }
6309
6310 mSrcFormat = srcFormat;
6311 mSrcChannelMask = srcChannelMask;
6312 mSrcSampleRate = srcSampleRate;
6313 mDstFormat = dstFormat;
6314 mDstChannelMask = dstChannelMask;
6315 mDstSampleRate = dstSampleRate;
6316
6317 // compute derived parameters
6318 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6319 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6320 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6321
6322 // do we need a format buffer?
6323 if (mSrcFormat != mDstFormat && mDstChannelCount != mSrcChannelCount) {
6324 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6325 } else {
6326 mBufFrameSize = 0;
6327 }
6328 mBufFrames = 0; // force the buffer to be resized.
6329
6330 // do we need to resample?
6331 if (mSrcSampleRate != mDstSampleRate) {
6332 if (mResampler != NULL) {
6333 delete mResampler;
6334 }
6335 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_16_BIT,
6336 mSrcChannelCount, mDstSampleRate); // may seem confusing...
6337 mResampler->setSampleRate(mSrcSampleRate);
6338 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6339 }
6340 return NO_ERROR;
6341}
6342
6343void AudioFlinger::RecordThread::RecordBufferConverter::convert(
6344 void *dst, /*const*/ void *src, size_t frames)
6345{
6346 // check if a memcpy will do
6347 if (mResampler == NULL
6348 && mSrcChannelCount == mDstChannelCount
6349 && mSrcFormat == mDstFormat) {
6350 memcpy(dst, src,
6351 frames * mDstChannelCount * audio_bytes_per_sample(mDstFormat));
6352 return;
6353 }
6354 // reallocate buffer if needed
6355 if (mBufFrameSize != 0 && mBufFrames < frames) {
6356 free(mBuf);
6357 mBufFrames = frames;
6358 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6359 }
6360 // do processing
6361 if (mResampler != NULL) {
6362 // src channel count is always >= 2.
6363 void *dstBuf = mBuf != NULL ? mBuf : dst;
6364 // ditherAndClamp() works as long as all buffers returned by
6365 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
6366 if (mDstChannelCount == 1) {
6367 // the resampler always outputs stereo samples.
6368 // FIXME: this rewrites back into src
6369 ditherAndClamp((int32_t *)src, (const int32_t *)src, frames);
6370 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6371 (const int16_t *)src, frames);
6372 } else {
6373 ditherAndClamp((int32_t *)dstBuf, (const int32_t *)src, frames);
6374 }
6375 } else if (mSrcChannelCount != mDstChannelCount) {
6376 void *dstBuf = mBuf != NULL ? mBuf : dst;
6377 if (mSrcChannelCount == 1) {
6378 upmix_to_stereo_i16_from_mono_i16((int16_t *)dstBuf, (const int16_t *)src,
6379 frames);
6380 } else {
6381 downmix_to_mono_i16_from_stereo_i16((int16_t *)dstBuf,
6382 (const int16_t *)src, frames);
6383 }
6384 }
6385 if (mSrcFormat != mDstFormat) {
6386 void *srcBuf = mBuf != NULL ? mBuf : src;
6387 memcpy_by_audio_format(dst, mDstFormat, srcBuf, mSrcFormat,
6388 frames * mDstChannelCount);
6389 }
6390}
6391
Eric Laurent10351942014-05-08 18:49:52 -07006392bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6393 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006394{
6395 bool reconfig = false;
6396
Eric Laurent10351942014-05-08 18:49:52 -07006397 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006398
Eric Laurent10351942014-05-08 18:49:52 -07006399 audio_format_t reqFormat = mFormat;
6400 uint32_t samplingRate = mSampleRate;
6401 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6402
6403 AudioParameter param = AudioParameter(keyValuePair);
6404 int value;
6405 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6406 // channel count change can be requested. Do we mandate the first client defines the
6407 // HAL sampling rate and channel count or do we allow changes on the fly?
6408 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6409 samplingRate = value;
6410 reconfig = true;
6411 }
6412 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006413 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006414 status = BAD_VALUE;
6415 } else {
6416 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006417 reconfig = true;
6418 }
Eric Laurent10351942014-05-08 18:49:52 -07006419 }
6420 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6421 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6422 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6423 status = BAD_VALUE;
6424 } else {
6425 channelMask = mask;
6426 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006427 }
Eric Laurent10351942014-05-08 18:49:52 -07006428 }
6429 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6430 // do not accept frame count changes if tracks are open as the track buffer
6431 // size depends on frame count and correct behavior would not be guaranteed
6432 // if frame count is changed after track creation
6433 if (mActiveTracks.size() > 0) {
6434 status = INVALID_OPERATION;
6435 } else {
6436 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006437 }
Eric Laurent10351942014-05-08 18:49:52 -07006438 }
6439 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6440 // forward device change to effects that have requested to be
6441 // aware of attached audio device.
6442 for (size_t i = 0; i < mEffectChains.size(); i++) {
6443 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006444 }
Eric Laurent81784c32012-11-19 14:55:58 -08006445
Eric Laurent10351942014-05-08 18:49:52 -07006446 // store input device and output device but do not forward output device to audio HAL.
6447 // Note that status is ignored by the caller for output device
6448 // (see AudioFlinger::setParameters()
6449 if (audio_is_output_devices(value)) {
6450 mOutDevice = value;
6451 status = BAD_VALUE;
6452 } else {
6453 mInDevice = value;
6454 // disable AEC and NS if the device is a BT SCO headset supporting those
6455 // pre processings
6456 if (mTracks.size() > 0) {
6457 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6458 mAudioFlinger->btNrecIsOff();
6459 for (size_t i = 0; i < mTracks.size(); i++) {
6460 sp<RecordTrack> track = mTracks[i];
6461 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6462 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006463 }
6464 }
6465 }
Eric Laurent10351942014-05-08 18:49:52 -07006466 }
6467 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6468 mAudioSource != (audio_source_t)value) {
6469 // forward device change to effects that have requested to be
6470 // aware of attached audio device.
6471 for (size_t i = 0; i < mEffectChains.size(); i++) {
6472 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006473 }
Eric Laurent10351942014-05-08 18:49:52 -07006474 mAudioSource = (audio_source_t)value;
6475 }
Glenn Kastene198c362013-08-13 09:13:36 -07006476
Eric Laurent10351942014-05-08 18:49:52 -07006477 if (status == NO_ERROR) {
6478 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6479 keyValuePair.string());
6480 if (status == INVALID_OPERATION) {
6481 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006482 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6483 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006484 }
6485 if (reconfig) {
6486 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006487 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6488 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006489 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006490 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006491 audio_channel_count_from_in_mask(
6492 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006493 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6494 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6495 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006496 }
Eric Laurent10351942014-05-08 18:49:52 -07006497 if (status == NO_ERROR) {
6498 readInputParameters_l();
6499 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006500 }
6501 }
Eric Laurent81784c32012-11-19 14:55:58 -08006502 }
Eric Laurent10351942014-05-08 18:49:52 -07006503
Eric Laurent81784c32012-11-19 14:55:58 -08006504 return reconfig;
6505}
6506
6507String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6508{
Eric Laurent81784c32012-11-19 14:55:58 -08006509 Mutex::Autolock _l(mLock);
6510 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006511 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006512 }
6513
Glenn Kastend8ea6992013-07-16 14:17:15 -07006514 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6515 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006516 free(s);
6517 return out_s8;
6518}
6519
Eric Laurent021cf962014-05-13 10:18:14 -07006520void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006521 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006522 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006523
6524 switch (event) {
6525 case AudioSystem::INPUT_OPENED:
6526 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006527 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006528 desc.samplingRate = mSampleRate;
6529 desc.format = mFormat;
6530 desc.frameCount = mFrameCount;
6531 desc.latency = 0;
6532 param2 = &desc;
6533 break;
6534
6535 case AudioSystem::INPUT_CLOSED:
6536 default:
6537 break;
6538 }
Eric Laurent021cf962014-05-13 10:18:14 -07006539 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006540}
6541
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006542void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006543{
Eric Laurent81784c32012-11-19 14:55:58 -08006544 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6545 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006546 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006547 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6548 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006549 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006550 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006551 }
Eric Laurent665470b2014-07-03 16:37:08 -07006552 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006553 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6554 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006555 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006556 // 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 -07006557 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006558 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006559 // A larger value should allow more old data to be read after a track calls start(),
6560 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006561 //
6562 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006563 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006564 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006565 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006566
6567 // TODO optimize audio capture buffer sizes ...
6568 // Here we calculate the size of the sliding buffer used as a source
6569 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6570 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6571 // be better to have it derived from the pipe depth in the long term.
6572 // The current value is higher than necessary. However it should not add to latency.
6573
Glenn Kasten85948432013-08-19 12:09:05 -07006574 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6575 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006576
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006577 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6578 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006579}
6580
Glenn Kasten5f972c02014-01-13 09:59:31 -08006581uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006582{
6583 Mutex::Autolock _l(mLock);
6584 if (initCheck() != NO_ERROR) {
6585 return 0;
6586 }
6587
6588 return mInput->stream->get_input_frames_lost(mInput->stream);
6589}
6590
6591uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6592{
6593 Mutex::Autolock _l(mLock);
6594 uint32_t result = 0;
6595 if (getEffectChain_l(sessionId) != 0) {
6596 result = EFFECT_SESSION;
6597 }
6598
6599 for (size_t i = 0; i < mTracks.size(); ++i) {
6600 if (sessionId == mTracks[i]->sessionId()) {
6601 result |= TRACK_SESSION;
6602 break;
6603 }
6604 }
6605
6606 return result;
6607}
6608
6609KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6610{
6611 KeyedVector<int, bool> ids;
6612 Mutex::Autolock _l(mLock);
6613 for (size_t j = 0; j < mTracks.size(); ++j) {
6614 sp<RecordThread::RecordTrack> track = mTracks[j];
6615 int sessionId = track->sessionId();
6616 if (ids.indexOfKey(sessionId) < 0) {
6617 ids.add(sessionId, true);
6618 }
6619 }
6620 return ids;
6621}
6622
6623AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6624{
6625 Mutex::Autolock _l(mLock);
6626 AudioStreamIn *input = mInput;
6627 mInput = NULL;
6628 return input;
6629}
6630
6631// this method must always be called either with ThreadBase mLock held or inside the thread loop
6632audio_stream_t* AudioFlinger::RecordThread::stream() const
6633{
6634 if (mInput == NULL) {
6635 return NULL;
6636 }
6637 return &mInput->stream->common;
6638}
6639
6640status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6641{
6642 // only one chain per input thread
6643 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006644 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006645 return INVALID_OPERATION;
6646 }
6647 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006648 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006649 chain->setInBuffer(NULL);
6650 chain->setOutBuffer(NULL);
6651
6652 checkSuspendOnAddEffectChain_l(chain);
6653
Eric Laurent1b928682014-10-02 19:41:47 -07006654 // make sure enabled pre processing effects state is communicated to the HAL as we
6655 // just moved them to a new input stream.
6656 chain->syncHalEffectsState();
6657
Eric Laurent81784c32012-11-19 14:55:58 -08006658 mEffectChains.add(chain);
6659
6660 return NO_ERROR;
6661}
6662
6663size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6664{
6665 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6666 ALOGW_IF(mEffectChains.size() != 1,
6667 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6668 chain.get(), mEffectChains.size(), this);
6669 if (mEffectChains.size() == 1) {
6670 mEffectChains.removeAt(0);
6671 }
6672 return 0;
6673}
6674
Eric Laurent1c333e22014-05-20 10:48:17 -07006675status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6676 audio_patch_handle_t *handle)
6677{
6678 status_t status = NO_ERROR;
6679 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6680 // store new device and send to effects
6681 mInDevice = patch->sources[0].ext.device.type;
6682 for (size_t i = 0; i < mEffectChains.size(); i++) {
6683 mEffectChains[i]->setDevice_l(mInDevice);
6684 }
6685
6686 // disable AEC and NS if the device is a BT SCO headset supporting those
6687 // pre processings
6688 if (mTracks.size() > 0) {
6689 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6690 mAudioFlinger->btNrecIsOff();
6691 for (size_t i = 0; i < mTracks.size(); i++) {
6692 sp<RecordTrack> track = mTracks[i];
6693 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6694 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6695 }
6696 }
6697
6698 // store new source and send to effects
6699 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6700 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6701 for (size_t i = 0; i < mEffectChains.size(); i++) {
6702 mEffectChains[i]->setAudioSource_l(mAudioSource);
6703 }
6704 }
6705
6706 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6707 status = hwDevice->create_audio_patch(hwDevice,
6708 patch->num_sources,
6709 patch->sources,
6710 patch->num_sinks,
6711 patch->sinks,
6712 handle);
6713 } else {
6714 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6715 }
6716 return status;
6717}
6718
6719status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6720{
6721 status_t status = NO_ERROR;
6722 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6723 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6724 status = hwDevice->release_audio_patch(hwDevice, handle);
6725 } else {
6726 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6727 }
6728 return status;
6729}
6730
Eric Laurent83b88082014-06-20 18:31:16 -07006731void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6732{
6733 Mutex::Autolock _l(mLock);
6734 mTracks.add(record);
6735}
6736
6737void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6738{
6739 Mutex::Autolock _l(mLock);
6740 destroyTrack_l(record);
6741}
6742
6743void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6744{
6745 ThreadBase::getAudioPortConfig(config);
6746 config->role = AUDIO_PORT_ROLE_SINK;
6747 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6748 config->ext.mix.usecase.source = mAudioSource;
6749}
Eric Laurent1c333e22014-05-20 10:48:17 -07006750
Glenn Kasten63238ef2015-03-02 15:50:29 -08006751} // namespace android