blob: a853f07e2576e8f42baf998b1eb44046328b7809 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
59#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
62#include "SchedulingPolicyService.h"
63
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Glenn Kasten49d00ad2014-07-21 11:22:03 -070089#define max(a, b) ((a) > (b) ? (a) : (b))
90
Eric Laurent81784c32012-11-19 14:55:58 -080091namespace android {
92
93// retry counts for buffer fill timeout
94// 50 * ~20msecs = 1 second
95static const int8_t kMaxTrackRetries = 50;
96static const int8_t kMaxTrackStartupRetries = 50;
97// allow less retry attempts on direct output thread.
98// direct outputs can be a scarce resource in audio hardware and should
99// be released as quickly as possible.
100static const int8_t kMaxTrackRetriesDirect = 2;
101
102// don't warn about blocked writes or record buffer overflows more often than this
103static const nsecs_t kWarningThrottleNs = seconds(5);
104
105// RecordThread loop sleep time upon application overrun or audio HAL read error
106static const int kRecordThreadSleepUs = 5000;
107
Eric Laurent10351942014-05-08 18:49:52 -0700108// maximum time to wait in sendConfigEvent_l() for a status to be received
109static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800110
111// minimum sleep time for the mixer thread loop when tracks are active but in underrun
112static const uint32_t kMinThreadSleepTimeUs = 5000;
113// maximum divider applied to the active sleep time in the mixer thread loop
114static const uint32_t kMaxThreadSleepTimeShift = 2;
115
Andy Hung09a50072014-02-27 14:30:47 -0800116// minimum normal sink buffer size, expressed in milliseconds rather than frames
117static const uint32_t kMinNormalSinkBufferSizeMs = 20;
118// maximum normal sink buffer size
119static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800120
Eric Laurent972a1732013-09-04 09:42:59 -0700121// Offloaded output thread standby delay: allows track transition without going to standby
122static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// Whether to use fast mixer
125static const enum {
126 FastMixer_Never, // never initialize or use: for debugging only
127 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
128 // normal mixer multiplier is 1
129 FastMixer_Static, // initialize if needed, then use all the time if initialized,
130 // multiplier is calculated based on min & max normal mixer buffer size
131 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
132 // multiplier is calculated based on min & max normal mixer buffer size
133 // FIXME for FastMixer_Dynamic:
134 // Supporting this option will require fixing HALs that can't handle large writes.
135 // For example, one HAL implementation returns an error from a large write,
136 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
137 // We could either fix the HAL implementations, or provide a wrapper that breaks
138 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
139} kUseFastMixer = FastMixer_Static;
140
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700141// Whether to use fast capture
142static const enum {
143 FastCapture_Never, // never initialize or use: for debugging only
144 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
145 FastCapture_Static, // initialize if needed, then use all the time if initialized
146} kUseFastCapture = FastCapture_Static;
147
Eric Laurent81784c32012-11-19 14:55:58 -0800148// Priorities for requestPriority
149static const int kPriorityAudioApp = 2;
150static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700151static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800152
153// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
154// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800155// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
156// So for now we just assume that client is double-buffered for fast tracks.
157// FIXME It would be better for client to tell AudioFlinger the value of N,
158// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800159// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700160
161// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800162static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
Glenn Kasten03490092014-05-27 12:30:54 -0700164// The minimum and maximum allowed values
165static const int kFastTrackMultiplierMin = 1;
166static const int kFastTrackMultiplierMax = 2;
167
168// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
169static int sFastTrackMultiplier = kFastTrackMultiplier;
170
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700171// See Thread::readOnlyHeap().
172// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
173// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
174// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700175static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// ----------------------------------------------------------------------------
178
Glenn Kasten03490092014-05-27 12:30:54 -0700179static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
180
181static void sFastTrackMultiplierInit()
182{
183 char value[PROPERTY_VALUE_MAX];
184 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
185 char *endptr;
186 unsigned long ul = strtoul(value, &endptr, 0);
187 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
188 sFastTrackMultiplier = (int) ul;
189 }
190 }
191}
192
193// ----------------------------------------------------------------------------
194
Eric Laurent81784c32012-11-19 14:55:58 -0800195#ifdef ADD_BATTERY_DATA
196// To collect the amplifier usage
197static void addBatteryData(uint32_t params) {
198 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
199 if (service == NULL) {
200 // it already logged
201 return;
202 }
203
204 service->addBatteryData(params);
205}
206#endif
207
208
209// ----------------------------------------------------------------------------
210// CPU Stats
211// ----------------------------------------------------------------------------
212
213class CpuStats {
214public:
215 CpuStats();
216 void sample(const String8 &title);
217#ifdef DEBUG_CPU_USAGE
218private:
219 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
220 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
221
222 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
223
224 int mCpuNum; // thread's current CPU number
225 int mCpukHz; // frequency of thread's current CPU in kHz
226#endif
227};
228
229CpuStats::CpuStats()
230#ifdef DEBUG_CPU_USAGE
231 : mCpuNum(-1), mCpukHz(-1)
232#endif
233{
234}
235
Glenn Kasten0f11b512014-01-31 16:18:54 -0800236void CpuStats::sample(const String8 &title
237#ifndef DEBUG_CPU_USAGE
238 __unused
239#endif
240 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800241#ifdef DEBUG_CPU_USAGE
242 // get current thread's delta CPU time in wall clock ns
243 double wcNs;
244 bool valid = mCpuUsage.sampleAndEnable(wcNs);
245
246 // record sample for wall clock statistics
247 if (valid) {
248 mWcStats.sample(wcNs);
249 }
250
251 // get the current CPU number
252 int cpuNum = sched_getcpu();
253
254 // get the current CPU frequency in kHz
255 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
256
257 // check if either CPU number or frequency changed
258 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
259 mCpuNum = cpuNum;
260 mCpukHz = cpukHz;
261 // ignore sample for purposes of cycles
262 valid = false;
263 }
264
265 // if no change in CPU number or frequency, then record sample for cycle statistics
266 if (valid && mCpukHz > 0) {
267 double cycles = wcNs * cpukHz * 0.000001;
268 mHzStats.sample(cycles);
269 }
270
271 unsigned n = mWcStats.n();
272 // mCpuUsage.elapsed() is expensive, so don't call it every loop
273 if ((n & 127) == 1) {
274 long long elapsed = mCpuUsage.elapsed();
275 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
276 double perLoop = elapsed / (double) n;
277 double perLoop100 = perLoop * 0.01;
278 double perLoop1k = perLoop * 0.001;
279 double mean = mWcStats.mean();
280 double stddev = mWcStats.stddev();
281 double minimum = mWcStats.minimum();
282 double maximum = mWcStats.maximum();
283 double meanCycles = mHzStats.mean();
284 double stddevCycles = mHzStats.stddev();
285 double minCycles = mHzStats.minimum();
286 double maxCycles = mHzStats.maximum();
287 mCpuUsage.resetElapsed();
288 mWcStats.reset();
289 mHzStats.reset();
290 ALOGD("CPU usage for %s over past %.1f secs\n"
291 " (%u mixer loops at %.1f mean ms per loop):\n"
292 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
293 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
294 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
295 title.string(),
296 elapsed * .000000001, n, perLoop * .000001,
297 mean * .001,
298 stddev * .001,
299 minimum * .001,
300 maximum * .001,
301 mean / perLoop100,
302 stddev / perLoop100,
303 minimum / perLoop100,
304 maximum / perLoop100,
305 meanCycles / perLoop1k,
306 stddevCycles / perLoop1k,
307 minCycles / perLoop1k,
308 maxCycles / perLoop1k);
309
310 }
311 }
312#endif
313};
314
315// ----------------------------------------------------------------------------
316// ThreadBase
317// ----------------------------------------------------------------------------
318
Glenn Kasten97b7b752014-09-28 13:04:24 -0700319// static
320const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
321{
322 switch (type) {
323 case MIXER:
324 return "MIXER";
325 case DIRECT:
326 return "DIRECT";
327 case DUPLICATING:
328 return "DUPLICATING";
329 case RECORD:
330 return "RECORD";
331 case OFFLOAD:
332 return "OFFLOAD";
333 default:
334 return "unknown";
335 }
336}
337
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800338String8 devicesToString(audio_devices_t devices)
339{
340 static const struct mapping {
341 audio_devices_t mDevices;
342 const char * mString;
343 } mappingsOut[] = {
344 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
345 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
346 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
347 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
348 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
349 AUDIO_DEVICE_NONE, "NONE", // must be last
350 }, mappingsIn[] = {
351 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
352 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
353 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
354 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
355 AUDIO_DEVICE_NONE, "NONE", // must be last
356 };
357 String8 result;
358 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
359 const mapping *entry;
360 if (devices & AUDIO_DEVICE_BIT_IN) {
361 devices &= ~AUDIO_DEVICE_BIT_IN;
362 entry = mappingsIn;
363 } else {
364 entry = mappingsOut;
365 }
366 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
367 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
368 if (devices & entry->mDevices) {
369 if (!result.isEmpty()) {
370 result.append("|");
371 }
372 result.append(entry->mString);
373 }
374 }
375 if (devices & ~allDevices) {
376 if (!result.isEmpty()) {
377 result.append("|");
378 }
379 result.appendFormat("0x%X", devices & ~allDevices);
380 }
381 if (result.isEmpty()) {
382 result.append(entry->mString);
383 }
384 return result;
385}
386
387String8 inputFlagsToString(audio_input_flags_t flags)
388{
389 static const struct mapping {
390 audio_input_flags_t mFlag;
391 const char * mString;
392 } mappings[] = {
393 AUDIO_INPUT_FLAG_FAST, "FAST",
394 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
395 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
396 };
397 String8 result;
398 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
399 const mapping *entry;
400 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
401 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
402 if (flags & entry->mFlag) {
403 if (!result.isEmpty()) {
404 result.append("|");
405 }
406 result.append(entry->mString);
407 }
408 }
409 if (flags & ~allFlags) {
410 if (!result.isEmpty()) {
411 result.append("|");
412 }
413 result.appendFormat("0x%X", flags & ~allFlags);
414 }
415 if (result.isEmpty()) {
416 result.append(entry->mString);
417 }
418 return result;
419}
420
421String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700422{
423 static const struct mapping {
424 audio_output_flags_t mFlag;
425 const char * mString;
426 } mappings[] = {
427 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
428 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
429 AUDIO_OUTPUT_FLAG_FAST, "FAST",
430 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800431 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
433 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
434 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
435 };
436 String8 result;
437 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
438 const mapping *entry;
439 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
440 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
441 if (flags & entry->mFlag) {
442 if (!result.isEmpty()) {
443 result.append("|");
444 }
445 result.append(entry->mString);
446 }
447 }
448 if (flags & ~allFlags) {
449 if (!result.isEmpty()) {
450 result.append("|");
451 }
452 result.appendFormat("0x%X", flags & ~allFlags);
453 }
454 if (result.isEmpty()) {
455 result.append(entry->mString);
456 }
457 return result;
458}
459
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460const char *sourceToString(audio_source_t source)
461{
462 switch (source) {
463 case AUDIO_SOURCE_DEFAULT: return "default";
464 case AUDIO_SOURCE_MIC: return "mic";
465 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
466 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
467 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
468 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
469 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
470 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
471 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
472 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
473 case AUDIO_SOURCE_HOTWORD: return "hotword";
474 default: return "unknown";
475 }
476}
477
Eric Laurent81784c32012-11-19 14:55:58 -0800478AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
479 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
480 : Thread(false /*canCallJava*/),
481 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700482 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700483 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800484 // are set by PlaybackThread::readOutputParameters_l() or
485 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700486 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800487 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
488 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
489 // mName will be set by concrete (non-virtual) subclass
490 mDeathRecipient(new PMDeathRecipient(this))
491{
492}
493
494AudioFlinger::ThreadBase::~ThreadBase()
495{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700496 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700497 mConfigEvents.clear();
498
Eric Laurent81784c32012-11-19 14:55:58 -0800499 // do not lock the mutex in destructor
500 releaseWakeLock_l();
501 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800502 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800503 binder->unlinkToDeath(mDeathRecipient);
504 }
505}
506
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700507status_t AudioFlinger::ThreadBase::readyToRun()
508{
509 status_t status = initCheck();
510 if (status == NO_ERROR) {
511 ALOGI("AudioFlinger's thread %p ready to run", this);
512 } else {
513 ALOGE("No working audio driver found.");
514 }
515 return status;
516}
517
Eric Laurent81784c32012-11-19 14:55:58 -0800518void AudioFlinger::ThreadBase::exit()
519{
520 ALOGV("ThreadBase::exit");
521 // do any cleanup required for exit to succeed
522 preExit();
523 {
524 // This lock prevents the following race in thread (uniprocessor for illustration):
525 // if (!exitPending()) {
526 // // context switch from here to exit()
527 // // exit() calls requestExit(), what exitPending() observes
528 // // exit() calls signal(), which is dropped since no waiters
529 // // context switch back from exit() to here
530 // mWaitWorkCV.wait(...);
531 // // now thread is hung
532 // }
533 AutoMutex lock(mLock);
534 requestExit();
535 mWaitWorkCV.broadcast();
536 }
537 // When Thread::requestExitAndWait is made virtual and this method is renamed to
538 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
539 requestExitAndWait();
540}
541
542status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
543{
544 status_t status;
545
546 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
547 Mutex::Autolock _l(mLock);
548
Eric Laurent10351942014-05-08 18:49:52 -0700549 return sendSetParameterConfigEvent_l(keyValuePairs);
550}
551
552// sendConfigEvent_l() must be called with ThreadBase::mLock held
553// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
554status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
555{
556 status_t status = NO_ERROR;
557
558 mConfigEvents.add(event);
559 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800560 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700561 mLock.unlock();
562 {
563 Mutex::Autolock _l(event->mLock);
564 while (event->mWaitStatus) {
565 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
566 event->mStatus = TIMED_OUT;
567 event->mWaitStatus = false;
568 }
569 }
570 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800571 }
Eric Laurent10351942014-05-08 18:49:52 -0700572 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800573 return status;
574}
575
576void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
577{
578 Mutex::Autolock _l(mLock);
579 sendIoConfigEvent_l(event, param);
580}
581
582// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
583void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
584{
Eric Laurent10351942014-05-08 18:49:52 -0700585 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
586 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800587}
588
589// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
590void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
591{
Eric Laurent10351942014-05-08 18:49:52 -0700592 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
593 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800594}
595
Eric Laurent10351942014-05-08 18:49:52 -0700596// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
597status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800598{
Eric Laurent10351942014-05-08 18:49:52 -0700599 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
600 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700601}
602
Eric Laurent1c333e22014-05-20 10:48:17 -0700603status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
604 const struct audio_patch *patch,
605 audio_patch_handle_t *handle)
606{
607 Mutex::Autolock _l(mLock);
608 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
609 status_t status = sendConfigEvent_l(configEvent);
610 if (status == NO_ERROR) {
611 CreateAudioPatchConfigEventData *data =
612 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
613 *handle = data->mHandle;
614 }
615 return status;
616}
617
618status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
619 const audio_patch_handle_t handle)
620{
621 Mutex::Autolock _l(mLock);
622 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
623 return sendConfigEvent_l(configEvent);
624}
625
626
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700627// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700628void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700629{
Eric Laurent10351942014-05-08 18:49:52 -0700630 bool configChanged = false;
631
Eric Laurent81784c32012-11-19 14:55:58 -0800632 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700633 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
634 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800635 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700636 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700637 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700638 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
639 // FIXME Need to understand why this has to be done asynchronously
640 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700641 true /*asynchronous*/);
642 if (err != 0) {
643 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700644 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700645 }
646 } break;
647 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700648 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700649 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700650 } break;
651 case CFG_EVENT_SET_PARAMETER: {
652 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
653 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
654 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700655 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700656 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700657 case CFG_EVENT_CREATE_AUDIO_PATCH: {
658 CreateAudioPatchConfigEventData *data =
659 (CreateAudioPatchConfigEventData *)event->mData.get();
660 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
661 } break;
662 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
663 ReleaseAudioPatchConfigEventData *data =
664 (ReleaseAudioPatchConfigEventData *)event->mData.get();
665 event->mStatus = releaseAudioPatch_l(data->mHandle);
666 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700667 default:
Eric Laurent10351942014-05-08 18:49:52 -0700668 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700669 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800670 }
Eric Laurent10351942014-05-08 18:49:52 -0700671 {
672 Mutex::Autolock _l(event->mLock);
673 if (event->mWaitStatus) {
674 event->mWaitStatus = false;
675 event->mCond.signal();
676 }
677 }
678 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
679 }
680
681 if (configChanged) {
682 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800683 }
Eric Laurent81784c32012-11-19 14:55:58 -0800684}
685
Marco Nelissenb2208842014-02-07 14:00:50 -0800686String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
687 String8 s;
688 if (output) {
689 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
690 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
691 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
692 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
693 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
694 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
695 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
696 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
697 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
698 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
699 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
700 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
701 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
702 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
703 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
704 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
705 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
706 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
707 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
708 } else {
709 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
710 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
711 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
712 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
713 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
714 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
715 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
716 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
717 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
718 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
719 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
720 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
721 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
722 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
723 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
724 }
725 int len = s.length();
726 if (s.length() > 2) {
727 char *str = s.lockBuffer(len);
728 s.unlockBuffer(len - 2);
729 }
730 return s;
731}
732
Glenn Kasten0f11b512014-01-31 16:18:54 -0800733void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800734{
735 const size_t SIZE = 256;
736 char buffer[SIZE];
737 String8 result;
738
739 bool locked = AudioFlinger::dumpTryLock(mLock);
740 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700741 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
743
Elliott Hughes87cebad2014-05-22 10:14:43 -0700744 dprintf(fd, " I/O handle: %d\n", mId);
745 dprintf(fd, " TID: %d\n", getTid());
746 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700747 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700748 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700749 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700750 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700751 dprintf(fd, " Channel count: %u\n", mChannelCount);
752 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800753 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700754 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
755 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700756 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800757 size_t numConfig = mConfigEvents.size();
758 if (numConfig) {
759 for (size_t i = 0; i < numConfig; i++) {
760 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700761 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800762 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700763 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800764 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700765 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800766 }
Eric Laurent81784c32012-11-19 14:55:58 -0800767
768 if (locked) {
769 mLock.unlock();
770 }
771}
772
773void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
774{
775 const size_t SIZE = 256;
776 char buffer[SIZE];
777 String8 result;
778
Marco Nelissenb2208842014-02-07 14:00:50 -0800779 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000780 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800781 write(fd, buffer, strlen(buffer));
782
Marco Nelissenb2208842014-02-07 14:00:50 -0800783 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800784 sp<EffectChain> chain = mEffectChains[i];
785 if (chain != 0) {
786 chain->dump(fd, args);
787 }
788 }
789}
790
Marco Nelissene14a5d62013-10-03 08:51:24 -0700791void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800792{
793 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700794 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800795}
796
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100797String16 AudioFlinger::ThreadBase::getWakeLockTag()
798{
799 switch (mType) {
800 case MIXER:
801 return String16("AudioMix");
802 case DIRECT:
803 return String16("AudioDirectOut");
804 case DUPLICATING:
805 return String16("AudioDup");
806 case RECORD:
807 return String16("AudioIn");
808 case OFFLOAD:
809 return String16("AudioOffload");
810 default:
811 ALOG_ASSERT(false);
812 return String16("AudioUnknown");
813 }
814}
815
Marco Nelissene14a5d62013-10-03 08:51:24 -0700816void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800817{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800818 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800819 if (mPowerManager != 0) {
820 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700821 status_t status;
822 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700823 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700824 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100825 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700826 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700827 uid,
828 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700829 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700830 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700831 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100832 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700833 String16("media"),
834 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700835 }
Eric Laurent81784c32012-11-19 14:55:58 -0800836 if (status == NO_ERROR) {
837 mWakeLockToken = binder;
838 }
839 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
840 }
841}
842
843void AudioFlinger::ThreadBase::releaseWakeLock()
844{
845 Mutex::Autolock _l(mLock);
846 releaseWakeLock_l();
847}
848
849void AudioFlinger::ThreadBase::releaseWakeLock_l()
850{
851 if (mWakeLockToken != 0) {
852 ALOGV("releaseWakeLock_l() %s", mName);
853 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700854 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
855 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800856 }
857 mWakeLockToken.clear();
858 }
859}
860
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800861void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
862 Mutex::Autolock _l(mLock);
863 updateWakeLockUids_l(uids);
864}
865
866void AudioFlinger::ThreadBase::getPowerManager_l() {
867
868 if (mPowerManager == 0) {
869 // use checkService() to avoid blocking if power service is not up yet
870 sp<IBinder> binder =
871 defaultServiceManager()->checkService(String16("power"));
872 if (binder == 0) {
873 ALOGW("Thread %s cannot connect to the power manager service", mName);
874 } else {
875 mPowerManager = interface_cast<IPowerManager>(binder);
876 binder->linkToDeath(mDeathRecipient);
877 }
878 }
879}
880
881void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
882
883 getPowerManager_l();
884 if (mWakeLockToken == NULL) {
885 ALOGE("no wake lock to update!");
886 return;
887 }
888 if (mPowerManager != 0) {
889 sp<IBinder> binder = new BBinder();
890 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700891 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
892 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800893 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
894 }
895}
896
Eric Laurent81784c32012-11-19 14:55:58 -0800897void AudioFlinger::ThreadBase::clearPowerManager()
898{
899 Mutex::Autolock _l(mLock);
900 releaseWakeLock_l();
901 mPowerManager.clear();
902}
903
Glenn Kasten0f11b512014-01-31 16:18:54 -0800904void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800905{
906 sp<ThreadBase> thread = mThread.promote();
907 if (thread != 0) {
908 thread->clearPowerManager();
909 }
910 ALOGW("power manager service died !!!");
911}
912
913void AudioFlinger::ThreadBase::setEffectSuspended(
914 const effect_uuid_t *type, bool suspend, int sessionId)
915{
916 Mutex::Autolock _l(mLock);
917 setEffectSuspended_l(type, suspend, sessionId);
918}
919
920void AudioFlinger::ThreadBase::setEffectSuspended_l(
921 const effect_uuid_t *type, bool suspend, int sessionId)
922{
923 sp<EffectChain> chain = getEffectChain_l(sessionId);
924 if (chain != 0) {
925 if (type != NULL) {
926 chain->setEffectSuspended_l(type, suspend);
927 } else {
928 chain->setEffectSuspendedAll_l(suspend);
929 }
930 }
931
932 updateSuspendedSessions_l(type, suspend, sessionId);
933}
934
935void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
936{
937 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
938 if (index < 0) {
939 return;
940 }
941
942 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
943 mSuspendedSessions.valueAt(index);
944
945 for (size_t i = 0; i < sessionEffects.size(); i++) {
946 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
947 for (int j = 0; j < desc->mRefCount; j++) {
948 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
949 chain->setEffectSuspendedAll_l(true);
950 } else {
951 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
952 desc->mType.timeLow);
953 chain->setEffectSuspended_l(&desc->mType, true);
954 }
955 }
956 }
957}
958
959void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
960 bool suspend,
961 int sessionId)
962{
963 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
964
965 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
966
967 if (suspend) {
968 if (index >= 0) {
969 sessionEffects = mSuspendedSessions.valueAt(index);
970 } else {
971 mSuspendedSessions.add(sessionId, sessionEffects);
972 }
973 } else {
974 if (index < 0) {
975 return;
976 }
977 sessionEffects = mSuspendedSessions.valueAt(index);
978 }
979
980
981 int key = EffectChain::kKeyForSuspendAll;
982 if (type != NULL) {
983 key = type->timeLow;
984 }
985 index = sessionEffects.indexOfKey(key);
986
987 sp<SuspendedSessionDesc> desc;
988 if (suspend) {
989 if (index >= 0) {
990 desc = sessionEffects.valueAt(index);
991 } else {
992 desc = new SuspendedSessionDesc();
993 if (type != NULL) {
994 desc->mType = *type;
995 }
996 sessionEffects.add(key, desc);
997 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
998 }
999 desc->mRefCount++;
1000 } else {
1001 if (index < 0) {
1002 return;
1003 }
1004 desc = sessionEffects.valueAt(index);
1005 if (--desc->mRefCount == 0) {
1006 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1007 sessionEffects.removeItemsAt(index);
1008 if (sessionEffects.isEmpty()) {
1009 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1010 sessionId);
1011 mSuspendedSessions.removeItem(sessionId);
1012 }
1013 }
1014 }
1015 if (!sessionEffects.isEmpty()) {
1016 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1017 }
1018}
1019
1020void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1021 bool enabled,
1022 int sessionId)
1023{
1024 Mutex::Autolock _l(mLock);
1025 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1026}
1027
1028void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1029 bool enabled,
1030 int sessionId)
1031{
1032 if (mType != RECORD) {
1033 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1034 // another session. This gives the priority to well behaved effect control panels
1035 // and applications not using global effects.
1036 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1037 // global effects
1038 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1039 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1040 }
1041 }
1042
1043 sp<EffectChain> chain = getEffectChain_l(sessionId);
1044 if (chain != 0) {
1045 chain->checkSuspendOnEffectEnabled(effect, enabled);
1046 }
1047}
1048
1049// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1050sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1051 const sp<AudioFlinger::Client>& client,
1052 const sp<IEffectClient>& effectClient,
1053 int32_t priority,
1054 int sessionId,
1055 effect_descriptor_t *desc,
1056 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001057 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001058{
1059 sp<EffectModule> effect;
1060 sp<EffectHandle> handle;
1061 status_t lStatus;
1062 sp<EffectChain> chain;
1063 bool chainCreated = false;
1064 bool effectCreated = false;
1065 bool effectRegistered = false;
1066
1067 lStatus = initCheck();
1068 if (lStatus != NO_ERROR) {
1069 ALOGW("createEffect_l() Audio driver not initialized.");
1070 goto Exit;
1071 }
1072
Andy Hung98ef9782014-03-04 14:46:50 -08001073 // Reject any effect on Direct output threads for now, since the format of
1074 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1075 if (mType == DIRECT) {
1076 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
1077 desc->name, mName);
1078 lStatus = BAD_VALUE;
1079 goto Exit;
1080 }
1081
Andy Hung389cfdb2014-08-07 17:49:53 -07001082 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001083 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001084 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1085 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1086 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001087 lStatus = BAD_VALUE;
1088 goto Exit;
1089 }
1090
Eric Laurent5baf2af2013-09-12 17:37:00 -07001091 // Allow global effects only on offloaded and mixer threads
1092 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1093 switch (mType) {
1094 case MIXER:
1095 case OFFLOAD:
1096 break;
1097 case DIRECT:
1098 case DUPLICATING:
1099 case RECORD:
1100 default:
1101 ALOGW("createEffect_l() Cannot add global effect %s on thread %s", desc->name, mName);
1102 lStatus = BAD_VALUE;
1103 goto Exit;
1104 }
Eric Laurent81784c32012-11-19 14:55:58 -08001105 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001106
Eric Laurent81784c32012-11-19 14:55:58 -08001107 // Only Pre processor effects are allowed on input threads and only on input threads
1108 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1109 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1110 desc->name, desc->flags, mType);
1111 lStatus = BAD_VALUE;
1112 goto Exit;
1113 }
1114
1115 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1116
1117 { // scope for mLock
1118 Mutex::Autolock _l(mLock);
1119
1120 // check for existing effect chain with the requested audio session
1121 chain = getEffectChain_l(sessionId);
1122 if (chain == 0) {
1123 // create a new chain for this session
1124 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1125 chain = new EffectChain(this, sessionId);
1126 addEffectChain_l(chain);
1127 chain->setStrategy(getStrategyForSession_l(sessionId));
1128 chainCreated = true;
1129 } else {
1130 effect = chain->getEffectFromDesc_l(desc);
1131 }
1132
1133 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1134
1135 if (effect == 0) {
1136 int id = mAudioFlinger->nextUniqueId();
1137 // Check CPU and memory usage
1138 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1139 if (lStatus != NO_ERROR) {
1140 goto Exit;
1141 }
1142 effectRegistered = true;
1143 // create a new effect module if none present in the chain
1144 effect = new EffectModule(this, chain, desc, id, sessionId);
1145 lStatus = effect->status();
1146 if (lStatus != NO_ERROR) {
1147 goto Exit;
1148 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001149 effect->setOffloaded(mType == OFFLOAD, mId);
1150
Eric Laurent81784c32012-11-19 14:55:58 -08001151 lStatus = chain->addEffect_l(effect);
1152 if (lStatus != NO_ERROR) {
1153 goto Exit;
1154 }
1155 effectCreated = true;
1156
1157 effect->setDevice(mOutDevice);
1158 effect->setDevice(mInDevice);
1159 effect->setMode(mAudioFlinger->getMode());
1160 effect->setAudioSource(mAudioSource);
1161 }
1162 // create effect handle and connect it to effect module
1163 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001164 lStatus = handle->initCheck();
1165 if (lStatus == OK) {
1166 lStatus = effect->addHandle(handle.get());
1167 }
Eric Laurent81784c32012-11-19 14:55:58 -08001168 if (enabled != NULL) {
1169 *enabled = (int)effect->isEnabled();
1170 }
1171 }
1172
1173Exit:
1174 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1175 Mutex::Autolock _l(mLock);
1176 if (effectCreated) {
1177 chain->removeEffect_l(effect);
1178 }
1179 if (effectRegistered) {
1180 AudioSystem::unregisterEffect(effect->id());
1181 }
1182 if (chainCreated) {
1183 removeEffectChain_l(chain);
1184 }
1185 handle.clear();
1186 }
1187
Glenn Kasten9156ef32013-08-06 15:39:08 -07001188 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001189 return handle;
1190}
1191
1192sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1193{
1194 Mutex::Autolock _l(mLock);
1195 return getEffect_l(sessionId, effectId);
1196}
1197
1198sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1199{
1200 sp<EffectChain> chain = getEffectChain_l(sessionId);
1201 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1202}
1203
1204// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1205// PlaybackThread::mLock held
1206status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1207{
1208 // check for existing effect chain with the requested audio session
1209 int sessionId = effect->sessionId();
1210 sp<EffectChain> chain = getEffectChain_l(sessionId);
1211 bool chainCreated = false;
1212
Eric Laurent5baf2af2013-09-12 17:37:00 -07001213 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1214 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1215 this, effect->desc().name, effect->desc().flags);
1216
Eric Laurent81784c32012-11-19 14:55:58 -08001217 if (chain == 0) {
1218 // create a new chain for this session
1219 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1220 chain = new EffectChain(this, sessionId);
1221 addEffectChain_l(chain);
1222 chain->setStrategy(getStrategyForSession_l(sessionId));
1223 chainCreated = true;
1224 }
1225 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1226
1227 if (chain->getEffectFromId_l(effect->id()) != 0) {
1228 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1229 this, effect->desc().name, chain.get());
1230 return BAD_VALUE;
1231 }
1232
Eric Laurent5baf2af2013-09-12 17:37:00 -07001233 effect->setOffloaded(mType == OFFLOAD, mId);
1234
Eric Laurent81784c32012-11-19 14:55:58 -08001235 status_t status = chain->addEffect_l(effect);
1236 if (status != NO_ERROR) {
1237 if (chainCreated) {
1238 removeEffectChain_l(chain);
1239 }
1240 return status;
1241 }
1242
1243 effect->setDevice(mOutDevice);
1244 effect->setDevice(mInDevice);
1245 effect->setMode(mAudioFlinger->getMode());
1246 effect->setAudioSource(mAudioSource);
1247 return NO_ERROR;
1248}
1249
1250void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1251
1252 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1253 effect_descriptor_t desc = effect->desc();
1254 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1255 detachAuxEffect_l(effect->id());
1256 }
1257
1258 sp<EffectChain> chain = effect->chain().promote();
1259 if (chain != 0) {
1260 // remove effect chain if removing last effect
1261 if (chain->removeEffect_l(effect) == 0) {
1262 removeEffectChain_l(chain);
1263 }
1264 } else {
1265 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1266 }
1267}
1268
1269void AudioFlinger::ThreadBase::lockEffectChains_l(
1270 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1271{
1272 effectChains = mEffectChains;
1273 for (size_t i = 0; i < mEffectChains.size(); i++) {
1274 mEffectChains[i]->lock();
1275 }
1276}
1277
1278void AudioFlinger::ThreadBase::unlockEffectChains(
1279 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1280{
1281 for (size_t i = 0; i < effectChains.size(); i++) {
1282 effectChains[i]->unlock();
1283 }
1284}
1285
1286sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1287{
1288 Mutex::Autolock _l(mLock);
1289 return getEffectChain_l(sessionId);
1290}
1291
1292sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1293{
1294 size_t size = mEffectChains.size();
1295 for (size_t i = 0; i < size; i++) {
1296 if (mEffectChains[i]->sessionId() == sessionId) {
1297 return mEffectChains[i];
1298 }
1299 }
1300 return 0;
1301}
1302
1303void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1304{
1305 Mutex::Autolock _l(mLock);
1306 size_t size = mEffectChains.size();
1307 for (size_t i = 0; i < size; i++) {
1308 mEffectChains[i]->setMode_l(mode);
1309 }
1310}
1311
Eric Laurent83b88082014-06-20 18:31:16 -07001312void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1313{
1314 config->type = AUDIO_PORT_TYPE_MIX;
1315 config->ext.mix.handle = mId;
1316 config->sample_rate = mSampleRate;
1317 config->format = mFormat;
1318 config->channel_mask = mChannelMask;
1319 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1320 AUDIO_PORT_CONFIG_FORMAT;
1321}
1322
1323
Eric Laurent81784c32012-11-19 14:55:58 -08001324// ----------------------------------------------------------------------------
1325// Playback
1326// ----------------------------------------------------------------------------
1327
1328AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1329 AudioStreamOut* output,
1330 audio_io_handle_t id,
1331 audio_devices_t device,
1332 type_t type)
1333 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001334 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001335 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001336 mMixerBuffer(NULL),
1337 mMixerBufferSize(0),
1338 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1339 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001340 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001341 mEffectBuffer(NULL),
1342 mEffectBufferSize(0),
1343 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1344 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001345 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001346 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001347 // mStreamTypes[] initialized in constructor body
1348 mOutput(output),
1349 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1350 mMixerStatus(MIXER_IDLE),
1351 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1352 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001353 mBytesRemaining(0),
1354 mCurrentWriteLength(0),
1355 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001356 mWriteAckSequence(0),
1357 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001358 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001359 mScreenState(AudioFlinger::mScreenState),
1360 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001361 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001362 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001363 // mLatchD, mLatchQ,
1364 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001365{
1366 snprintf(mName, kNameLength, "AudioOut_%X", id);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001367 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08001368
1369 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1370 // it would be safer to explicitly pass initial masterVolume/masterMute as
1371 // parameter.
1372 //
1373 // If the HAL we are using has support for master volume or master mute,
1374 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1375 // and the mute set to false).
1376 mMasterVolume = audioFlinger->masterVolume_l();
1377 mMasterMute = audioFlinger->masterMute_l();
1378 if (mOutput && mOutput->audioHwDev) {
1379 if (mOutput->audioHwDev->canSetMasterVolume()) {
1380 mMasterVolume = 1.0;
1381 }
1382
1383 if (mOutput->audioHwDev->canSetMasterMute()) {
1384 mMasterMute = false;
1385 }
1386 }
1387
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001388 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001389
Eric Laurent223fd5c2014-11-11 13:43:36 -08001390 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001391 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001392 stream = (audio_stream_type_t) (stream + 1)) {
1393 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1394 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1395 }
Eric Laurent81784c32012-11-19 14:55:58 -08001396}
1397
1398AudioFlinger::PlaybackThread::~PlaybackThread()
1399{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001400 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001401 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001402 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001403 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001404}
1405
1406void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1407{
1408 dumpInternals(fd, args);
1409 dumpTracks(fd, args);
1410 dumpEffectChains(fd, args);
1411}
1412
Glenn Kasten0f11b512014-01-31 16:18:54 -08001413void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001414{
1415 const size_t SIZE = 256;
1416 char buffer[SIZE];
1417 String8 result;
1418
Marco Nelissenb2208842014-02-07 14:00:50 -08001419 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001420 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1421 const stream_type_t *st = &mStreamTypes[i];
1422 if (i > 0) {
1423 result.appendFormat(", ");
1424 }
1425 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1426 if (st->mute) {
1427 result.append("M");
1428 }
1429 }
1430 result.append("\n");
1431 write(fd, result.string(), result.length());
1432 result.clear();
1433
Eric Laurent81784c32012-11-19 14:55:58 -08001434 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1435 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001436 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001437 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001438
1439 size_t numtracks = mTracks.size();
1440 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001441 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001442 size_t numactiveseen = 0;
1443 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001444 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001445 Track::appendDumpHeader(result);
1446 for (size_t i = 0; i < numtracks; ++i) {
1447 sp<Track> track = mTracks[i];
1448 if (track != 0) {
1449 bool active = mActiveTracks.indexOf(track) >= 0;
1450 if (active) {
1451 numactiveseen++;
1452 }
1453 track->dump(buffer, SIZE, active);
1454 result.append(buffer);
1455 }
1456 }
1457 } else {
1458 result.append("\n");
1459 }
1460 if (numactiveseen != numactive) {
1461 // some tracks in the active list were not in the tracks list
1462 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1463 " not in the track list\n");
1464 result.append(buffer);
1465 Track::appendDumpHeader(result);
1466 for (size_t i = 0; i < numactive; ++i) {
1467 sp<Track> track = mActiveTracks[i].promote();
1468 if (track != 0 && mTracks.indexOf(track) < 0) {
1469 track->dump(buffer, SIZE, true);
1470 result.append(buffer);
1471 }
1472 }
1473 }
1474
1475 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001476}
1477
1478void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1479{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001480 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001481 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1482 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1483 dprintf(fd, " Total writes: %d\n", mNumWrites);
1484 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1485 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1486 dprintf(fd, " Suspend count: %d\n", mSuspended);
1487 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1488 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1489 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1490 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001491 AudioStreamOut *output = mOutput;
1492 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1493 String8 flagsAsString = outputFlagsToString(flags);
1494 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001495
1496 dumpBase(fd, args);
1497}
1498
1499// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001500
1501void AudioFlinger::PlaybackThread::onFirstRef()
1502{
1503 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1504}
1505
1506// ThreadBase virtuals
1507void AudioFlinger::PlaybackThread::preExit()
1508{
1509 ALOGV(" preExit()");
1510 // FIXME this is using hard-coded strings but in the future, this functionality will be
1511 // converted to use audio HAL extensions required to support tunneling
1512 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1513}
1514
1515// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1516sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1517 const sp<AudioFlinger::Client>& client,
1518 audio_stream_type_t streamType,
1519 uint32_t sampleRate,
1520 audio_format_t format,
1521 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001522 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001523 const sp<IMemory>& sharedBuffer,
1524 int sessionId,
1525 IAudioFlinger::track_flags_t *flags,
1526 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001527 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001528 status_t *status)
1529{
Glenn Kasten74935e42013-12-19 08:56:45 -08001530 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001531 sp<Track> track;
1532 status_t lStatus;
1533
1534 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1535
1536 // client expresses a preference for FAST, but we get the final say
1537 if (*flags & IAudioFlinger::TRACK_FAST) {
1538 if (
1539 // not timed
1540 (!isTimed) &&
1541 // either of these use cases:
1542 (
1543 // use case 1: shared buffer with any frame count
1544 (
1545 (sharedBuffer != 0)
1546 ) ||
1547 // use case 2: callback handler and frame count is default or at least as large as HAL
1548 (
1549 (tid != -1) &&
1550 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001551 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001552 )
1553 ) &&
1554 // PCM data
1555 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001556 // identical channel mask to sink, or mono in and stereo sink
1557 (channelMask == mChannelMask ||
1558 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1559 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001560 // hardware sample rate
1561 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001562 // normal mixer has an associated fast mixer
1563 hasFastMixer() &&
1564 // there are sufficient fast track slots available
1565 (mFastTrackAvailMask != 0)
1566 // FIXME test that MixerThread for this fast track has a capable output HAL
1567 // FIXME add a permission test also?
1568 ) {
1569 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1570 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001571 // read the fast track multiplier property the first time it is needed
1572 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1573 if (ok != 0) {
1574 ALOGE("%s pthread_once failed: %d", __func__, ok);
1575 }
1576 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001577 }
1578 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1579 frameCount, mFrameCount);
1580 } else {
1581 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001582 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1583 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001584 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001585 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001586 audio_is_linear_pcm(format),
1587 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1588 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001589 }
1590 }
1591 // For normal PCM streaming tracks, update minimum frame count.
1592 // For compatibility with AudioTrack calculation, buffer depth is forced
1593 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1594 // This is probably too conservative, but legacy application code may depend on it.
1595 // If you change this calculation, also review the start threshold which is related.
1596 if (!(*flags & IAudioFlinger::TRACK_FAST)
1597 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001598 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1599 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1600 if (minBufCount < 2) {
1601 minBufCount = 2;
1602 }
Andy Hung0e48d252015-01-26 11:43:15 -08001603 size_t minFrameCount =
1604 minBufCount * sourceFramesNeeded(sampleRate, mNormalFrameCount, mSampleRate);
1605 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001606 frameCount = minFrameCount;
1607 }
Eric Laurent81784c32012-11-19 14:55:58 -08001608 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001609 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001610
Glenn Kastenc3df8382014-03-13 15:05:25 -07001611 switch (mType) {
1612
1613 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001614 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001615 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001616 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1617 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001618 sampleRate, format, channelMask, mOutput, mFormat);
1619 lStatus = BAD_VALUE;
1620 goto Exit;
1621 }
1622 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001623 break;
1624
1625 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001626 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001627 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1628 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001629 sampleRate, format, channelMask, mOutput, mFormat);
1630 lStatus = BAD_VALUE;
1631 goto Exit;
1632 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001633 break;
1634
1635 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001636 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001637 ALOGE("createTrack_l() Bad parameter: format %#x \""
1638 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001639 format, mOutput, mFormat);
1640 lStatus = BAD_VALUE;
1641 goto Exit;
1642 }
Andy Hungcd044842014-08-07 11:04:34 -07001643 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001644 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1645 lStatus = BAD_VALUE;
1646 goto Exit;
1647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001648 break;
1649
Eric Laurent81784c32012-11-19 14:55:58 -08001650 }
1651
1652 lStatus = initCheck();
1653 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001654 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001655 goto Exit;
1656 }
1657
1658 { // scope for mLock
1659 Mutex::Autolock _l(mLock);
1660
1661 // all tracks in same audio session must share the same routing strategy otherwise
1662 // conflicts will happen when tracks are moved from one output to another by audio policy
1663 // manager
1664 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1665 for (size_t i = 0; i < mTracks.size(); ++i) {
1666 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001667 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001668 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1669 if (sessionId == t->sessionId() && strategy != actual) {
1670 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1671 strategy, actual);
1672 lStatus = BAD_VALUE;
1673 goto Exit;
1674 }
1675 }
1676 }
1677
1678 if (!isTimed) {
1679 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001680 channelMask, frameCount, NULL, sharedBuffer,
1681 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001682 } else {
1683 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001684 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001685 }
Glenn Kasten03003332013-08-06 15:40:54 -07001686
1687 // new Track always returns non-NULL,
1688 // but TimedTrack::create() is a factory that could fail by returning NULL
1689 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1690 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001691 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001692 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001693 goto Exit;
1694 }
1695 mTracks.add(track);
1696
1697 sp<EffectChain> chain = getEffectChain_l(sessionId);
1698 if (chain != 0) {
1699 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1700 track->setMainBuffer(chain->inBuffer());
1701 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1702 chain->incTrackCnt();
1703 }
1704
1705 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1706 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1707 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1708 // so ask activity manager to do this on our behalf
1709 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1710 }
1711 }
1712
1713 lStatus = NO_ERROR;
1714
1715Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001716 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001717 return track;
1718}
1719
1720uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1721{
1722 return latency;
1723}
1724
1725uint32_t AudioFlinger::PlaybackThread::latency() const
1726{
1727 Mutex::Autolock _l(mLock);
1728 return latency_l();
1729}
1730uint32_t AudioFlinger::PlaybackThread::latency_l() const
1731{
1732 if (initCheck() == NO_ERROR) {
1733 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1734 } else {
1735 return 0;
1736 }
1737}
1738
1739void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1740{
1741 Mutex::Autolock _l(mLock);
1742 // Don't apply master volume in SW if our HAL can do it for us.
1743 if (mOutput && mOutput->audioHwDev &&
1744 mOutput->audioHwDev->canSetMasterVolume()) {
1745 mMasterVolume = 1.0;
1746 } else {
1747 mMasterVolume = value;
1748 }
1749}
1750
1751void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1752{
1753 Mutex::Autolock _l(mLock);
1754 // Don't apply master mute in SW if our HAL can do it for us.
1755 if (mOutput && mOutput->audioHwDev &&
1756 mOutput->audioHwDev->canSetMasterMute()) {
1757 mMasterMute = false;
1758 } else {
1759 mMasterMute = muted;
1760 }
1761}
1762
1763void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1764{
1765 Mutex::Autolock _l(mLock);
1766 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001767 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001768}
1769
1770void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1771{
1772 Mutex::Autolock _l(mLock);
1773 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001774 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001775}
1776
1777float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1778{
1779 Mutex::Autolock _l(mLock);
1780 return mStreamTypes[stream].volume;
1781}
1782
1783// addTrack_l() must be called with ThreadBase::mLock held
1784status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1785{
1786 status_t status = ALREADY_EXISTS;
1787
1788 // set retry count for buffer fill
1789 track->mRetryCount = kMaxTrackStartupRetries;
1790 if (mActiveTracks.indexOf(track) < 0) {
1791 // the track is newly added, make sure it fills up all its
1792 // buffers before playing. This is to ensure the client will
1793 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001794 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001795 TrackBase::track_state state = track->mState;
1796 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001797 status = AudioSystem::startOutput(mId, track->streamType(),
1798 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001799 mLock.lock();
1800 // abort track was stopped/paused while we released the lock
1801 if (state != track->mState) {
1802 if (status == NO_ERROR) {
1803 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001804 AudioSystem::stopOutput(mId, track->streamType(),
1805 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001806 mLock.lock();
1807 }
1808 return INVALID_OPERATION;
1809 }
1810 // abort if start is rejected by audio policy manager
1811 if (status != NO_ERROR) {
1812 return PERMISSION_DENIED;
1813 }
1814#ifdef ADD_BATTERY_DATA
1815 // to track the speaker usage
1816 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1817#endif
1818 }
1819
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001820 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001821 track->mResetDone = false;
1822 track->mPresentationCompleteFrames = 0;
1823 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001824 mWakeLockUids.add(track->uid());
1825 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001826 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001827 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1828 if (chain != 0) {
1829 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1830 track->sessionId());
1831 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001832 }
1833
1834 status = NO_ERROR;
1835 }
1836
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001837 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001838 return status;
1839}
1840
Eric Laurentbfb1b832013-01-07 09:53:42 -08001841bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001842{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001843 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001844 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001845 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1846 track->mState = TrackBase::STOPPED;
1847 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001848 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001849 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001850 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001851 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001852
1853 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001854}
1855
1856void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1857{
1858 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1859 mTracks.remove(track);
1860 deleteTrackName_l(track->name());
1861 // redundant as track is about to be destroyed, for dumpsys only
1862 track->mName = -1;
1863 if (track->isFastTrack()) {
1864 int index = track->mFastIndex;
1865 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1866 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1867 mFastTrackAvailMask |= 1 << index;
1868 // redundant as track is about to be destroyed, for dumpsys only
1869 track->mFastIndex = -1;
1870 }
1871 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1872 if (chain != 0) {
1873 chain->decTrackCnt();
1874 }
1875}
1876
Eric Laurentede6c3b2013-09-19 14:37:46 -07001877void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001878{
1879 // Thread could be blocked waiting for async
1880 // so signal it to handle state changes immediately
1881 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1882 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1883 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001884 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001885}
1886
Eric Laurent81784c32012-11-19 14:55:58 -08001887String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1888{
Eric Laurent81784c32012-11-19 14:55:58 -08001889 Mutex::Autolock _l(mLock);
1890 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001891 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001892 }
1893
Glenn Kastend8ea6992013-07-16 14:17:15 -07001894 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1895 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001896 free(s);
1897 return out_s8;
1898}
1899
Eric Laurent021cf962014-05-13 10:18:14 -07001900void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001901 AudioSystem::OutputDescriptor desc;
1902 void *param2 = NULL;
1903
Eric Laurent021cf962014-05-13 10:18:14 -07001904 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001905 param);
1906
1907 switch (event) {
1908 case AudioSystem::OUTPUT_OPENED:
1909 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001910 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001911 desc.samplingRate = mSampleRate;
1912 desc.format = mFormat;
1913 desc.frameCount = mNormalFrameCount; // FIXME see
1914 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001915 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001916 param2 = &desc;
1917 break;
1918
1919 case AudioSystem::STREAM_CONFIG_CHANGED:
1920 param2 = &param;
1921 case AudioSystem::OUTPUT_CLOSED:
1922 default:
1923 break;
1924 }
Eric Laurent021cf962014-05-13 10:18:14 -07001925 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001926}
1927
Eric Laurentbfb1b832013-01-07 09:53:42 -08001928void AudioFlinger::PlaybackThread::writeCallback()
1929{
1930 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001931 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001932}
1933
1934void AudioFlinger::PlaybackThread::drainCallback()
1935{
1936 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001937 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001938}
1939
Eric Laurent3b4529e2013-09-05 18:09:19 -07001940void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941{
1942 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001943 // reject out of sequence requests
1944 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1945 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001946 mWaitWorkCV.signal();
1947 }
1948}
1949
Eric Laurent3b4529e2013-09-05 18:09:19 -07001950void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951{
1952 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001953 // reject out of sequence requests
1954 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1955 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001956 mWaitWorkCV.signal();
1957 }
1958}
1959
1960// static
1961int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001962 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 void *cookie)
1964{
1965 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1966 ALOGV("asyncCallback() event %d", event);
1967 switch (event) {
1968 case STREAM_CBK_EVENT_WRITE_READY:
1969 me->writeCallback();
1970 break;
1971 case STREAM_CBK_EVENT_DRAIN_READY:
1972 me->drainCallback();
1973 break;
1974 default:
1975 ALOGW("asyncCallback() unknown event %d", event);
1976 break;
1977 }
1978 return 0;
1979}
1980
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001981void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001982{
Glenn Kastenadad3d72014-02-21 14:51:43 -08001983 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08001984 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1985 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001986 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001987 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001988 }
Andy Hung9a592762014-07-21 21:56:01 -07001989 if ((mType == MIXER || mType == DUPLICATING)
1990 && !isValidPcmSinkChannelMask(mChannelMask)) {
1991 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
1992 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001993 }
Andy Hunge5412692014-05-16 11:25:07 -07001994 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07001995 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1996 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001997 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08001998 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07001999 }
Andy Hung6146c082014-03-18 11:56:15 -07002000 if ((mType == MIXER || mType == DUPLICATING)
2001 && !isValidPcmSinkFormat(mFormat)) {
2002 LOG_FATAL("HAL format %#x not supported for mixed output",
2003 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002004 }
Eric Laurent665470b2014-07-03 16:37:08 -07002005 mFrameSize = audio_stream_out_frame_size(mOutput->stream);
Glenn Kasten70949c42013-08-06 07:40:12 -07002006 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2007 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002008 if (mFrameCount & 15) {
2009 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2010 mFrameCount);
2011 }
2012
Eric Laurentbfb1b832013-01-07 09:53:42 -08002013 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2014 (mOutput->stream->set_callback != NULL)) {
2015 if (mOutput->stream->set_callback(mOutput->stream,
2016 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2017 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002018 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002019 }
2020 }
2021
Eric Laurentd1f69b02014-12-15 14:33:13 -08002022 mHwSupportsPause = false;
2023 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2024 if (mOutput->stream->pause != NULL) {
2025 if (mOutput->stream->resume != NULL) {
2026 mHwSupportsPause = true;
2027 } else {
2028 ALOGW("direct output implements pause but not resume");
2029 }
2030 } else if (mOutput->stream->resume != NULL) {
2031 ALOGW("direct output implements resume but not pause");
2032 }
2033 }
2034
Andy Hungfbfc3952015-01-15 13:33:51 -08002035 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2036 // For best precision, we use float instead of the associated output
2037 // device format (typically PCM 16 bit).
2038
2039 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2040 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2041 mBufferSize = mFrameSize * mFrameCount;
2042
2043 // TODO: We currently use the associated output device channel mask and sample rate.
2044 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2045 // (if a valid mask) to avoid premature downmix.
2046 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2047 // instead of the output device sample rate to avoid loss of high frequency information.
2048 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2049 }
2050
Andy Hung09a50072014-02-27 14:30:47 -08002051 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002052 double multiplier = 1.0;
2053 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2054 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002055 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2056 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002057 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2058 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2059 maxNormalFrameCount = maxNormalFrameCount & ~15;
2060 if (maxNormalFrameCount < minNormalFrameCount) {
2061 maxNormalFrameCount = minNormalFrameCount;
2062 }
2063 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2064 if (multiplier <= 1.0) {
2065 multiplier = 1.0;
2066 } else if (multiplier <= 2.0) {
2067 if (2 * mFrameCount <= maxNormalFrameCount) {
2068 multiplier = 2.0;
2069 } else {
2070 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2071 }
2072 } else {
2073 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002074 // 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 -08002075 // track, but we sometimes have to do this to satisfy the maximum frame count
2076 // constraint)
2077 // FIXME this rounding up should not be done if no HAL SRC
2078 uint32_t truncMult = (uint32_t) multiplier;
2079 if ((truncMult & 1)) {
2080 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2081 ++truncMult;
2082 }
2083 }
2084 multiplier = (double) truncMult;
2085 }
2086 }
2087 mNormalFrameCount = multiplier * mFrameCount;
2088 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002089 if (mType == MIXER || mType == DUPLICATING) {
2090 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2091 }
Andy Hung09a50072014-02-27 14:30:47 -08002092 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002093 mNormalFrameCount);
2094
Andy Hung010a1a12014-03-13 13:57:33 -07002095 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2096 // Originally this was int16_t[] array, need to remove legacy implications.
2097 free(mSinkBuffer);
2098 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002099 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2100 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2101 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002102 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002103
Andy Hung69aed5f2014-02-25 17:24:40 -08002104 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2105 // drives the output.
2106 free(mMixerBuffer);
2107 mMixerBuffer = NULL;
2108 if (mMixerBufferEnabled) {
2109 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2110 mMixerBufferSize = mNormalFrameCount * mChannelCount
2111 * audio_bytes_per_sample(mMixerBufferFormat);
2112 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2113 }
Andy Hung98ef9782014-03-04 14:46:50 -08002114 free(mEffectBuffer);
2115 mEffectBuffer = NULL;
2116 if (mEffectBufferEnabled) {
2117 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2118 mEffectBufferSize = mNormalFrameCount * mChannelCount
2119 * audio_bytes_per_sample(mEffectBufferFormat);
2120 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2121 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002122
Eric Laurent81784c32012-11-19 14:55:58 -08002123 // force reconfiguration of effect chains and engines to take new buffer size and audio
2124 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002125 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002126 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2127 // matter.
2128 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2129 Vector< sp<EffectChain> > effectChains = mEffectChains;
2130 for (size_t i = 0; i < effectChains.size(); i ++) {
2131 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2132 }
2133}
2134
2135
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002136status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002137{
2138 if (halFrames == NULL || dspFrames == NULL) {
2139 return BAD_VALUE;
2140 }
2141 Mutex::Autolock _l(mLock);
2142 if (initCheck() != NO_ERROR) {
2143 return INVALID_OPERATION;
2144 }
2145 size_t framesWritten = mBytesWritten / mFrameSize;
2146 *halFrames = framesWritten;
2147
2148 if (isSuspended()) {
2149 // return an estimation of rendered frames when the output is suspended
2150 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2151 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2152 return NO_ERROR;
2153 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002154 status_t status;
2155 uint32_t frames;
2156 status = mOutput->stream->get_render_position(mOutput->stream, &frames);
2157 *dspFrames = (size_t)frames;
2158 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002159 }
2160}
2161
2162uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2163{
2164 Mutex::Autolock _l(mLock);
2165 uint32_t result = 0;
2166 if (getEffectChain_l(sessionId) != 0) {
2167 result = EFFECT_SESSION;
2168 }
2169
2170 for (size_t i = 0; i < mTracks.size(); ++i) {
2171 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002172 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002173 result |= TRACK_SESSION;
2174 break;
2175 }
2176 }
2177
2178 return result;
2179}
2180
2181uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2182{
2183 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2184 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2185 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2186 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2187 }
2188 for (size_t i = 0; i < mTracks.size(); i++) {
2189 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002190 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002191 return AudioSystem::getStrategyForStream(track->streamType());
2192 }
2193 }
2194 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2195}
2196
2197
2198AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
2199{
2200 Mutex::Autolock _l(mLock);
2201 return mOutput;
2202}
2203
2204AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2205{
2206 Mutex::Autolock _l(mLock);
2207 AudioStreamOut *output = mOutput;
2208 mOutput = NULL;
2209 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2210 // must push a NULL and wait for ack
2211 mOutputSink.clear();
2212 mPipeSink.clear();
2213 mNormalSink.clear();
2214 return output;
2215}
2216
2217// this method must always be called either with ThreadBase mLock held or inside the thread loop
2218audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2219{
2220 if (mOutput == NULL) {
2221 return NULL;
2222 }
2223 return &mOutput->stream->common;
2224}
2225
2226uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2227{
2228 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2229}
2230
2231status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2232{
2233 if (!isValidSyncEvent(event)) {
2234 return BAD_VALUE;
2235 }
2236
2237 Mutex::Autolock _l(mLock);
2238
2239 for (size_t i = 0; i < mTracks.size(); ++i) {
2240 sp<Track> track = mTracks[i];
2241 if (event->triggerSession() == track->sessionId()) {
2242 (void) track->setSyncEvent(event);
2243 return NO_ERROR;
2244 }
2245 }
2246
2247 return NAME_NOT_FOUND;
2248}
2249
2250bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2251{
2252 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2253}
2254
2255void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2256 const Vector< sp<Track> >& tracksToRemove)
2257{
2258 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002259 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002260 for (size_t i = 0 ; i < count ; i++) {
2261 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002262 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002263 AudioSystem::stopOutput(mId, track->streamType(),
2264 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002265#ifdef ADD_BATTERY_DATA
2266 // to track the speaker usage
2267 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2268#endif
2269 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002270 AudioSystem::releaseOutput(mId, track->streamType(),
2271 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272 }
Eric Laurent81784c32012-11-19 14:55:58 -08002273 }
2274 }
2275 }
Eric Laurent81784c32012-11-19 14:55:58 -08002276}
2277
2278void AudioFlinger::PlaybackThread::checkSilentMode_l()
2279{
2280 if (!mMasterMute) {
2281 char value[PROPERTY_VALUE_MAX];
2282 if (property_get("ro.audio.silent", value, "0") > 0) {
2283 char *endptr;
2284 unsigned long ul = strtoul(value, &endptr, 0);
2285 if (*endptr == '\0' && ul != 0) {
2286 ALOGD("Silence is golden");
2287 // The setprop command will not allow a property to be changed after
2288 // the first time it is set, so we don't have to worry about un-muting.
2289 setMasterMute_l(true);
2290 }
2291 }
2292 }
2293}
2294
2295// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002296ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002297{
2298 // FIXME rewrite to reduce number of system calls
2299 mLastWriteTime = systemTime();
2300 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002301 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002302 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002303
2304 // If an NBAIO sink is present, use it to write the normal mixer's submix
2305 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002306
Andy Hung010a1a12014-03-13 13:57:33 -07002307 const size_t count = mBytesRemaining / mFrameSize;
2308
Simon Wilson2d590962012-11-29 15:18:50 -08002309 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002310 // update the setpoint when AudioFlinger::mScreenState changes
2311 uint32_t screenState = AudioFlinger::mScreenState;
2312 if (screenState != mScreenState) {
2313 mScreenState = screenState;
2314 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2315 if (pipe != NULL) {
2316 pipe->setAvgFrames((mScreenState & 1) ?
2317 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2318 }
2319 }
Andy Hung010a1a12014-03-13 13:57:33 -07002320 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002321 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002322 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002323 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002324 } else {
2325 bytesWritten = framesWritten;
2326 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002327 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002328 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002329 if (status == NO_ERROR) {
2330 size_t totalFramesWritten = mNormalSink->framesWritten();
2331 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2332 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002333 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002334 mLatchDValid = true;
2335 }
2336 }
Eric Laurent81784c32012-11-19 14:55:58 -08002337 // otherwise use the HAL / AudioStreamOut directly
2338 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002340
Eric Laurentbfb1b832013-01-07 09:53:42 -08002341 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002342 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2343 mWriteAckSequence += 2;
2344 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002345 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002346 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002347 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002348 // FIXME We should have an implementation of timestamps for direct output threads.
2349 // They are used e.g for multichannel PCM playback over HDMI.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002350 bytesWritten = mOutput->stream->write(mOutput->stream,
Andy Hung2098f272014-02-27 14:00:06 -08002351 (char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 if (mUseAsyncWrite &&
2353 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2354 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002355 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002356 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002357 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002358 }
Eric Laurent81784c32012-11-19 14:55:58 -08002359 }
2360
Eric Laurent81784c32012-11-19 14:55:58 -08002361 mNumWrites++;
2362 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002363 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 return bytesWritten;
2365}
2366
2367void AudioFlinger::PlaybackThread::threadLoop_drain()
2368{
2369 if (mOutput->stream->drain) {
2370 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2371 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002372 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2373 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002375 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 }
2377 mOutput->stream->drain(mOutput->stream,
2378 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2379 : AUDIO_DRAIN_ALL);
2380 }
2381}
2382
2383void AudioFlinger::PlaybackThread::threadLoop_exit()
2384{
Eric Laurent275e8e92014-11-30 15:14:47 -08002385 {
2386 Mutex::Autolock _l(mLock);
2387 for (size_t i = 0; i < mTracks.size(); i++) {
2388 sp<Track> track = mTracks[i];
2389 track->invalidate();
2390 }
2391 }
Eric Laurent81784c32012-11-19 14:55:58 -08002392}
2393
2394/*
2395The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002396 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002397 - activeSleepTime from activeSleepTimeUs()
2398 - idleSleepTime from idleSleepTimeUs()
2399 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2400 - maxPeriod from frame count and sample rate (MIXER only)
2401
2402The parameters that affect these derived values are:
2403 - frame count
2404 - frame size
2405 - sample rate
2406 - device type: A2DP or not
2407 - device latency
2408 - format: PCM or not
2409 - active sleep time
2410 - idle sleep time
2411*/
2412
2413void AudioFlinger::PlaybackThread::cacheParameters_l()
2414{
Andy Hung25c2dac2014-02-27 14:56:00 -08002415 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002416 activeSleepTime = activeSleepTimeUs();
2417 idleSleepTime = idleSleepTimeUs();
2418}
2419
2420void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2421{
Glenn Kasten7c027242012-12-26 14:43:16 -08002422 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002423 this, streamType, mTracks.size());
2424 Mutex::Autolock _l(mLock);
2425
2426 size_t size = mTracks.size();
2427 for (size_t i = 0; i < size; i++) {
2428 sp<Track> t = mTracks[i];
2429 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002430 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002431 }
2432 }
2433}
2434
2435status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2436{
2437 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002438 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2439 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002440 bool ownsBuffer = false;
2441
2442 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2443 if (session > 0) {
2444 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002445 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002446 if (mType != DIRECT) {
2447 size_t numSamples = mNormalFrameCount * mChannelCount;
2448 buffer = new int16_t[numSamples];
2449 memset(buffer, 0, numSamples * sizeof(int16_t));
2450 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2451 ownsBuffer = true;
2452 }
2453
2454 // Attach all tracks with same session ID to this chain.
2455 for (size_t i = 0; i < mTracks.size(); ++i) {
2456 sp<Track> track = mTracks[i];
2457 if (session == track->sessionId()) {
2458 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2459 buffer);
2460 track->setMainBuffer(buffer);
2461 chain->incTrackCnt();
2462 }
2463 }
2464
2465 // indicate all active tracks in the chain
2466 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2467 sp<Track> track = mActiveTracks[i].promote();
2468 if (track == 0) {
2469 continue;
2470 }
2471 if (session == track->sessionId()) {
2472 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2473 chain->incActiveTrackCnt();
2474 }
2475 }
2476 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002477 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002478 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002479 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2480 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002481 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2482 // chains list in order to be processed last as it contains output stage effects
2483 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2484 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2485 // after track specific effects and before output stage
2486 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2487 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2488 // Effect chain for other sessions are inserted at beginning of effect
2489 // chains list to be processed before output mix effects. Relative order between other
2490 // sessions is not important
2491 size_t size = mEffectChains.size();
2492 size_t i = 0;
2493 for (i = 0; i < size; i++) {
2494 if (mEffectChains[i]->sessionId() < session) {
2495 break;
2496 }
2497 }
2498 mEffectChains.insertAt(chain, i);
2499 checkSuspendOnAddEffectChain_l(chain);
2500
2501 return NO_ERROR;
2502}
2503
2504size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2505{
2506 int session = chain->sessionId();
2507
2508 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2509
2510 for (size_t i = 0; i < mEffectChains.size(); i++) {
2511 if (chain == mEffectChains[i]) {
2512 mEffectChains.removeAt(i);
2513 // detach all active tracks from the chain
2514 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2515 sp<Track> track = mActiveTracks[i].promote();
2516 if (track == 0) {
2517 continue;
2518 }
2519 if (session == track->sessionId()) {
2520 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2521 chain.get(), session);
2522 chain->decActiveTrackCnt();
2523 }
2524 }
2525
2526 // detach all tracks with same session ID from this chain
2527 for (size_t i = 0; i < mTracks.size(); ++i) {
2528 sp<Track> track = mTracks[i];
2529 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002530 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002531 chain->decTrackCnt();
2532 }
2533 }
2534 break;
2535 }
2536 }
2537 return mEffectChains.size();
2538}
2539
2540status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2541 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2542{
2543 Mutex::Autolock _l(mLock);
2544 return attachAuxEffect_l(track, EffectId);
2545}
2546
2547status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2548 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2549{
2550 status_t status = NO_ERROR;
2551
2552 if (EffectId == 0) {
2553 track->setAuxBuffer(0, NULL);
2554 } else {
2555 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2556 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2557 if (effect != 0) {
2558 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2559 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2560 } else {
2561 status = INVALID_OPERATION;
2562 }
2563 } else {
2564 status = BAD_VALUE;
2565 }
2566 }
2567 return status;
2568}
2569
2570void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2571{
2572 for (size_t i = 0; i < mTracks.size(); ++i) {
2573 sp<Track> track = mTracks[i];
2574 if (track->auxEffectId() == effectId) {
2575 attachAuxEffect_l(track, 0);
2576 }
2577 }
2578}
2579
2580bool AudioFlinger::PlaybackThread::threadLoop()
2581{
2582 Vector< sp<Track> > tracksToRemove;
2583
2584 standbyTime = systemTime();
2585
2586 // MIXER
2587 nsecs_t lastWarning = 0;
2588
2589 // DUPLICATING
2590 // FIXME could this be made local to while loop?
2591 writeFrames = 0;
2592
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002593 int lastGeneration = 0;
2594
Eric Laurent81784c32012-11-19 14:55:58 -08002595 cacheParameters_l();
2596 sleepTime = idleSleepTime;
2597
2598 if (mType == MIXER) {
2599 sleepTimeShift = 0;
2600 }
2601
2602 CpuStats cpuStats;
2603 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2604
2605 acquireWakeLock();
2606
Glenn Kasten9e58b552013-01-18 15:09:48 -08002607 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2608 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2609 // and then that string will be logged at the next convenient opportunity.
2610 const char *logString = NULL;
2611
Eric Laurent664539d2013-09-23 18:24:31 -07002612 checkSilentMode_l();
2613
Eric Laurent81784c32012-11-19 14:55:58 -08002614 while (!exitPending())
2615 {
2616 cpuStats.sample(myName);
2617
2618 Vector< sp<EffectChain> > effectChains;
2619
Eric Laurent81784c32012-11-19 14:55:58 -08002620 { // scope for mLock
2621
2622 Mutex::Autolock _l(mLock);
2623
Eric Laurent021cf962014-05-13 10:18:14 -07002624 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002625
Glenn Kasten9e58b552013-01-18 15:09:48 -08002626 if (logString != NULL) {
2627 mNBLogWriter->logTimestamp();
2628 mNBLogWriter->log(logString);
2629 logString = NULL;
2630 }
2631
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002632 // Gather the framesReleased counters for all active tracks,
2633 // and latch them atomically with the timestamp.
2634 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2635 mLatchD.mFramesReleased.clear();
2636 size_t size = mActiveTracks.size();
2637 for (size_t i = 0; i < size; i++) {
2638 sp<Track> t = mActiveTracks[i].promote();
2639 if (t != 0) {
2640 mLatchD.mFramesReleased.add(t.get(),
2641 t->mAudioTrackServerProxy->framesReleased());
2642 }
2643 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002644 if (mLatchDValid) {
2645 mLatchQ = mLatchD;
2646 mLatchDValid = false;
2647 mLatchQValid = true;
2648 }
2649
Eric Laurent81784c32012-11-19 14:55:58 -08002650 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 if (mSignalPending) {
2652 // A signal was raised while we were unlocked
2653 mSignalPending = false;
2654 } else if (waitingAsyncCallback_l()) {
2655 if (exitPending()) {
2656 break;
2657 }
2658 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002659 mWakeLockUids.clear();
2660 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661 ALOGV("wait async completion");
2662 mWaitWorkCV.wait(mLock);
2663 ALOGV("async completion/wake");
2664 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002665 standbyTime = systemTime() + standbyDelay;
2666 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002667
2668 continue;
2669 }
2670 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 isSuspended()) {
2672 // put audio hardware into standby after short delay
2673 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002674
2675 threadLoop_standby();
2676
2677 mStandby = true;
2678 }
2679
2680 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2681 // we're about to wait, flush the binder command buffer
2682 IPCThreadState::self()->flushCommands();
2683
2684 clearOutputTracks();
2685
2686 if (exitPending()) {
2687 break;
2688 }
2689
2690 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002691 mWakeLockUids.clear();
2692 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002693 // wait until we have something to do...
2694 ALOGV("%s going to sleep", myName.string());
2695 mWaitWorkCV.wait(mLock);
2696 ALOGV("%s waking up", myName.string());
2697 acquireWakeLock_l();
2698
2699 mMixerStatus = MIXER_IDLE;
2700 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2701 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002702 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002703 checkSilentMode_l();
2704
2705 standbyTime = systemTime() + standbyDelay;
2706 sleepTime = idleSleepTime;
2707 if (mType == MIXER) {
2708 sleepTimeShift = 0;
2709 }
2710
2711 continue;
2712 }
2713 }
Eric Laurent81784c32012-11-19 14:55:58 -08002714 // mMixerStatusIgnoringFastTracks is also updated internally
2715 mMixerStatus = prepareTracks_l(&tracksToRemove);
2716
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002717 // compare with previously applied list
2718 if (lastGeneration != mActiveTracksGeneration) {
2719 // update wakelock
2720 updateWakeLockUids_l(mWakeLockUids);
2721 lastGeneration = mActiveTracksGeneration;
2722 }
2723
Eric Laurent81784c32012-11-19 14:55:58 -08002724 // prevent any changes in effect chain list and in each effect chain
2725 // during mixing and effect process as the audio buffers could be deleted
2726 // or modified if an effect is created or deleted
2727 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002728 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002729
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730 if (mBytesRemaining == 0) {
2731 mCurrentWriteLength = 0;
2732 if (mMixerStatus == MIXER_TRACKS_READY) {
2733 // threadLoop_mix() sets mCurrentWriteLength
2734 threadLoop_mix();
2735 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2736 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2737 // threadLoop_sleepTime sets sleepTime to 0 if data
2738 // must be written to HAL
2739 threadLoop_sleepTime();
2740 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002741 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002742 }
2743 }
Andy Hung98ef9782014-03-04 14:46:50 -08002744 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2745 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2746 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2747 // or mSinkBuffer (if there are no effects).
2748 //
2749 // This is done pre-effects computation; if effects change to
2750 // support higher precision, this needs to move.
2751 //
2752 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2753 // TODO use sleepTime == 0 as an additional condition.
2754 if (mMixerBufferValid) {
2755 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2756 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2757
2758 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2759 mNormalFrameCount * mChannelCount);
2760 }
2761
Eric Laurentbfb1b832013-01-07 09:53:42 -08002762 mBytesRemaining = mCurrentWriteLength;
2763 if (isSuspended()) {
2764 sleepTime = suspendSleepTimeUs();
2765 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002766 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767 mBytesRemaining = 0;
2768 }
Eric Laurent81784c32012-11-19 14:55:58 -08002769
Eric Laurentbfb1b832013-01-07 09:53:42 -08002770 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002771 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772 for (size_t i = 0; i < effectChains.size(); i ++) {
2773 effectChains[i]->process_l();
2774 }
Eric Laurent81784c32012-11-19 14:55:58 -08002775 }
2776 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002777 // Process effect chains for offloaded thread even if no audio
2778 // was read from audio track: process only updates effect state
2779 // and thus does have to be synchronized with audio writes but may have
2780 // to be called while waiting for async write callback
2781 if (mType == OFFLOAD) {
2782 for (size_t i = 0; i < effectChains.size(); i ++) {
2783 effectChains[i]->process_l();
2784 }
2785 }
Eric Laurent81784c32012-11-19 14:55:58 -08002786
Andy Hung98ef9782014-03-04 14:46:50 -08002787 // Only if the Effects buffer is enabled and there is data in the
2788 // Effects buffer (buffer valid), we need to
2789 // copy into the sink buffer.
2790 // TODO use sleepTime == 0 as an additional condition.
2791 if (mEffectBufferValid) {
2792 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2793 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2794 mNormalFrameCount * mChannelCount);
2795 }
2796
Eric Laurent81784c32012-11-19 14:55:58 -08002797 // enable changes in effect chain
2798 unlockEffectChains(effectChains);
2799
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800 if (!waitingAsyncCallback()) {
2801 // sleepTime == 0 means we must write to audio hardware
2802 if (sleepTime == 0) {
2803 if (mBytesRemaining) {
2804 ssize_t ret = threadLoop_write();
2805 if (ret < 0) {
2806 mBytesRemaining = 0;
2807 } else {
2808 mBytesWritten += ret;
2809 mBytesRemaining -= ret;
2810 }
2811 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2812 (mMixerStatus == MIXER_DRAIN_ALL)) {
2813 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002814 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002815 if (mType == MIXER) {
2816 // write blocked detection
2817 nsecs_t now = systemTime();
2818 nsecs_t delta = now - mLastWriteTime;
2819 if (!mStandby && delta > maxPeriod) {
2820 mNumDelayedWrites++;
2821 if ((now - lastWarning) > kWarningThrottleNs) {
2822 ATRACE_NAME("underrun");
2823 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2824 ns2ms(delta), mNumDelayedWrites, this);
2825 lastWarning = now;
2826 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002827 }
2828 }
Eric Laurent81784c32012-11-19 14:55:58 -08002829
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002831 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002832 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002833 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002834 }
Eric Laurent81784c32012-11-19 14:55:58 -08002835 }
2836
2837 // Finally let go of removed track(s), without the lock held
2838 // since we can't guarantee the destructors won't acquire that
2839 // same lock. This will also mutate and push a new fast mixer state.
2840 threadLoop_removeTracks(tracksToRemove);
2841 tracksToRemove.clear();
2842
2843 // FIXME I don't understand the need for this here;
2844 // it was in the original code but maybe the
2845 // assignment in saveOutputTracks() makes this unnecessary?
2846 clearOutputTracks();
2847
2848 // Effect chains will be actually deleted here if they were removed from
2849 // mEffectChains list during mixing or effects processing
2850 effectChains.clear();
2851
2852 // FIXME Note that the above .clear() is no longer necessary since effectChains
2853 // is now local to this block, but will keep it for now (at least until merge done).
2854 }
2855
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 threadLoop_exit();
2857
Eric Laurentcf817a22014-08-04 20:36:31 -07002858 if (!mStandby) {
2859 threadLoop_standby();
2860 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002861 }
2862
2863 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002864 mWakeLockUids.clear();
2865 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002866
2867 ALOGV("Thread %p type %d exiting", this, mType);
2868 return false;
2869}
2870
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871// removeTracks_l() must be called with ThreadBase::mLock held
2872void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2873{
2874 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002875 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876 for (size_t i=0 ; i<count ; i++) {
2877 const sp<Track>& track = tracksToRemove.itemAt(i);
2878 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002879 mWakeLockUids.remove(track->uid());
2880 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2882 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2883 if (chain != 0) {
2884 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2885 track->sessionId());
2886 chain->decActiveTrackCnt();
2887 }
2888 if (track->isTerminated()) {
2889 removeTrack_l(track);
2890 }
2891 }
2892 }
2893
2894}
Eric Laurent81784c32012-11-19 14:55:58 -08002895
Eric Laurentaccc1472013-09-20 09:36:34 -07002896status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2897{
2898 if (mNormalSink != 0) {
2899 return mNormalSink->getTimestamp(timestamp);
2900 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002901 if ((mType == OFFLOAD || mType == DIRECT)
2902 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002903 uint64_t position64;
2904 int ret = mOutput->stream->get_presentation_position(
2905 mOutput->stream, &position64, &timestamp.mTime);
2906 if (ret == 0) {
2907 timestamp.mPosition = (uint32_t)position64;
2908 return NO_ERROR;
2909 }
2910 }
2911 return INVALID_OPERATION;
2912}
Eric Laurent1c333e22014-05-20 10:48:17 -07002913
2914status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2915 audio_patch_handle_t *handle)
2916{
2917 status_t status = NO_ERROR;
2918 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2919 // store new device and send to effects
2920 audio_devices_t type = AUDIO_DEVICE_NONE;
2921 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2922 type |= patch->sinks[i].ext.device.type;
2923 }
2924 mOutDevice = type;
2925 for (size_t i = 0; i < mEffectChains.size(); i++) {
2926 mEffectChains[i]->setDevice_l(mOutDevice);
2927 }
2928
2929 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2930 status = hwDevice->create_audio_patch(hwDevice,
2931 patch->num_sources,
2932 patch->sources,
2933 patch->num_sinks,
2934 patch->sinks,
2935 handle);
2936 } else {
2937 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2938 }
2939 return status;
2940}
2941
2942status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2943{
2944 status_t status = NO_ERROR;
2945 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2946 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2947 status = hwDevice->release_audio_patch(hwDevice, handle);
2948 } else {
2949 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2950 }
2951 return status;
2952}
2953
Eric Laurent83b88082014-06-20 18:31:16 -07002954void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2955{
2956 Mutex::Autolock _l(mLock);
2957 mTracks.add(track);
2958}
2959
2960void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2961{
2962 Mutex::Autolock _l(mLock);
2963 destroyTrack_l(track);
2964}
2965
2966void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2967{
2968 ThreadBase::getAudioPortConfig(config);
2969 config->role = AUDIO_PORT_ROLE_SOURCE;
2970 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2971 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2972}
2973
Eric Laurent81784c32012-11-19 14:55:58 -08002974// ----------------------------------------------------------------------------
2975
2976AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2977 audio_io_handle_t id, audio_devices_t device, type_t type)
2978 : PlaybackThread(audioFlinger, output, id, device, type),
2979 // mAudioMixer below
2980 // mFastMixer below
2981 mFastMixerFutex(0)
2982 // mOutputSink below
2983 // mPipeSink below
2984 // mNormalSink below
2985{
2986 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07002987 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08002988 "mFrameCount=%d, mNormalFrameCount=%d",
2989 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2990 mNormalFrameCount);
2991 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2992
Andy Hungfbfc3952015-01-15 13:33:51 -08002993 if (type == DUPLICATING) {
2994 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
2995 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
2996 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
2997 return;
2998 }
Eric Laurent81784c32012-11-19 14:55:58 -08002999 // create an NBAIO sink for the HAL output stream, and negotiate
3000 mOutputSink = new AudioStreamOutSink(output->stream);
3001 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003002 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003003 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3004 ALOG_ASSERT(index == 0);
3005
3006 // initialize fast mixer depending on configuration
3007 bool initFastMixer;
3008 switch (kUseFastMixer) {
3009 case FastMixer_Never:
3010 initFastMixer = false;
3011 break;
3012 case FastMixer_Always:
3013 initFastMixer = true;
3014 break;
3015 case FastMixer_Static:
3016 case FastMixer_Dynamic:
3017 initFastMixer = mFrameCount < mNormalFrameCount;
3018 break;
3019 }
3020 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003021 audio_format_t fastMixerFormat;
3022 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3023 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3024 } else {
3025 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3026 }
3027 if (mFormat != fastMixerFormat) {
3028 // change our Sink format to accept our intermediate precision
3029 mFormat = fastMixerFormat;
3030 free(mSinkBuffer);
3031 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3032 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3033 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3034 }
Eric Laurent81784c32012-11-19 14:55:58 -08003035
3036 // create a MonoPipe to connect our submix to FastMixer
3037 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003038 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003039 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003040 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003041 format.mFormat = fastMixerFormat;
3042 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3043
Eric Laurent81784c32012-11-19 14:55:58 -08003044 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3045 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3046 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3047 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3048 const NBAIO_Format offers[1] = {format};
3049 size_t numCounterOffers = 0;
3050 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3051 ALOG_ASSERT(index == 0);
3052 monoPipe->setAvgFrames((mScreenState & 1) ?
3053 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3054 mPipeSink = monoPipe;
3055
Glenn Kasten46909e72013-02-26 09:20:22 -08003056#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003057 if (mTeeSinkOutputEnabled) {
3058 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003059 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3060 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003061 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003062 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003063 ALOG_ASSERT(index == 0);
3064 mTeeSink = teeSink;
3065 PipeReader *teeSource = new PipeReader(*teeSink);
3066 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003067 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003068 ALOG_ASSERT(index == 0);
3069 mTeeSource = teeSource;
3070 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003071#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003072
3073 // create fast mixer and configure it initially with just one fast track for our submix
3074 mFastMixer = new FastMixer();
3075 FastMixerStateQueue *sq = mFastMixer->sq();
3076#ifdef STATE_QUEUE_DUMP
3077 sq->setObserverDump(&mStateQueueObserverDump);
3078 sq->setMutatorDump(&mStateQueueMutatorDump);
3079#endif
3080 FastMixerState *state = sq->begin();
3081 FastTrack *fastTrack = &state->mFastTracks[0];
3082 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3083 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3084 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003085 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3086 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003087 fastTrack->mGeneration++;
3088 state->mFastTracksGen++;
3089 state->mTrackMask = 1;
3090 // fast mixer will use the HAL output sink
3091 state->mOutputSink = mOutputSink.get();
3092 state->mOutputSinkGen++;
3093 state->mFrameCount = mFrameCount;
3094 state->mCommand = FastMixerState::COLD_IDLE;
3095 // already done in constructor initialization list
3096 //mFastMixerFutex = 0;
3097 state->mColdFutexAddr = &mFastMixerFutex;
3098 state->mColdGen++;
3099 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003100#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003101 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003102#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003103 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3104 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003105 sq->end();
3106 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3107
3108 // start the fast mixer
3109 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3110 pid_t tid = mFastMixer->getTid();
3111 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3112 if (err != 0) {
3113 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3114 kPriorityFastMixer, getpid_cached, tid, err);
3115 }
3116
3117#ifdef AUDIO_WATCHDOG
3118 // create and start the watchdog
3119 mAudioWatchdog = new AudioWatchdog();
3120 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3121 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3122 tid = mAudioWatchdog->getTid();
3123 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3124 if (err != 0) {
3125 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3126 kPriorityFastMixer, getpid_cached, tid, err);
3127 }
3128#endif
3129
Eric Laurent81784c32012-11-19 14:55:58 -08003130 }
3131
3132 switch (kUseFastMixer) {
3133 case FastMixer_Never:
3134 case FastMixer_Dynamic:
3135 mNormalSink = mOutputSink;
3136 break;
3137 case FastMixer_Always:
3138 mNormalSink = mPipeSink;
3139 break;
3140 case FastMixer_Static:
3141 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3142 break;
3143 }
3144}
3145
3146AudioFlinger::MixerThread::~MixerThread()
3147{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003148 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003149 FastMixerStateQueue *sq = mFastMixer->sq();
3150 FastMixerState *state = sq->begin();
3151 if (state->mCommand == FastMixerState::COLD_IDLE) {
3152 int32_t old = android_atomic_inc(&mFastMixerFutex);
3153 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003154 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003155 }
3156 }
3157 state->mCommand = FastMixerState::EXIT;
3158 sq->end();
3159 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3160 mFastMixer->join();
3161 // Though the fast mixer thread has exited, it's state queue is still valid.
3162 // We'll use that extract the final state which contains one remaining fast track
3163 // corresponding to our sub-mix.
3164 state = sq->begin();
3165 ALOG_ASSERT(state->mTrackMask == 1);
3166 FastTrack *fastTrack = &state->mFastTracks[0];
3167 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3168 delete fastTrack->mBufferProvider;
3169 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003170 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003171#ifdef AUDIO_WATCHDOG
3172 if (mAudioWatchdog != 0) {
3173 mAudioWatchdog->requestExit();
3174 mAudioWatchdog->requestExitAndWait();
3175 mAudioWatchdog.clear();
3176 }
3177#endif
3178 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003179 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003180 delete mAudioMixer;
3181}
3182
3183
3184uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3185{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003186 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003187 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3188 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3189 }
3190 return latency;
3191}
3192
3193
3194void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3195{
3196 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3197}
3198
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003200{
3201 // FIXME we should only do one push per cycle; confirm this is true
3202 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003203 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003204 FastMixerStateQueue *sq = mFastMixer->sq();
3205 FastMixerState *state = sq->begin();
3206 if (state->mCommand != FastMixerState::MIX_WRITE &&
3207 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3208 if (state->mCommand == FastMixerState::COLD_IDLE) {
3209 int32_t old = android_atomic_inc(&mFastMixerFutex);
3210 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003211 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003212 }
3213#ifdef AUDIO_WATCHDOG
3214 if (mAudioWatchdog != 0) {
3215 mAudioWatchdog->resume();
3216 }
3217#endif
3218 }
3219 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003220#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003221 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003222 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003223#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003224 sq->end();
3225 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3226 if (kUseFastMixer == FastMixer_Dynamic) {
3227 mNormalSink = mPipeSink;
3228 }
3229 } else {
3230 sq->end(false /*didModify*/);
3231 }
3232 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003233 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003234}
3235
3236void AudioFlinger::MixerThread::threadLoop_standby()
3237{
3238 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003239 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003240 FastMixerStateQueue *sq = mFastMixer->sq();
3241 FastMixerState *state = sq->begin();
3242 if (!(state->mCommand & FastMixerState::IDLE)) {
3243 state->mCommand = FastMixerState::COLD_IDLE;
3244 state->mColdFutexAddr = &mFastMixerFutex;
3245 state->mColdGen++;
3246 mFastMixerFutex = 0;
3247 sq->end();
3248 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3249 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3250 if (kUseFastMixer == FastMixer_Dynamic) {
3251 mNormalSink = mOutputSink;
3252 }
3253#ifdef AUDIO_WATCHDOG
3254 if (mAudioWatchdog != 0) {
3255 mAudioWatchdog->pause();
3256 }
3257#endif
3258 } else {
3259 sq->end(false /*didModify*/);
3260 }
3261 }
3262 PlaybackThread::threadLoop_standby();
3263}
3264
Eric Laurentbfb1b832013-01-07 09:53:42 -08003265bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3266{
3267 return false;
3268}
3269
3270bool AudioFlinger::PlaybackThread::shouldStandby_l()
3271{
3272 return !mStandby;
3273}
3274
3275bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3276{
3277 Mutex::Autolock _l(mLock);
3278 return waitingAsyncCallback_l();
3279}
3280
Eric Laurent81784c32012-11-19 14:55:58 -08003281// shared by MIXER and DIRECT, overridden by DUPLICATING
3282void AudioFlinger::PlaybackThread::threadLoop_standby()
3283{
3284 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
3285 mOutput->stream->common.standby(&mOutput->stream->common);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003286 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003287 // discard any pending drain or write ack by incrementing sequence
3288 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3289 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003291 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3292 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003294 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003295}
3296
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003297void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3298{
3299 ALOGV("signal playback thread");
3300 broadcast_l();
3301}
3302
Eric Laurent81784c32012-11-19 14:55:58 -08003303void AudioFlinger::MixerThread::threadLoop_mix()
3304{
3305 // obtain the presentation timestamp of the next output buffer
3306 int64_t pts;
3307 status_t status = INVALID_OPERATION;
3308
3309 if (mNormalSink != 0) {
3310 status = mNormalSink->getNextWriteTimestamp(&pts);
3311 } else {
3312 status = mOutputSink->getNextWriteTimestamp(&pts);
3313 }
3314
3315 if (status != NO_ERROR) {
3316 pts = AudioBufferProvider::kInvalidPTS;
3317 }
3318
3319 // mix buffers...
3320 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003321 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003322 // increase sleep time progressively when application underrun condition clears.
3323 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3324 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3325 // such that we would underrun the audio HAL.
3326 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3327 sleepTimeShift--;
3328 }
3329 sleepTime = 0;
3330 standbyTime = systemTime() + standbyDelay;
3331 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003332
Eric Laurent81784c32012-11-19 14:55:58 -08003333}
3334
3335void AudioFlinger::MixerThread::threadLoop_sleepTime()
3336{
3337 // If no tracks are ready, sleep once for the duration of an output
3338 // buffer size, then write 0s to the output
3339 if (sleepTime == 0) {
3340 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3341 sleepTime = activeSleepTime >> sleepTimeShift;
3342 if (sleepTime < kMinThreadSleepTimeUs) {
3343 sleepTime = kMinThreadSleepTimeUs;
3344 }
3345 // reduce sleep time in case of consecutive application underruns to avoid
3346 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3347 // duration we would end up writing less data than needed by the audio HAL if
3348 // the condition persists.
3349 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3350 sleepTimeShift++;
3351 }
3352 } else {
3353 sleepTime = idleSleepTime;
3354 }
3355 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003356 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3357 // before effects processing or output.
3358 if (mMixerBufferValid) {
3359 memset(mMixerBuffer, 0, mMixerBufferSize);
3360 } else {
3361 memset(mSinkBuffer, 0, mSinkBufferSize);
3362 }
Eric Laurent81784c32012-11-19 14:55:58 -08003363 sleepTime = 0;
3364 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3365 "anticipated start");
3366 }
3367 // TODO add standby time extension fct of effect tail
3368}
3369
3370// prepareTracks_l() must be called with ThreadBase::mLock held
3371AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3372 Vector< sp<Track> > *tracksToRemove)
3373{
3374
3375 mixer_state mixerStatus = MIXER_IDLE;
3376 // find out which tracks need to be processed
3377 size_t count = mActiveTracks.size();
3378 size_t mixedTracks = 0;
3379 size_t tracksWithEffect = 0;
3380 // counts only _active_ fast tracks
3381 size_t fastTracks = 0;
3382 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3383
3384 float masterVolume = mMasterVolume;
3385 bool masterMute = mMasterMute;
3386
3387 if (masterMute) {
3388 masterVolume = 0;
3389 }
3390 // Delegate master volume control to effect in output mix effect chain if needed
3391 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3392 if (chain != 0) {
3393 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3394 chain->setVolume_l(&v, &v);
3395 masterVolume = (float)((v + (1 << 23)) >> 24);
3396 chain.clear();
3397 }
3398
3399 // prepare a new state to push
3400 FastMixerStateQueue *sq = NULL;
3401 FastMixerState *state = NULL;
3402 bool didModify = false;
3403 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003404 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003405 sq = mFastMixer->sq();
3406 state = sq->begin();
3407 }
3408
Andy Hung69aed5f2014-02-25 17:24:40 -08003409 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003410 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003411
Eric Laurent81784c32012-11-19 14:55:58 -08003412 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003413 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003414 if (t == 0) {
3415 continue;
3416 }
3417
3418 // this const just means the local variable doesn't change
3419 Track* const track = t.get();
3420
3421 // process fast tracks
3422 if (track->isFastTrack()) {
3423
3424 // It's theoretically possible (though unlikely) for a fast track to be created
3425 // and then removed within the same normal mix cycle. This is not a problem, as
3426 // the track never becomes active so it's fast mixer slot is never touched.
3427 // The converse, of removing an (active) track and then creating a new track
3428 // at the identical fast mixer slot within the same normal mix cycle,
3429 // is impossible because the slot isn't marked available until the end of each cycle.
3430 int j = track->mFastIndex;
3431 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3432 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3433 FastTrack *fastTrack = &state->mFastTracks[j];
3434
3435 // Determine whether the track is currently in underrun condition,
3436 // and whether it had a recent underrun.
3437 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3438 FastTrackUnderruns underruns = ftDump->mUnderruns;
3439 uint32_t recentFull = (underruns.mBitFields.mFull -
3440 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3441 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3442 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3443 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3444 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3445 uint32_t recentUnderruns = recentPartial + recentEmpty;
3446 track->mObservedUnderruns = underruns;
3447 // don't count underruns that occur while stopping or pausing
3448 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003449 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3450 recentUnderruns > 0) {
3451 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3452 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003453 }
3454
3455 // This is similar to the state machine for normal tracks,
3456 // with a few modifications for fast tracks.
3457 bool isActive = true;
3458 switch (track->mState) {
3459 case TrackBase::STOPPING_1:
3460 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003461 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003462 track->mState = TrackBase::STOPPING_2;
3463 }
3464 break;
3465 case TrackBase::PAUSING:
3466 // ramp down is not yet implemented
3467 track->setPaused();
3468 break;
3469 case TrackBase::RESUMING:
3470 // ramp up is not yet implemented
3471 track->mState = TrackBase::ACTIVE;
3472 break;
3473 case TrackBase::ACTIVE:
3474 if (recentFull > 0 || recentPartial > 0) {
3475 // track has provided at least some frames recently: reset retry count
3476 track->mRetryCount = kMaxTrackRetries;
3477 }
3478 if (recentUnderruns == 0) {
3479 // no recent underruns: stay active
3480 break;
3481 }
3482 // there has recently been an underrun of some kind
3483 if (track->sharedBuffer() == 0) {
3484 // were any of the recent underruns "empty" (no frames available)?
3485 if (recentEmpty == 0) {
3486 // no, then ignore the partial underruns as they are allowed indefinitely
3487 break;
3488 }
3489 // there has recently been an "empty" underrun: decrement the retry counter
3490 if (--(track->mRetryCount) > 0) {
3491 break;
3492 }
3493 // indicate to client process that the track was disabled because of underrun;
3494 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003495 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003496 // remove from active list, but state remains ACTIVE [confusing but true]
3497 isActive = false;
3498 break;
3499 }
3500 // fall through
3501 case TrackBase::STOPPING_2:
3502 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003503 case TrackBase::STOPPED:
3504 case TrackBase::FLUSHED: // flush() while active
3505 // Check for presentation complete if track is inactive
3506 // We have consumed all the buffers of this track.
3507 // This would be incomplete if we auto-paused on underrun
3508 {
3509 size_t audioHALFrames =
3510 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3511 size_t framesWritten = mBytesWritten / mFrameSize;
3512 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3513 // track stays in active list until presentation is complete
3514 break;
3515 }
3516 }
3517 if (track->isStopping_2()) {
3518 track->mState = TrackBase::STOPPED;
3519 }
3520 if (track->isStopped()) {
3521 // Can't reset directly, as fast mixer is still polling this track
3522 // track->reset();
3523 // So instead mark this track as needing to be reset after push with ack
3524 resetMask |= 1 << i;
3525 }
3526 isActive = false;
3527 break;
3528 case TrackBase::IDLE:
3529 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003530 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003531 }
3532
3533 if (isActive) {
3534 // was it previously inactive?
3535 if (!(state->mTrackMask & (1 << j))) {
3536 ExtendedAudioBufferProvider *eabp = track;
3537 VolumeProvider *vp = track;
3538 fastTrack->mBufferProvider = eabp;
3539 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003540 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003541 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003542 fastTrack->mGeneration++;
3543 state->mTrackMask |= 1 << j;
3544 didModify = true;
3545 // no acknowledgement required for newly active tracks
3546 }
3547 // cache the combined master volume and stream type volume for fast mixer; this
3548 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003549 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003550 ++fastTracks;
3551 } else {
3552 // was it previously active?
3553 if (state->mTrackMask & (1 << j)) {
3554 fastTrack->mBufferProvider = NULL;
3555 fastTrack->mGeneration++;
3556 state->mTrackMask &= ~(1 << j);
3557 didModify = true;
3558 // If any fast tracks were removed, we must wait for acknowledgement
3559 // because we're about to decrement the last sp<> on those tracks.
3560 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3561 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003562 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003563 }
3564 tracksToRemove->add(track);
3565 // Avoids a misleading display in dumpsys
3566 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3567 }
3568 continue;
3569 }
3570
3571 { // local variable scope to avoid goto warning
3572
3573 audio_track_cblk_t* cblk = track->cblk();
3574
3575 // The first time a track is added we wait
3576 // for all its buffers to be filled before processing it
3577 int name = track->name();
3578 // make sure that we have enough frames to mix one full buffer.
3579 // enforce this condition only once to enable draining the buffer in case the client
3580 // app does not call stop() and relies on underrun to stop:
3581 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3582 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003583 size_t desiredFrames;
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003584 uint32_t sr = track->sampleRate();
3585 if (sr == mSampleRate) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003586 desiredFrames = mNormalFrameCount;
3587 } else {
Andy Hungc25b84a2015-01-14 19:04:10 -08003588 desiredFrames = sourceFramesNeeded(sr, mNormalFrameCount, mSampleRate);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003589 // add frames already consumed but not yet released by the resampler
Glenn Kasten2fc14732013-08-05 14:58:14 -07003590 // because mAudioTrackServerProxy->framesReady() will include these frames
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003591 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
Glenn Kasten74935e42013-12-19 08:56:45 -08003592#if 0
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003593 // the minimum track buffer size is normally twice the number of frames necessary
3594 // to fill one buffer and the resampler should not leave more than one buffer worth
3595 // of unreleased frames after each pass, but just in case...
3596 ALOG_ASSERT(desiredFrames <= cblk->frameCount_);
Glenn Kasten74935e42013-12-19 08:56:45 -08003597#endif
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003598 }
Eric Laurent81784c32012-11-19 14:55:58 -08003599 uint32_t minFrames = 1;
3600 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3601 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003602 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003603 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003604
3605 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003606 if (ATRACE_ENABLED()) {
3607 // I wish we had formatted trace names
3608 char traceName[16];
3609 strcpy(traceName, "nRdy");
3610 int name = track->name();
3611 if (AudioMixer::TRACK0 <= name &&
3612 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3613 name -= AudioMixer::TRACK0;
3614 traceName[4] = (name / 10) + '0';
3615 traceName[5] = (name % 10) + '0';
3616 } else {
3617 traceName[4] = '?';
3618 traceName[5] = '?';
3619 }
3620 traceName[6] = '\0';
3621 ATRACE_INT(traceName, framesReady);
3622 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003623 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003624 !track->isPaused() && !track->isTerminated())
3625 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003626 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003627
3628 mixedTracks++;
3629
Andy Hung69aed5f2014-02-25 17:24:40 -08003630 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3631 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003632 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003633 if (track->mainBuffer() != mSinkBuffer &&
3634 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003635 if (mEffectBufferEnabled) {
3636 mEffectBufferValid = true; // Later can set directly.
3637 }
Eric Laurent81784c32012-11-19 14:55:58 -08003638 chain = getEffectChain_l(track->sessionId());
3639 // Delegate volume control to effect in track effect chain if needed
3640 if (chain != 0) {
3641 tracksWithEffect++;
3642 } else {
3643 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3644 "session %d",
3645 name, track->sessionId());
3646 }
3647 }
3648
3649
3650 int param = AudioMixer::VOLUME;
3651 if (track->mFillingUpStatus == Track::FS_FILLED) {
3652 // no ramp for the first volume setting
3653 track->mFillingUpStatus = Track::FS_ACTIVE;
3654 if (track->mState == TrackBase::RESUMING) {
3655 track->mState = TrackBase::ACTIVE;
3656 param = AudioMixer::RAMP_VOLUME;
3657 }
3658 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003659 // FIXME should not make a decision based on mServer
3660 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003661 // If the track is stopped before the first frame was mixed,
3662 // do not apply ramp
3663 param = AudioMixer::RAMP_VOLUME;
3664 }
3665
3666 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003667 uint32_t vl, vr; // in U8.24 integer format
3668 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003669 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003670 vl = vr = 0;
3671 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003672 if (track->isPausing()) {
3673 track->setPaused();
3674 }
3675 } else {
3676
3677 // read original volumes with volume control
3678 float typeVolume = mStreamTypes[track->streamType()].volume;
3679 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003680 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003681 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003682 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3683 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003684 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003685 if (vlf > GAIN_FLOAT_UNITY) {
3686 ALOGV("Track left volume out of range: %.3g", vlf);
3687 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003688 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003689 if (vrf > GAIN_FLOAT_UNITY) {
3690 ALOGV("Track right volume out of range: %.3g", vrf);
3691 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003692 }
3693 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003694 vlf *= v;
3695 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003696 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003697 // then derive vl and vr as U8.24 versions for the effect chain
3698 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3699 vl = (uint32_t) (scaleto8_24 * vlf);
3700 vr = (uint32_t) (scaleto8_24 * vrf);
3701 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003702 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003703 // send level comes from shared memory and so may be corrupt
3704 if (sendLevel > MAX_GAIN_INT) {
3705 ALOGV("Track send level out of range: %04X", sendLevel);
3706 sendLevel = MAX_GAIN_INT;
3707 }
Andy Hung6be49402014-05-30 10:42:03 -07003708 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3709 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003710 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003711
Eric Laurent81784c32012-11-19 14:55:58 -08003712 // Delegate volume control to effect in track effect chain if needed
3713 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3714 // Do not ramp volume if volume is controlled by effect
3715 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003716 // Update remaining floating point volume levels
3717 vlf = (float)vl / (1 << 24);
3718 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003719 track->mHasVolumeController = true;
3720 } else {
3721 // force no volume ramp when volume controller was just disabled or removed
3722 // from effect chain to avoid volume spike
3723 if (track->mHasVolumeController) {
3724 param = AudioMixer::VOLUME;
3725 }
3726 track->mHasVolumeController = false;
3727 }
3728
Eric Laurent81784c32012-11-19 14:55:58 -08003729 // XXX: these things DON'T need to be done each time
3730 mAudioMixer->setBufferProvider(name, track);
3731 mAudioMixer->enable(name);
3732
Andy Hung6be49402014-05-30 10:42:03 -07003733 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3734 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3735 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003736 mAudioMixer->setParameter(
3737 name,
3738 AudioMixer::TRACK,
3739 AudioMixer::FORMAT, (void *)track->format());
3740 mAudioMixer->setParameter(
3741 name,
3742 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003743 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003744 mAudioMixer->setParameter(
3745 name,
3746 AudioMixer::TRACK,
3747 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003748 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003749 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003750 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003751 if (reqSampleRate == 0) {
3752 reqSampleRate = mSampleRate;
3753 } else if (reqSampleRate > maxSampleRate) {
3754 reqSampleRate = maxSampleRate;
3755 }
Eric Laurent81784c32012-11-19 14:55:58 -08003756 mAudioMixer->setParameter(
3757 name,
3758 AudioMixer::RESAMPLE,
3759 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003760 (void *)(uintptr_t)reqSampleRate);
Andy Hung69aed5f2014-02-25 17:24:40 -08003761 /*
3762 * Select the appropriate output buffer for the track.
3763 *
Andy Hung98ef9782014-03-04 14:46:50 -08003764 * Tracks with effects go into their own effects chain buffer
3765 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003766 *
3767 * Other tracks can use mMixerBuffer for higher precision
3768 * channel accumulation. If this buffer is enabled
3769 * (mMixerBufferEnabled true), then selected tracks will accumulate
3770 * into it.
3771 *
3772 */
3773 if (mMixerBufferEnabled
3774 && (track->mainBuffer() == mSinkBuffer
3775 || track->mainBuffer() == mMixerBuffer)) {
3776 mAudioMixer->setParameter(
3777 name,
3778 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003779 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003780 mAudioMixer->setParameter(
3781 name,
3782 AudioMixer::TRACK,
3783 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3784 // TODO: override track->mainBuffer()?
3785 mMixerBufferValid = true;
3786 } else {
3787 mAudioMixer->setParameter(
3788 name,
3789 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003790 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003791 mAudioMixer->setParameter(
3792 name,
3793 AudioMixer::TRACK,
3794 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3795 }
Eric Laurent81784c32012-11-19 14:55:58 -08003796 mAudioMixer->setParameter(
3797 name,
3798 AudioMixer::TRACK,
3799 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3800
3801 // reset retry count
3802 track->mRetryCount = kMaxTrackRetries;
3803
3804 // If one track is ready, set the mixer ready if:
3805 // - the mixer was not ready during previous round OR
3806 // - no other track is not ready
3807 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3808 mixerStatus != MIXER_TRACKS_ENABLED) {
3809 mixerStatus = MIXER_TRACKS_READY;
3810 }
3811 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003812 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003813 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003814 }
Eric Laurent81784c32012-11-19 14:55:58 -08003815 // clear effect chain input buffer if an active track underruns to avoid sending
3816 // previous audio buffer again to effects
3817 chain = getEffectChain_l(track->sessionId());
3818 if (chain != 0) {
3819 chain->clearInputBuffer();
3820 }
3821
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003822 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003823 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3824 track->isStopped() || track->isPaused()) {
3825 // We have consumed all the buffers of this track.
3826 // Remove it from the list of active tracks.
3827 // TODO: use actual buffer filling status instead of latency when available from
3828 // audio HAL
3829 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3830 size_t framesWritten = mBytesWritten / mFrameSize;
3831 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3832 if (track->isStopped()) {
3833 track->reset();
3834 }
3835 tracksToRemove->add(track);
3836 }
3837 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003838 // No buffers for this track. Give it a few chances to
3839 // fill a buffer, then remove it from active list.
3840 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003841 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003842 tracksToRemove->add(track);
3843 // indicate to client process that the track was disabled because of underrun;
3844 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003845 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003846 // If one track is not ready, mark the mixer also not ready if:
3847 // - the mixer was ready during previous round OR
3848 // - no other track is ready
3849 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3850 mixerStatus != MIXER_TRACKS_READY) {
3851 mixerStatus = MIXER_TRACKS_ENABLED;
3852 }
3853 }
3854 mAudioMixer->disable(name);
3855 }
3856
3857 } // local variable scope to avoid goto warning
3858track_is_ready: ;
3859
3860 }
3861
3862 // Push the new FastMixer state if necessary
3863 bool pauseAudioWatchdog = false;
3864 if (didModify) {
3865 state->mFastTracksGen++;
3866 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3867 if (kUseFastMixer == FastMixer_Dynamic &&
3868 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3869 state->mCommand = FastMixerState::COLD_IDLE;
3870 state->mColdFutexAddr = &mFastMixerFutex;
3871 state->mColdGen++;
3872 mFastMixerFutex = 0;
3873 if (kUseFastMixer == FastMixer_Dynamic) {
3874 mNormalSink = mOutputSink;
3875 }
3876 // If we go into cold idle, need to wait for acknowledgement
3877 // so that fast mixer stops doing I/O.
3878 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3879 pauseAudioWatchdog = true;
3880 }
Eric Laurent81784c32012-11-19 14:55:58 -08003881 }
3882 if (sq != NULL) {
3883 sq->end(didModify);
3884 sq->push(block);
3885 }
3886#ifdef AUDIO_WATCHDOG
3887 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3888 mAudioWatchdog->pause();
3889 }
3890#endif
3891
3892 // Now perform the deferred reset on fast tracks that have stopped
3893 while (resetMask != 0) {
3894 size_t i = __builtin_ctz(resetMask);
3895 ALOG_ASSERT(i < count);
3896 resetMask &= ~(1 << i);
3897 sp<Track> t = mActiveTracks[i].promote();
3898 if (t == 0) {
3899 continue;
3900 }
3901 Track* track = t.get();
3902 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3903 track->reset();
3904 }
3905
3906 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003907 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003908
Eric Laurent97d547d2014-09-02 14:45:53 -07003909 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3910 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003911 }
3912
3913 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003914 // as long as there are effects we should clear the effects buffer, to avoid
3915 // passing a non-clean buffer to the effect chain
3916 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003917 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003918 // sink or mix buffer must be cleared if all tracks are connected to an
3919 // effect chain as in this case the mixer will not write to the sink or mix buffer
3920 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003921 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3922 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003923 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003924 if (mMixerBufferValid) {
3925 memset(mMixerBuffer, 0, mMixerBufferSize);
3926 // TODO: In testing, mSinkBuffer below need not be cleared because
3927 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3928 // after mixing.
3929 //
3930 // To enforce this guarantee:
3931 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3932 // (mixedTracks == 0 && fastTracks > 0))
3933 // must imply MIXER_TRACKS_READY.
3934 // Later, we may clear buffers regardless, and skip much of this logic.
3935 }
Andy Hung98ef9782014-03-04 14:46:50 -08003936 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003937 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003938 }
3939
3940 // if any fast tracks, then status is ready
3941 mMixerStatusIgnoringFastTracks = mixerStatus;
3942 if (fastTracks > 0) {
3943 mixerStatus = MIXER_TRACKS_READY;
3944 }
3945 return mixerStatus;
3946}
3947
3948// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003949int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3950 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003951{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003952 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003953}
3954
3955// deleteTrackName_l() must be called with ThreadBase::mLock held
3956void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3957{
3958 ALOGV("remove track (%d) and delete from mixer", name);
3959 mAudioMixer->deleteTrackName(name);
3960}
3961
Eric Laurent10351942014-05-08 18:49:52 -07003962// checkForNewParameter_l() must be called with ThreadBase::mLock held
3963bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3964 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003965{
Eric Laurent81784c32012-11-19 14:55:58 -08003966 bool reconfig = false;
3967
Eric Laurent10351942014-05-08 18:49:52 -07003968 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003969
Eric Laurent10351942014-05-08 18:49:52 -07003970 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3971 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003972 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003973 FastMixerStateQueue *sq = mFastMixer->sq();
3974 FastMixerState *state = sq->begin();
3975 if (!(state->mCommand & FastMixerState::IDLE)) {
3976 previousCommand = state->mCommand;
3977 state->mCommand = FastMixerState::HOT_IDLE;
3978 sq->end();
3979 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3980 } else {
3981 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003982 }
Eric Laurent10351942014-05-08 18:49:52 -07003983 }
Eric Laurent81784c32012-11-19 14:55:58 -08003984
Eric Laurent10351942014-05-08 18:49:52 -07003985 AudioParameter param = AudioParameter(keyValuePair);
3986 int value;
3987 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3988 reconfig = true;
3989 }
3990 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003991 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07003992 status = BAD_VALUE;
3993 } else {
3994 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08003995 reconfig = true;
3996 }
Eric Laurent10351942014-05-08 18:49:52 -07003997 }
3998 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07003999 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004000 status = BAD_VALUE;
4001 } else {
4002 // no need to save value, since it's constant
4003 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004004 }
Eric Laurent10351942014-05-08 18:49:52 -07004005 }
4006 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4007 // do not accept frame count changes if tracks are open as the track buffer
4008 // size depends on frame count and correct behavior would not be guaranteed
4009 // if frame count is changed after track creation
4010 if (!mTracks.isEmpty()) {
4011 status = INVALID_OPERATION;
4012 } else {
4013 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004014 }
Eric Laurent10351942014-05-08 18:49:52 -07004015 }
4016 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004017#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004018 // when changing the audio output device, call addBatteryData to notify
4019 // the change
4020 if (mOutDevice != value) {
4021 uint32_t params = 0;
4022 // check whether speaker is on
4023 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4024 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004025 }
Eric Laurent10351942014-05-08 18:49:52 -07004026
4027 audio_devices_t deviceWithoutSpeaker
4028 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4029 // check if any other device (except speaker) is on
4030 if (value & deviceWithoutSpeaker ) {
4031 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4032 }
4033
4034 if (params != 0) {
4035 addBatteryData(params);
4036 }
4037 }
Eric Laurent81784c32012-11-19 14:55:58 -08004038#endif
4039
Eric Laurent10351942014-05-08 18:49:52 -07004040 // forward device change to effects that have requested to be
4041 // aware of attached audio device.
4042 if (value != AUDIO_DEVICE_NONE) {
4043 mOutDevice = value;
4044 for (size_t i = 0; i < mEffectChains.size(); i++) {
4045 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004046 }
4047 }
Eric Laurent10351942014-05-08 18:49:52 -07004048 }
Eric Laurent81784c32012-11-19 14:55:58 -08004049
Eric Laurent10351942014-05-08 18:49:52 -07004050 if (status == NO_ERROR) {
4051 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4052 keyValuePair.string());
4053 if (!mStandby && status == INVALID_OPERATION) {
4054 mOutput->stream->common.standby(&mOutput->stream->common);
4055 mStandby = true;
4056 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004057 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004058 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004059 }
Eric Laurent10351942014-05-08 18:49:52 -07004060 if (status == NO_ERROR && reconfig) {
4061 readOutputParameters_l();
4062 delete mAudioMixer;
4063 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4064 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004065 int name = getTrackName_l(mTracks[i]->mChannelMask,
4066 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004067 if (name < 0) {
4068 break;
4069 }
4070 mTracks[i]->mName = name;
4071 }
4072 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4073 }
Eric Laurent81784c32012-11-19 14:55:58 -08004074 }
4075
4076 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004077 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004078 FastMixerStateQueue *sq = mFastMixer->sq();
4079 FastMixerState *state = sq->begin();
4080 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4081 state->mCommand = previousCommand;
4082 sq->end();
4083 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4084 }
4085
4086 return reconfig;
4087}
4088
4089
4090void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4091{
4092 const size_t SIZE = 256;
4093 char buffer[SIZE];
4094 String8 result;
4095
4096 PlaybackThread::dumpInternals(fd, args);
4097
Elliott Hughes87cebad2014-05-22 10:14:43 -07004098 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004099
4100 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004101 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004102 copy.dump(fd);
4103
4104#ifdef STATE_QUEUE_DUMP
4105 // Similar for state queue
4106 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4107 observerCopy.dump(fd);
4108 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4109 mutatorCopy.dump(fd);
4110#endif
4111
Glenn Kasten46909e72013-02-26 09:20:22 -08004112#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004113 // Write the tee output to a .wav file
4114 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004115#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004116
4117#ifdef AUDIO_WATCHDOG
4118 if (mAudioWatchdog != 0) {
4119 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4120 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4121 wdCopy.dump(fd);
4122 }
4123#endif
4124}
4125
4126uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4127{
4128 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4129}
4130
4131uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4132{
4133 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4134}
4135
4136void AudioFlinger::MixerThread::cacheParameters_l()
4137{
4138 PlaybackThread::cacheParameters_l();
4139
4140 // FIXME: Relaxed timing because of a certain device that can't meet latency
4141 // Should be reduced to 2x after the vendor fixes the driver issue
4142 // increase threshold again due to low power audio mode. The way this warning
4143 // threshold is calculated and its usefulness should be reconsidered anyway.
4144 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4145}
4146
4147// ----------------------------------------------------------------------------
4148
4149AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4150 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4151 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4152 // mLeftVolFloat, mRightVolFloat
4153{
4154}
4155
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4157 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4158 ThreadBase::type_t type)
4159 : PlaybackThread(audioFlinger, output, id, device, type)
4160 // mLeftVolFloat, mRightVolFloat
4161{
4162}
4163
Eric Laurent81784c32012-11-19 14:55:58 -08004164AudioFlinger::DirectOutputThread::~DirectOutputThread()
4165{
4166}
4167
Eric Laurentbfb1b832013-01-07 09:53:42 -08004168void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4169{
4170 audio_track_cblk_t* cblk = track->cblk();
4171 float left, right;
4172
4173 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4174 left = right = 0;
4175 } else {
4176 float typeVolume = mStreamTypes[track->streamType()].volume;
4177 float v = mMasterVolume * typeVolume;
4178 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004179 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4180 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4181 if (left > GAIN_FLOAT_UNITY) {
4182 left = GAIN_FLOAT_UNITY;
4183 }
4184 left *= v;
4185 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4186 if (right > GAIN_FLOAT_UNITY) {
4187 right = GAIN_FLOAT_UNITY;
4188 }
4189 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004190 }
4191
4192 if (lastTrack) {
4193 if (left != mLeftVolFloat || right != mRightVolFloat) {
4194 mLeftVolFloat = left;
4195 mRightVolFloat = right;
4196
4197 // Convert volumes from float to 8.24
4198 uint32_t vl = (uint32_t)(left * (1 << 24));
4199 uint32_t vr = (uint32_t)(right * (1 << 24));
4200
4201 // Delegate volume control to effect in track effect chain if needed
4202 // only one effect chain can be present on DirectOutputThread, so if
4203 // there is one, the track is connected to it
4204 if (!mEffectChains.isEmpty()) {
4205 mEffectChains[0]->setVolume_l(&vl, &vr);
4206 left = (float)vl / (1 << 24);
4207 right = (float)vr / (1 << 24);
4208 }
4209 if (mOutput->stream->set_volume) {
4210 mOutput->stream->set_volume(mOutput->stream, left, right);
4211 }
4212 }
4213 }
4214}
4215
4216
Eric Laurent81784c32012-11-19 14:55:58 -08004217AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4218 Vector< sp<Track> > *tracksToRemove
4219)
4220{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004221 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004222 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004223 bool doHwPause = false;
4224 bool doHwResume = false;
4225 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004226
4227 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004228 for (size_t i = 0; i < count; i++) {
4229 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004230 // The track died recently
4231 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004232 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004233 }
4234
4235 Track* const track = t.get();
4236 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004237 // Only consider last track started for volume and mixer state control.
4238 // In theory an older track could underrun and restart after the new one starts
4239 // but as we only care about the transition phase between two tracks on a
4240 // direct output, it is not a problem to ignore the underrun case.
4241 sp<Track> l = mLatestActiveTrack.promote();
4242 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004243
Eric Laurentd1f69b02014-12-15 14:33:13 -08004244 if (mHwSupportsPause && track->isPausing()) {
4245 track->setPaused();
4246 if (last && !mHwPaused) {
4247 doHwPause = true;
4248 mHwPaused = true;
4249 }
4250 tracksToRemove->add(track);
4251 } else if (track->isFlushPending()) {
4252 track->flushAck();
4253 if (last) {
4254 flushPending = true;
4255 }
4256 } else if (mHwSupportsPause && track->isResumePending()){
4257 track->resumeAck();
4258 if (last) {
4259 if (mHwPaused) {
4260 doHwResume = true;
4261 mHwPaused = false;
4262 }
4263 }
4264 }
4265
Eric Laurent81784c32012-11-19 14:55:58 -08004266 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004267 // for all its buffers to be filled before processing it.
4268 // Allow draining the buffer in case the client
4269 // app does not call stop() and relies on underrun to stop:
4270 // hence the test on (track->mRetryCount > 1).
4271 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004272 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004273 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4274 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004275 minFrames = mNormalFrameCount;
4276 } else {
4277 minFrames = 1;
4278 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004279
Eric Laurentab5cdba2014-06-09 17:22:27 -07004280 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4281 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004282 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004283 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004284
4285 if (track->mFillingUpStatus == Track::FS_FILLED) {
4286 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004287 // make sure processVolume_l() will apply new volume even if 0
4288 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004289 if (!mHwSupportsPause) {
4290 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004291 }
4292 }
4293
4294 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004295 processVolume_l(track, last);
4296 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004297 // reset retry count
4298 track->mRetryCount = kMaxTrackRetriesDirect;
4299 mActiveTrack = t;
4300 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004301 if (usesHwAvSync() && mHwPaused) {
4302 doHwResume = true;
4303 mHwPaused = false;
4304 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004305 }
Eric Laurent81784c32012-11-19 14:55:58 -08004306 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004307 // clear effect chain input buffer if the last active track started underruns
4308 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004309 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004310 mEffectChains[0]->clearInputBuffer();
4311 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004312 if (track->isStopping_1()) {
4313 track->mState = TrackBase::STOPPING_2;
4314 }
4315 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4316 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004317 // We have consumed all the buffers of this track.
4318 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004319 size_t audioHALFrames;
4320 if (audio_is_linear_pcm(mFormat)) {
4321 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4322 } else {
4323 audioHALFrames = 0;
4324 }
4325
Eric Laurent81784c32012-11-19 14:55:58 -08004326 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004327 if (mStandby || !last ||
4328 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004329 if (track->isStopping_2()) {
4330 track->mState = TrackBase::STOPPED;
4331 }
Eric Laurent81784c32012-11-19 14:55:58 -08004332 if (track->isStopped()) {
4333 track->reset();
4334 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004335 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004336 }
4337 } else {
4338 // No buffers for this track. Give it a few chances to
4339 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004340 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004341 if (--(track->mRetryCount) <= 0) {
4342 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004343 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004344 // indicate to client process that the track was disabled because of underrun;
4345 // it will then automatically call start() when data is available
4346 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004347 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004348 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004349 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4350 doHwPause = true;
4351 mHwPaused = true;
4352 }
Eric Laurent81784c32012-11-19 14:55:58 -08004353 }
4354 }
4355 }
4356 }
4357
Eric Laurentd1f69b02014-12-15 14:33:13 -08004358 // if an active track did not command a flush, check for pending flush on stopped tracks
4359 if (!flushPending) {
4360 for (size_t i = 0; i < mTracks.size(); i++) {
4361 if (mTracks[i]->isFlushPending()) {
4362 mTracks[i]->flushAck();
4363 flushPending = true;
4364 }
4365 }
4366 }
4367
4368 // make sure the pause/flush/resume sequence is executed in the right order.
4369 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4370 // before flush and then resume HW. This can happen in case of pause/flush/resume
4371 // if resume is received before pause is executed.
4372 if (mHwSupportsPause && !mStandby &&
4373 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4374 mOutput->stream->pause(mOutput->stream);
4375 }
4376 if (flushPending) {
4377 flushHw_l();
4378 }
4379 if (mHwSupportsPause && !mStandby && doHwResume) {
4380 mOutput->stream->resume(mOutput->stream);
4381 }
Eric Laurent81784c32012-11-19 14:55:58 -08004382 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004383 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004384
4385 return mixerStatus;
4386}
4387
4388void AudioFlinger::DirectOutputThread::threadLoop_mix()
4389{
Eric Laurent81784c32012-11-19 14:55:58 -08004390 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004391 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004392 // output audio to hardware
4393 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004394 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004395 buffer.frameCount = frameCount;
4396 mActiveTrack->getNextBuffer(&buffer);
Glenn Kastenfa319e62013-07-29 17:17:38 -07004397 if (buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004398 memset(curBuf, 0, frameCount * mFrameSize);
4399 break;
4400 }
4401 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4402 frameCount -= buffer.frameCount;
4403 curBuf += buffer.frameCount * mFrameSize;
4404 mActiveTrack->releaseBuffer(&buffer);
4405 }
Andy Hung2098f272014-02-27 14:00:06 -08004406 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004407 sleepTime = 0;
4408 standbyTime = systemTime() + standbyDelay;
4409 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004410}
4411
4412void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4413{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004414 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004415 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004416 sleepTime = idleSleepTime;
4417 return;
4418 }
Eric Laurent81784c32012-11-19 14:55:58 -08004419 if (sleepTime == 0) {
4420 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4421 sleepTime = activeSleepTime;
4422 } else {
4423 sleepTime = idleSleepTime;
4424 }
4425 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004426 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004427 sleepTime = 0;
4428 }
4429}
4430
Eric Laurentd1f69b02014-12-15 14:33:13 -08004431void AudioFlinger::DirectOutputThread::threadLoop_exit()
4432{
4433 {
4434 Mutex::Autolock _l(mLock);
4435 bool flushPending = false;
4436 for (size_t i = 0; i < mTracks.size(); i++) {
4437 if (mTracks[i]->isFlushPending()) {
4438 mTracks[i]->flushAck();
4439 flushPending = true;
4440 }
4441 }
4442 if (flushPending) {
4443 flushHw_l();
4444 }
4445 }
4446 PlaybackThread::threadLoop_exit();
4447}
4448
4449// must be called with thread mutex locked
4450bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4451{
4452 bool trackPaused = false;
4453
4454 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4455 // after a timeout and we will enter standby then.
4456 if (mTracks.size() > 0) {
4457 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
4458 }
4459
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004460 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004461}
4462
Eric Laurent81784c32012-11-19 14:55:58 -08004463// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004464int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004465 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004466{
4467 return 0;
4468}
4469
4470// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004471void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004472{
4473}
4474
Eric Laurent10351942014-05-08 18:49:52 -07004475// checkForNewParameter_l() must be called with ThreadBase::mLock held
4476bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4477 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004478{
4479 bool reconfig = false;
4480
Eric Laurent10351942014-05-08 18:49:52 -07004481 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004482
Eric Laurent10351942014-05-08 18:49:52 -07004483 AudioParameter param = AudioParameter(keyValuePair);
4484 int value;
4485 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4486 // forward device change to effects that have requested to be
4487 // aware of attached audio device.
4488 if (value != AUDIO_DEVICE_NONE) {
4489 mOutDevice = value;
4490 for (size_t i = 0; i < mEffectChains.size(); i++) {
4491 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004492 }
4493 }
Eric Laurent81784c32012-11-19 14:55:58 -08004494 }
Eric Laurent10351942014-05-08 18:49:52 -07004495 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4496 // do not accept frame count changes if tracks are open as the track buffer
4497 // size depends on frame count and correct behavior would not be garantied
4498 // if frame count is changed after track creation
4499 if (!mTracks.isEmpty()) {
4500 status = INVALID_OPERATION;
4501 } else {
4502 reconfig = true;
4503 }
4504 }
4505 if (status == NO_ERROR) {
4506 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4507 keyValuePair.string());
4508 if (!mStandby && status == INVALID_OPERATION) {
4509 mOutput->stream->common.standby(&mOutput->stream->common);
4510 mStandby = true;
4511 mBytesWritten = 0;
4512 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4513 keyValuePair.string());
4514 }
4515 if (status == NO_ERROR && reconfig) {
4516 readOutputParameters_l();
4517 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4518 }
4519 }
4520
Eric Laurent81784c32012-11-19 14:55:58 -08004521 return reconfig;
4522}
4523
4524uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4525{
4526 uint32_t time;
4527 if (audio_is_linear_pcm(mFormat)) {
4528 time = PlaybackThread::activeSleepTimeUs();
4529 } else {
4530 time = 10000;
4531 }
4532 return time;
4533}
4534
4535uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4536{
4537 uint32_t time;
4538 if (audio_is_linear_pcm(mFormat)) {
4539 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4540 } else {
4541 time = 10000;
4542 }
4543 return time;
4544}
4545
4546uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4547{
4548 uint32_t time;
4549 if (audio_is_linear_pcm(mFormat)) {
4550 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4551 } else {
4552 time = 10000;
4553 }
4554 return time;
4555}
4556
4557void AudioFlinger::DirectOutputThread::cacheParameters_l()
4558{
4559 PlaybackThread::cacheParameters_l();
4560
4561 // use shorter standby delay as on normal output to release
4562 // hardware resources as soon as possible
Eric Laurent972a1732013-09-04 09:42:59 -07004563 if (audio_is_linear_pcm(mFormat)) {
4564 standbyDelay = microseconds(activeSleepTime*2);
4565 } else {
4566 standbyDelay = kOffloadStandbyDelayNs;
4567 }
Eric Laurent81784c32012-11-19 14:55:58 -08004568}
4569
Eric Laurente659ef42014-09-29 13:06:46 -07004570void AudioFlinger::DirectOutputThread::flushHw_l()
4571{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004572 if (mOutput->stream->flush != NULL) {
Eric Laurente659ef42014-09-29 13:06:46 -07004573 mOutput->stream->flush(mOutput->stream);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004574 }
4575 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004576}
4577
Eric Laurent81784c32012-11-19 14:55:58 -08004578// ----------------------------------------------------------------------------
4579
Eric Laurentbfb1b832013-01-07 09:53:42 -08004580AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004581 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004582 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004583 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004584 mWriteAckSequence(0),
4585 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004586{
4587}
4588
4589AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4590{
4591}
4592
4593void AudioFlinger::AsyncCallbackThread::onFirstRef()
4594{
4595 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4596}
4597
4598bool AudioFlinger::AsyncCallbackThread::threadLoop()
4599{
4600 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004601 uint32_t writeAckSequence;
4602 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004603
4604 {
4605 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004606 while (!((mWriteAckSequence & 1) ||
4607 (mDrainSequence & 1) ||
4608 exitPending())) {
4609 mWaitWorkCV.wait(mLock);
4610 }
4611
Eric Laurentbfb1b832013-01-07 09:53:42 -08004612 if (exitPending()) {
4613 break;
4614 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004615 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4616 mWriteAckSequence, mDrainSequence);
4617 writeAckSequence = mWriteAckSequence;
4618 mWriteAckSequence &= ~1;
4619 drainSequence = mDrainSequence;
4620 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004621 }
4622 {
Eric Laurent4de95592013-09-26 15:28:21 -07004623 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4624 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004625 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004626 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004627 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004628 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004629 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004630 }
4631 }
4632 }
4633 }
4634 return false;
4635}
4636
4637void AudioFlinger::AsyncCallbackThread::exit()
4638{
4639 ALOGV("AsyncCallbackThread::exit");
4640 Mutex::Autolock _l(mLock);
4641 requestExit();
4642 mWaitWorkCV.broadcast();
4643}
4644
Eric Laurent3b4529e2013-09-05 18:09:19 -07004645void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004646{
4647 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004648 // bit 0 is cleared
4649 mWriteAckSequence = sequence << 1;
4650}
4651
4652void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4653{
4654 Mutex::Autolock _l(mLock);
4655 // ignore unexpected callbacks
4656 if (mWriteAckSequence & 2) {
4657 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004658 mWaitWorkCV.signal();
4659 }
4660}
4661
Eric Laurent3b4529e2013-09-05 18:09:19 -07004662void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004663{
4664 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004665 // bit 0 is cleared
4666 mDrainSequence = sequence << 1;
4667}
4668
4669void AudioFlinger::AsyncCallbackThread::resetDraining()
4670{
4671 Mutex::Autolock _l(mLock);
4672 // ignore unexpected callbacks
4673 if (mDrainSequence & 2) {
4674 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004675 mWaitWorkCV.signal();
4676 }
4677}
4678
4679
4680// ----------------------------------------------------------------------------
4681AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4682 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4683 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004684 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004685{
Eric Laurentfd477972013-10-25 18:10:40 -07004686 //FIXME: mStandby should be set to true by ThreadBase constructor
4687 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004688}
4689
Eric Laurentbfb1b832013-01-07 09:53:42 -08004690void AudioFlinger::OffloadThread::threadLoop_exit()
4691{
4692 if (mFlushPending || mHwPaused) {
4693 // If a flush is pending or track was paused, just discard buffered data
4694 flushHw_l();
4695 } else {
4696 mMixerStatus = MIXER_DRAIN_ALL;
4697 threadLoop_drain();
4698 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004699 if (mUseAsyncWrite) {
4700 ALOG_ASSERT(mCallbackThread != 0);
4701 mCallbackThread->exit();
4702 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004703 PlaybackThread::threadLoop_exit();
4704}
4705
4706AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4707 Vector< sp<Track> > *tracksToRemove
4708)
4709{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004710 size_t count = mActiveTracks.size();
4711
4712 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004713 bool doHwPause = false;
4714 bool doHwResume = false;
4715
Eric Laurentede6c3b2013-09-19 14:37:46 -07004716 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4717
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718 // find out which tracks need to be processed
4719 for (size_t i = 0; i < count; i++) {
4720 sp<Track> t = mActiveTracks[i].promote();
4721 // The track died recently
4722 if (t == 0) {
4723 continue;
4724 }
4725 Track* const track = t.get();
4726 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004727 // Only consider last track started for volume and mixer state control.
4728 // In theory an older track could underrun and restart after the new one starts
4729 // but as we only care about the transition phase between two tracks on a
4730 // direct output, it is not a problem to ignore the underrun case.
4731 sp<Track> l = mLatestActiveTrack.promote();
4732 bool last = l.get() == track;
4733
Haynes Mathew George7844f672014-01-15 12:32:55 -08004734 if (track->isInvalid()) {
4735 ALOGW("An invalidated track shouldn't be in active list");
4736 tracksToRemove->add(track);
4737 continue;
4738 }
4739
4740 if (track->mState == TrackBase::IDLE) {
4741 ALOGW("An idle track shouldn't be in active list");
4742 continue;
4743 }
4744
Eric Laurentbfb1b832013-01-07 09:53:42 -08004745 if (track->isPausing()) {
4746 track->setPaused();
4747 if (last) {
4748 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004749 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004750 mHwPaused = true;
4751 }
4752 // If we were part way through writing the mixbuffer to
4753 // the HAL we must save this until we resume
4754 // BUG - this will be wrong if a different track is made active,
4755 // in that case we want to discard the pending data in the
4756 // mixbuffer and tell the client to present it again when the
4757 // track is resumed
4758 mPausedWriteLength = mCurrentWriteLength;
4759 mPausedBytesRemaining = mBytesRemaining;
4760 mBytesRemaining = 0; // stop writing
4761 }
4762 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004763 } else if (track->isFlushPending()) {
4764 track->flushAck();
4765 if (last) {
4766 mFlushPending = true;
4767 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004768 } else if (track->isResumePending()){
4769 track->resumeAck();
4770 if (last) {
4771 if (mPausedBytesRemaining) {
4772 // Need to continue write that was interrupted
4773 mCurrentWriteLength = mPausedWriteLength;
4774 mBytesRemaining = mPausedBytesRemaining;
4775 mPausedBytesRemaining = 0;
4776 }
4777 if (mHwPaused) {
4778 doHwResume = true;
4779 mHwPaused = false;
4780 // threadLoop_mix() will handle the case that we need to
4781 // resume an interrupted write
4782 }
4783 // enable write to audio HAL
4784 sleepTime = 0;
4785
4786 // Do not handle new data in this iteration even if track->framesReady()
4787 mixerStatus = MIXER_TRACKS_ENABLED;
4788 }
4789 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004790 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004791 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004792 if (track->mFillingUpStatus == Track::FS_FILLED) {
4793 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004794 // make sure processVolume_l() will apply new volume even if 0
4795 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004796 }
4797
4798 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004799 sp<Track> previousTrack = mPreviousTrack.promote();
4800 if (previousTrack != 0) {
4801 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004802 // Flush any data still being written from last track
4803 mBytesRemaining = 0;
4804 if (mPausedBytesRemaining) {
4805 // Last track was paused so we also need to flush saved
4806 // mixbuffer state and invalidate track so that it will
4807 // re-submit that unwritten data when it is next resumed
4808 mPausedBytesRemaining = 0;
4809 // Invalidate is a bit drastic - would be more efficient
4810 // to have a flag to tell client that some of the
4811 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004812 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004813 }
4814 // flush data already sent to the DSP if changing audio session as audio
4815 // comes from a different source. Also invalidate previous track to force a
4816 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004817 if (previousTrack->sessionId() != track->sessionId()) {
4818 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004819 }
4820 }
4821 }
4822 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004823 // reset retry count
4824 track->mRetryCount = kMaxTrackRetriesOffload;
4825 mActiveTrack = t;
4826 mixerStatus = MIXER_TRACKS_READY;
4827 }
4828 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004829 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004830 if (track->isStopping_1()) {
4831 // Hardware buffer can hold a large amount of audio so we must
4832 // wait for all current track's data to drain before we say
4833 // that the track is stopped.
4834 if (mBytesRemaining == 0) {
4835 // Only start draining when all data in mixbuffer
4836 // has been written
4837 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4838 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004839 // do not drain if no data was ever sent to HAL (mStandby == true)
4840 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004841 // do not modify drain sequence if we are already draining. This happens
4842 // when resuming from pause after drain.
4843 if ((mDrainSequence & 1) == 0) {
4844 sleepTime = 0;
4845 standbyTime = systemTime() + standbyDelay;
4846 mixerStatus = MIXER_DRAIN_TRACK;
4847 mDrainSequence += 2;
4848 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849 if (mHwPaused) {
4850 // It is possible to move from PAUSED to STOPPING_1 without
4851 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004852 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004853 mHwPaused = false;
4854 }
4855 }
4856 }
4857 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004858 // Drain has completed or we are in standby, signal presentation complete
4859 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004860 track->mState = TrackBase::STOPPED;
4861 size_t audioHALFrames =
4862 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4863 size_t framesWritten =
Eric Laurent665470b2014-07-03 16:37:08 -07004864 mBytesWritten / audio_stream_out_frame_size(mOutput->stream);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004865 track->presentationComplete(framesWritten, audioHALFrames);
4866 track->reset();
4867 tracksToRemove->add(track);
4868 }
4869 } else {
4870 // No buffers for this track. Give it a few chances to
4871 // fill a buffer, then remove it from active list.
4872 if (--(track->mRetryCount) <= 0) {
4873 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4874 track->name());
4875 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004876 // indicate to client process that the track was disabled because of underrun;
4877 // it will then automatically call start() when data is available
4878 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004879 } else if (last){
4880 mixerStatus = MIXER_TRACKS_ENABLED;
4881 }
4882 }
4883 }
4884 // compute volume for this track
4885 processVolume_l(track, last);
4886 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004887
Eric Laurentea0fade2013-10-04 16:23:48 -07004888 // make sure the pause/flush/resume sequence is executed in the right order.
4889 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4890 // before flush and then resume HW. This can happen in case of pause/flush/resume
4891 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004892 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004893 mOutput->stream->pause(mOutput->stream);
4894 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004895 if (mFlushPending) {
4896 flushHw_l();
4897 mFlushPending = false;
4898 }
Eric Laurentfd477972013-10-25 18:10:40 -07004899 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004900 mOutput->stream->resume(mOutput->stream);
4901 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004902
Eric Laurentbfb1b832013-01-07 09:53:42 -08004903 // remove all the tracks that need to be...
4904 removeTracks_l(*tracksToRemove);
4905
4906 return mixerStatus;
4907}
4908
Eric Laurentbfb1b832013-01-07 09:53:42 -08004909// must be called with thread mutex locked
4910bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4911{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004912 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4913 mWriteAckSequence, mDrainSequence);
4914 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004915 return true;
4916 }
4917 return false;
4918}
4919
Eric Laurentbfb1b832013-01-07 09:53:42 -08004920bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4921{
4922 Mutex::Autolock _l(mLock);
4923 return waitingAsyncCallback_l();
4924}
4925
4926void AudioFlinger::OffloadThread::flushHw_l()
4927{
Eric Laurente659ef42014-09-29 13:06:46 -07004928 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004929 // Flush anything still waiting in the mixbuffer
4930 mCurrentWriteLength = 0;
4931 mBytesRemaining = 0;
4932 mPausedWriteLength = 0;
4933 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004934
Eric Laurentbfb1b832013-01-07 09:53:42 -08004935 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004936 // discard any pending drain or write ack by incrementing sequence
4937 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4938 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004939 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004940 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4941 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004942 }
4943}
4944
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004945void AudioFlinger::OffloadThread::onAddNewTrack_l()
4946{
4947 sp<Track> previousTrack = mPreviousTrack.promote();
4948 sp<Track> latestTrack = mLatestActiveTrack.promote();
4949
4950 if (previousTrack != 0 && latestTrack != 0 &&
4951 (previousTrack->sessionId() != latestTrack->sessionId())) {
4952 mFlushPending = true;
4953 }
4954 PlaybackThread::onAddNewTrack_l();
4955}
4956
Eric Laurentbfb1b832013-01-07 09:53:42 -08004957// ----------------------------------------------------------------------------
4958
Eric Laurent81784c32012-11-19 14:55:58 -08004959AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4960 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4961 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4962 DUPLICATING),
4963 mWaitTimeMs(UINT_MAX)
4964{
4965 addOutputTrack(mainThread);
4966}
4967
4968AudioFlinger::DuplicatingThread::~DuplicatingThread()
4969{
4970 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4971 mOutputTracks[i]->destroy();
4972 }
4973}
4974
4975void AudioFlinger::DuplicatingThread::threadLoop_mix()
4976{
4977 // mix buffers...
4978 if (outputsReady(outputTracks)) {
4979 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4980 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08004981 if (mMixerBufferValid) {
4982 memset(mMixerBuffer, 0, mMixerBufferSize);
4983 } else {
4984 memset(mSinkBuffer, 0, mSinkBufferSize);
4985 }
Eric Laurent81784c32012-11-19 14:55:58 -08004986 }
4987 sleepTime = 0;
4988 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08004989 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004990 standbyTime = systemTime() + standbyDelay;
4991}
4992
4993void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4994{
4995 if (sleepTime == 0) {
4996 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4997 sleepTime = activeSleepTime;
4998 } else {
4999 sleepTime = idleSleepTime;
5000 }
5001 } else if (mBytesWritten != 0) {
5002 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5003 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005004 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005005 } else {
5006 // flush remaining overflow buffers in output tracks
5007 writeFrames = 0;
5008 }
5009 sleepTime = 0;
5010 }
5011}
5012
Eric Laurentbfb1b832013-01-07 09:53:42 -08005013ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005014{
5015 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005016 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005017 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005018 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005019 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005020}
5021
5022void AudioFlinger::DuplicatingThread::threadLoop_standby()
5023{
5024 // DuplicatingThread implements standby by stopping all tracks
5025 for (size_t i = 0; i < outputTracks.size(); i++) {
5026 outputTracks[i]->stop();
5027 }
5028}
5029
5030void AudioFlinger::DuplicatingThread::saveOutputTracks()
5031{
5032 outputTracks = mOutputTracks;
5033}
5034
5035void AudioFlinger::DuplicatingThread::clearOutputTracks()
5036{
5037 outputTracks.clear();
5038}
5039
5040void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5041{
5042 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005043 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5044 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5045 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5046 const size_t frameCount =
5047 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5048 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5049 // from different OutputTracks and their associated MixerThreads (e.g. one may
5050 // nearly empty and the other may be dropping data).
5051
5052 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005053 this,
5054 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005055 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005056 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005057 frameCount,
5058 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005059 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005060 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005061 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005062 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005063 updateWaitTime_l();
5064 }
5065}
5066
5067void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5068{
5069 Mutex::Autolock _l(mLock);
5070 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5071 if (mOutputTracks[i]->thread() == thread) {
5072 mOutputTracks[i]->destroy();
5073 mOutputTracks.removeAt(i);
5074 updateWaitTime_l();
5075 return;
5076 }
5077 }
5078 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5079}
5080
5081// caller must hold mLock
5082void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5083{
5084 mWaitTimeMs = UINT_MAX;
5085 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5086 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5087 if (strong != 0) {
5088 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5089 if (waitTimeMs < mWaitTimeMs) {
5090 mWaitTimeMs = waitTimeMs;
5091 }
5092 }
5093 }
5094}
5095
5096
5097bool AudioFlinger::DuplicatingThread::outputsReady(
5098 const SortedVector< sp<OutputTrack> > &outputTracks)
5099{
5100 for (size_t i = 0; i < outputTracks.size(); i++) {
5101 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5102 if (thread == 0) {
5103 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5104 outputTracks[i].get());
5105 return false;
5106 }
5107 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5108 // see note at standby() declaration
5109 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5110 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5111 thread.get());
5112 return false;
5113 }
5114 }
5115 return true;
5116}
5117
5118uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5119{
5120 return (mWaitTimeMs * 1000) / 2;
5121}
5122
5123void AudioFlinger::DuplicatingThread::cacheParameters_l()
5124{
5125 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5126 updateWaitTime_l();
5127
5128 MixerThread::cacheParameters_l();
5129}
5130
5131// ----------------------------------------------------------------------------
5132// Record
5133// ----------------------------------------------------------------------------
5134
5135AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5136 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005137 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005138 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005139 audio_devices_t inDevice
5140#ifdef TEE_SINK
5141 , const sp<NBAIO_Sink>& teeSink
5142#endif
5143 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005144 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005145 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005146 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005147 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005148#ifdef TEE_SINK
5149 , mTeeSink(teeSink)
5150#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005151 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5152 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005153 // mFastCapture below
5154 , mFastCaptureFutex(0)
5155 // mInputSource
5156 // mPipeSink
5157 // mPipeSource
5158 , mPipeFramesP2(0)
5159 // mPipeMemory
5160 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005161 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005162{
5163 snprintf(mName, kNameLength, "AudioIn_%X", id);
Glenn Kasten481fb672013-09-30 14:39:28 -07005164 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mName);
Eric Laurent81784c32012-11-19 14:55:58 -08005165
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005166 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005167
5168 // create an NBAIO source for the HAL input stream, and negotiate
5169 mInputSource = new AudioStreamInSource(input->stream);
5170 size_t numCounterOffers = 0;
5171 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5172 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5173 ALOG_ASSERT(index == 0);
5174
5175 // initialize fast capture depending on configuration
5176 bool initFastCapture;
5177 switch (kUseFastCapture) {
5178 case FastCapture_Never:
5179 initFastCapture = false;
5180 break;
5181 case FastCapture_Always:
5182 initFastCapture = true;
5183 break;
5184 case FastCapture_Static:
5185 uint32_t primaryOutputSampleRate;
5186 {
5187 AutoMutex _l(audioFlinger->mHardwareLock);
5188 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5189 }
5190 initFastCapture =
5191 // either capture sample rate is same as (a reasonable) primary output sample rate
5192 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5193 (mSampleRate == primaryOutputSampleRate)) ||
5194 // or primary output sample rate is unknown, and capture sample rate is reasonable
5195 ((primaryOutputSampleRate == 0) &&
5196 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005197 // and the buffer size is < 12 ms
5198 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005199 break;
5200 // case FastCapture_Dynamic:
5201 }
5202
5203 if (initFastCapture) {
5204 // create a Pipe for FastMixer to write to, and for us and fast tracks to read from
5205 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005206 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005207 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5208 void *pipeBuffer;
5209 const sp<MemoryDealer> roHeap(readOnlyHeap());
5210 sp<IMemory> pipeMemory;
5211 if ((roHeap == 0) ||
5212 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5213 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5214 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5215 goto failed;
5216 }
5217 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5218 memset(pipeBuffer, 0, pipeSize);
5219 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5220 const NBAIO_Format offers[1] = {format};
5221 size_t numCounterOffers = 0;
5222 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5223 ALOG_ASSERT(index == 0);
5224 mPipeSink = pipe;
5225 PipeReader *pipeReader = new PipeReader(*pipe);
5226 numCounterOffers = 0;
5227 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5228 ALOG_ASSERT(index == 0);
5229 mPipeSource = pipeReader;
5230 mPipeFramesP2 = pipeFramesP2;
5231 mPipeMemory = pipeMemory;
5232
5233 // create fast capture
5234 mFastCapture = new FastCapture();
5235 FastCaptureStateQueue *sq = mFastCapture->sq();
5236#ifdef STATE_QUEUE_DUMP
5237 // FIXME
5238#endif
5239 FastCaptureState *state = sq->begin();
5240 state->mCblk = NULL;
5241 state->mInputSource = mInputSource.get();
5242 state->mInputSourceGen++;
5243 state->mPipeSink = pipe;
5244 state->mPipeSinkGen++;
5245 state->mFrameCount = mFrameCount;
5246 state->mCommand = FastCaptureState::COLD_IDLE;
5247 // already done in constructor initialization list
5248 //mFastCaptureFutex = 0;
5249 state->mColdFutexAddr = &mFastCaptureFutex;
5250 state->mColdGen++;
5251 state->mDumpState = &mFastCaptureDumpState;
5252#ifdef TEE_SINK
5253 // FIXME
5254#endif
5255 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5256 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5257 sq->end();
5258 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5259
5260 // start the fast capture
5261 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5262 pid_t tid = mFastCapture->getTid();
5263 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5264 if (err != 0) {
5265 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5266 kPriorityFastCapture, getpid_cached, tid, err);
5267 }
5268
5269#ifdef AUDIO_WATCHDOG
5270 // FIXME
5271#endif
5272
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005273 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005274 }
5275failed: ;
5276
5277 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005278}
5279
5280
5281AudioFlinger::RecordThread::~RecordThread()
5282{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005283 if (mFastCapture != 0) {
5284 FastCaptureStateQueue *sq = mFastCapture->sq();
5285 FastCaptureState *state = sq->begin();
5286 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5287 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5288 if (old == -1) {
5289 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5290 }
5291 }
5292 state->mCommand = FastCaptureState::EXIT;
5293 sq->end();
5294 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5295 mFastCapture->join();
5296 mFastCapture.clear();
5297 }
5298 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005299 mAudioFlinger->unregisterWriter(mNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005300 delete[] mRsmpInBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005301}
5302
5303void AudioFlinger::RecordThread::onFirstRef()
5304{
5305 run(mName, PRIORITY_URGENT_AUDIO);
5306}
5307
Eric Laurent81784c32012-11-19 14:55:58 -08005308bool AudioFlinger::RecordThread::threadLoop()
5309{
Eric Laurent81784c32012-11-19 14:55:58 -08005310 nsecs_t lastWarning = 0;
5311
5312 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005313
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005314reacquire_wakelock:
5315 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005316 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005317 {
5318 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005319 size_t size = mActiveTracks.size();
5320 activeTracksGen = mActiveTracksGen;
5321 if (size > 0) {
5322 // FIXME an arbitrary choice
5323 activeTrack = mActiveTracks[0];
5324 acquireWakeLock_l(activeTrack->uid());
5325 if (size > 1) {
5326 SortedVector<int> tmp;
5327 for (size_t i = 0; i < size; i++) {
5328 tmp.add(mActiveTracks[i]->uid());
5329 }
5330 updateWakeLockUids_l(tmp);
5331 }
5332 } else {
5333 acquireWakeLock_l(-1);
5334 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005335 }
5336
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005337 // used to request a deferred sleep, to be executed later while mutex is unlocked
5338 uint32_t sleepUs = 0;
5339
5340 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005341 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005342 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005343
Glenn Kasten5edadd42013-08-14 16:30:49 -07005344 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005345 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005346 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005347 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005348 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005349 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005350 }
5351
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005352 // activeTracks accumulates a copy of a subset of mActiveTracks
5353 Vector< sp<RecordTrack> > activeTracks;
5354
Glenn Kasten735f45f2014-08-18 15:51:59 -07005355 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005356 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005357
Glenn Kasten735f45f2014-08-18 15:51:59 -07005358 // reference to a fast track which is about to be removed
5359 sp<RecordTrack> fastTrackToRemove;
5360
Eric Laurent81784c32012-11-19 14:55:58 -08005361 { // scope for mLock
5362 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005363
Eric Laurent021cf962014-05-13 10:18:14 -07005364 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005365
Eric Laurent000a4192014-01-29 15:17:32 -08005366 // check exitPending here because checkForNewParameters_l() and
5367 // checkForNewParameters_l() can temporarily release mLock
5368 if (exitPending()) {
5369 break;
5370 }
5371
Glenn Kasten2b806402013-11-20 16:37:38 -08005372 // if no active track(s), then standby and release wakelock
5373 size_t size = mActiveTracks.size();
5374 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005375 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005376 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005377 releaseWakeLock_l();
5378 ALOGV("RecordThread: loop stopping");
5379 // go to sleep
5380 mWaitWorkCV.wait(mLock);
5381 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005382 goto reacquire_wakelock;
5383 }
5384
Glenn Kasten2b806402013-11-20 16:37:38 -08005385 if (mActiveTracksGen != activeTracksGen) {
5386 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005387 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005388 for (size_t i = 0; i < size; i++) {
5389 tmp.add(mActiveTracks[i]->uid());
5390 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005391 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005392 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005393
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005394 bool doBroadcast = false;
5395 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005396
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005397 activeTrack = mActiveTracks[i];
5398 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005399 if (activeTrack->isFastTrack()) {
5400 ALOG_ASSERT(fastTrackToRemove == 0);
5401 fastTrackToRemove = activeTrack;
5402 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005403 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005404 mActiveTracks.remove(activeTrack);
5405 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005406 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005407 continue;
5408 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005409
5410 TrackBase::track_state activeTrackState = activeTrack->mState;
5411 switch (activeTrackState) {
5412
5413 case TrackBase::PAUSING:
5414 mActiveTracks.remove(activeTrack);
5415 mActiveTracksGen++;
5416 doBroadcast = true;
5417 size--;
5418 continue;
5419
5420 case TrackBase::STARTING_1:
5421 sleepUs = 10000;
5422 i++;
5423 continue;
5424
5425 case TrackBase::STARTING_2:
5426 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005427 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005428 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005429 break;
5430
5431 case TrackBase::ACTIVE:
5432 break;
5433
5434 case TrackBase::IDLE:
5435 i++;
5436 continue;
5437
5438 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005439 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005440 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005441
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005442 activeTracks.add(activeTrack);
5443 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005444
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005445 if (activeTrack->isFastTrack()) {
5446 ALOG_ASSERT(!mFastTrackAvail);
5447 ALOG_ASSERT(fastTrack == 0);
5448 fastTrack = activeTrack;
5449 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005450 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005451 if (doBroadcast) {
5452 mStartStopCond.broadcast();
5453 }
5454
5455 // sleep if there are no active tracks to process
5456 if (activeTracks.size() == 0) {
5457 if (sleepUs == 0) {
5458 sleepUs = kRecordThreadSleepUs;
5459 }
5460 continue;
5461 }
5462 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005463
Eric Laurent81784c32012-11-19 14:55:58 -08005464 lockEffectChains_l(effectChains);
5465 }
5466
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005467 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005468
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005469 size_t size = effectChains.size();
5470 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005471 // thread mutex is not locked, but effect chain is locked
5472 effectChains[i]->process_l();
5473 }
5474
Glenn Kasten735f45f2014-08-18 15:51:59 -07005475 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005476 if (mFastCapture != 0) {
5477 FastCaptureStateQueue *sq = mFastCapture->sq();
5478 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005479 bool didModify = false;
5480 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005481 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5482 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5483 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5484 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5485 if (old == -1) {
5486 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5487 }
5488 }
5489 state->mCommand = FastCaptureState::READ_WRITE;
5490#if 0 // FIXME
5491 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005492 FastThreadDumpState::kSamplingNforLowRamDevice :
5493 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005494#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005495 didModify = true;
5496 }
5497 audio_track_cblk_t *cblkOld = state->mCblk;
5498 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5499 if (cblkNew != cblkOld) {
5500 state->mCblk = cblkNew;
5501 // block until acked if removing a fast track
5502 if (cblkOld != NULL) {
5503 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5504 }
5505 didModify = true;
5506 }
5507 sq->end(didModify);
5508 if (didModify) {
5509 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005510#if 0
5511 if (kUseFastCapture == FastCapture_Dynamic) {
5512 mNormalSource = mPipeSource;
5513 }
5514#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005515 }
5516 }
5517
Glenn Kasten735f45f2014-08-18 15:51:59 -07005518 // now run the fast track destructor with thread mutex unlocked
5519 fastTrackToRemove.clear();
5520
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005521 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5522 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5523 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5524 // If destination is non-contiguous, first read past the nominal end of buffer, then
5525 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005526
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005527 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005528 ssize_t framesRead;
5529
5530 // If an NBAIO source is present, use it to read the normal capture's data
5531 if (mPipeSource != 0) {
5532 size_t framesToRead = mBufferSize / mFrameSize;
5533 framesRead = mPipeSource->read(&mRsmpInBuffer[rear * mChannelCount],
5534 framesToRead, AudioBufferProvider::kInvalidPTS);
5535 if (framesRead == 0) {
5536 // since pipe is non-blocking, simulate blocking input
5537 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5538 }
5539 // otherwise use the HAL / AudioStreamIn directly
5540 } else {
5541 ssize_t bytesRead = mInput->stream->read(mInput->stream,
5542 &mRsmpInBuffer[rear * mChannelCount], mBufferSize);
5543 if (bytesRead < 0) {
5544 framesRead = bytesRead;
5545 } else {
5546 framesRead = bytesRead / mFrameSize;
5547 }
5548 }
5549
5550 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5551 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005552 // Force input into standby so that it tries to recover at next read attempt
5553 inputStandBy();
5554 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005555 }
5556 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005557 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005558 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005559 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005560
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005561 if (mTeeSink != 0) {
5562 (void) mTeeSink->write(&mRsmpInBuffer[rear * mChannelCount], framesRead);
5563 }
5564 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005565 {
5566 size_t part1 = mRsmpInFramesP2 - rear;
5567 if ((size_t) framesRead > part1) {
5568 memcpy(mRsmpInBuffer, &mRsmpInBuffer[mRsmpInFramesP2 * mChannelCount],
5569 (framesRead - part1) * mFrameSize);
5570 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005571 }
5572 rear = mRsmpInRear += framesRead;
5573
5574 size = activeTracks.size();
5575 // loop over each active track
5576 for (size_t i = 0; i < size; i++) {
5577 activeTrack = activeTracks[i];
5578
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005579 // skip fast tracks, as those are handled directly by FastCapture
5580 if (activeTrack->isFastTrack()) {
5581 continue;
5582 }
5583
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005584 enum {
5585 OVERRUN_UNKNOWN,
5586 OVERRUN_TRUE,
5587 OVERRUN_FALSE
5588 } overrun = OVERRUN_UNKNOWN;
5589
5590 // loop over getNextBuffer to handle circular sink
5591 for (;;) {
5592
5593 activeTrack->mSink.frameCount = ~0;
5594 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5595 size_t framesOut = activeTrack->mSink.frameCount;
5596 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5597
5598 int32_t front = activeTrack->mRsmpInFront;
5599 ssize_t filled = rear - front;
5600 size_t framesIn;
5601
5602 if (filled < 0) {
5603 // should not happen, but treat like a massive overrun and re-sync
5604 framesIn = 0;
5605 activeTrack->mRsmpInFront = rear;
5606 overrun = OVERRUN_TRUE;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005607 } else if ((size_t) filled <= mRsmpInFrames) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005608 framesIn = (size_t) filled;
5609 } else {
5610 // client is not keeping up with server, but give it latest data
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005611 framesIn = mRsmpInFrames;
5612 activeTrack->mRsmpInFront = front = rear - framesIn;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005613 overrun = OVERRUN_TRUE;
5614 }
5615
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005616 if (framesOut == 0 || framesIn == 0) {
5617 break;
5618 }
5619
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005620 if (activeTrack->mResampler == NULL) {
5621 // no resampling
5622 if (framesIn > framesOut) {
5623 framesIn = framesOut;
5624 } else {
5625 framesOut = framesIn;
5626 }
5627 int8_t *dst = activeTrack->mSink.i8;
5628 while (framesIn > 0) {
5629 front &= mRsmpInFramesP2 - 1;
5630 size_t part1 = mRsmpInFramesP2 - front;
5631 if (part1 > framesIn) {
5632 part1 = framesIn;
5633 }
5634 int8_t *src = (int8_t *)mRsmpInBuffer + (front * mFrameSize);
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005635 if (mChannelCount == activeTrack->mChannelCount) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005636 memcpy(dst, src, part1 * mFrameSize);
5637 } else if (mChannelCount == 1) {
Glenn Kastencd704212014-07-14 17:26:36 -07005638 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst, (const int16_t *)src,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005639 part1);
5640 } else {
Glenn Kastenb187de12014-12-30 08:18:15 -08005641 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
5642 (const int16_t *)src, part1);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005643 }
5644 dst += part1 * activeTrack->mFrameSize;
5645 front += part1;
5646 framesIn -= part1;
5647 }
5648 activeTrack->mRsmpInFront += framesOut;
5649
5650 } else {
5651 // resampling
5652 // FIXME framesInNeeded should really be part of resampler API, and should
5653 // depend on the SRC ratio
5654 // to keep mRsmpInBuffer full so resampler always has sufficient input
5655 size_t framesInNeeded;
5656 // FIXME only re-calculate when it changes, and optimize for common ratios
Andy Hung8661aaf2014-07-28 14:38:41 -07005657 // Do not precompute in/out because floating point is not associative
5658 // e.g. a*b/c != a*(b/c).
5659 const double in(mSampleRate);
5660 const double out(activeTrack->mSampleRate);
5661 framesInNeeded = ceil(framesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005662 ALOGV("need %u frames in to produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005663 framesInNeeded, framesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005664 // Although we theoretically have framesIn in circular buffer, some of those are
5665 // unreleased frames, and thus must be discounted for purpose of budgeting.
5666 size_t unreleased = activeTrack->mRsmpInUnrel;
5667 framesIn = framesIn > unreleased ? framesIn - unreleased : 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005668 if (framesIn < framesInNeeded) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005669 ALOGV("not enough to resample: have %u frames in but need %u in to "
5670 "produce %u out given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005671 framesIn, framesInNeeded, framesOut, in / out);
5672 size_t newFramesOut = framesIn > 0 ? floor((framesIn - 1) * out / in) : 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005673 LOG_ALWAYS_FATAL_IF(newFramesOut >= framesOut);
5674 if (newFramesOut == 0) {
5675 break;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005676 }
Andy Hung8661aaf2014-07-28 14:38:41 -07005677 framesInNeeded = ceil(newFramesOut * in / out) + 1;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005678 ALOGV("now need %u frames in to produce %u out given out/in ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005679 framesInNeeded, newFramesOut, out / in);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005680 LOG_ALWAYS_FATAL_IF(framesIn < framesInNeeded);
5681 ALOGV("success 2: have %u frames in and need %u in to produce %u out "
5682 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005683 framesIn, framesInNeeded, newFramesOut, in / out);
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005684 framesOut = newFramesOut;
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005685 } else {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005686 ALOGV("success 1: have %u in and need %u in to produce %u out "
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005687 "given in/out ratio of %.4g",
Andy Hung8661aaf2014-07-28 14:38:41 -07005688 framesIn, framesInNeeded, framesOut, in / out);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005689 }
5690
5691 // reallocate mRsmpOutBuffer as needed; we will grow but never shrink
5692 if (activeTrack->mRsmpOutFrameCount < framesOut) {
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005693 // FIXME why does each track need it's own mRsmpOutBuffer? can't they share?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005694 delete[] activeTrack->mRsmpOutBuffer;
5695 // resampler always outputs stereo
5696 activeTrack->mRsmpOutBuffer = new int32_t[framesOut * FCC_2];
5697 activeTrack->mRsmpOutFrameCount = framesOut;
5698 }
5699
5700 // resampler accumulates, but we only have one source track
5701 memset(activeTrack->mRsmpOutBuffer, 0, framesOut * FCC_2 * sizeof(int32_t));
5702 activeTrack->mResampler->resample(activeTrack->mRsmpOutBuffer, framesOut,
Glenn Kasten607fa3e2014-02-21 14:24:58 -08005703 // FIXME how about having activeTrack implement this interface itself?
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005704 activeTrack->mResamplerBufferProvider
5705 /*this*/ /* AudioBufferProvider* */);
5706 // ditherAndClamp() works as long as all buffers returned by
5707 // activeTrack->getNextBuffer() are 32 bit aligned which should be always true.
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005708 if (activeTrack->mChannelCount == 1) {
Andy Hung84a0c6e2014-04-02 11:24:53 -07005709 // temporarily type pun mRsmpOutBuffer from Q4.27 to int16_t
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005710 ditherAndClamp(activeTrack->mRsmpOutBuffer, activeTrack->mRsmpOutBuffer,
5711 framesOut);
5712 // the resampler always outputs stereo samples:
5713 // do post stereo to mono conversion
5714 downmix_to_mono_i16_from_stereo_i16(activeTrack->mSink.i16,
Glenn Kastencd704212014-07-14 17:26:36 -07005715 (const int16_t *)activeTrack->mRsmpOutBuffer, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005716 } else {
5717 ditherAndClamp((int32_t *)activeTrack->mSink.raw,
5718 activeTrack->mRsmpOutBuffer, framesOut);
5719 }
5720 // now done with mRsmpOutBuffer
5721
5722 }
5723
5724 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5725 overrun = OVERRUN_FALSE;
5726 }
5727
5728 if (activeTrack->mFramesToDrop == 0) {
5729 if (framesOut > 0) {
5730 activeTrack->mSink.frameCount = framesOut;
5731 activeTrack->releaseBuffer(&activeTrack->mSink);
5732 }
5733 } else {
5734 // FIXME could do a partial drop of framesOut
5735 if (activeTrack->mFramesToDrop > 0) {
5736 activeTrack->mFramesToDrop -= framesOut;
5737 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005738 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005739 }
5740 } else {
5741 activeTrack->mFramesToDrop += framesOut;
5742 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5743 activeTrack->mSyncStartEvent->isCancelled()) {
5744 ALOGW("Synced record %s, session %d, trigger session %d",
5745 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5746 activeTrack->sessionId(),
5747 (activeTrack->mSyncStartEvent != 0) ?
5748 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005749 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005750 }
5751 }
5752 }
5753
5754 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005755 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005756 }
5757 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005758
5759 switch (overrun) {
5760 case OVERRUN_TRUE:
5761 // client isn't retrieving buffers fast enough
5762 if (!activeTrack->setOverflow()) {
5763 nsecs_t now = systemTime();
5764 // FIXME should lastWarning per track?
5765 if ((now - lastWarning) > kWarningThrottleNs) {
5766 ALOGW("RecordThread: buffer overflow");
5767 lastWarning = now;
5768 }
5769 }
5770 break;
5771 case OVERRUN_FALSE:
5772 activeTrack->clearOverflow();
5773 break;
5774 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005775 break;
5776 }
5777
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005778 }
5779
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005780unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005781 // enable changes in effect chain
5782 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005783 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005784 }
5785
Glenn Kasten93e471f2013-08-19 08:40:07 -07005786 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005787
5788 {
5789 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005790 for (size_t i = 0; i < mTracks.size(); i++) {
5791 sp<RecordTrack> track = mTracks[i];
5792 track->invalidate();
5793 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005794 mActiveTracks.clear();
5795 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005796 mStartStopCond.broadcast();
5797 }
5798
5799 releaseWakeLock();
5800
5801 ALOGV("RecordThread %p exiting", this);
5802 return false;
5803}
5804
Glenn Kasten93e471f2013-08-19 08:40:07 -07005805void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005806{
5807 if (!mStandby) {
5808 inputStandBy();
5809 mStandby = true;
5810 }
5811}
5812
5813void AudioFlinger::RecordThread::inputStandBy()
5814{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005815 // Idle the fast capture if it's currently running
5816 if (mFastCapture != 0) {
5817 FastCaptureStateQueue *sq = mFastCapture->sq();
5818 FastCaptureState *state = sq->begin();
5819 if (!(state->mCommand & FastCaptureState::IDLE)) {
5820 state->mCommand = FastCaptureState::COLD_IDLE;
5821 state->mColdFutexAddr = &mFastCaptureFutex;
5822 state->mColdGen++;
5823 mFastCaptureFutex = 0;
5824 sq->end();
5825 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5826 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5827#if 0
5828 if (kUseFastCapture == FastCapture_Dynamic) {
5829 // FIXME
5830 }
5831#endif
5832#ifdef AUDIO_WATCHDOG
5833 // FIXME
5834#endif
5835 } else {
5836 sq->end(false /*didModify*/);
5837 }
5838 }
Eric Laurent81784c32012-11-19 14:55:58 -08005839 mInput->stream->common.standby(&mInput->stream->common);
5840}
5841
Glenn Kasten05997e22014-03-13 15:08:33 -07005842// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005843sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005844 const sp<AudioFlinger::Client>& client,
5845 uint32_t sampleRate,
5846 audio_format_t format,
5847 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005848 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005849 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005850 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005851 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005852 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005853 pid_t tid,
5854 status_t *status)
5855{
Glenn Kasten74935e42013-12-19 08:56:45 -08005856 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005857 sp<RecordTrack> track;
5858 status_t lStatus;
5859
Glenn Kasten90e58b12013-07-31 16:16:02 -07005860 // client expresses a preference for FAST, but we get the final say
5861 if (*flags & IAudioFlinger::TRACK_FAST) {
5862 if (
Glenn Kasten74105912014-07-03 12:28:53 -07005863 // use case: callback handler
5864 (tid != -1) &&
5865 // frame count is not specified, or is exactly the pipe depth
5866 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005867 // PCM data
5868 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005869 // native format
5870 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005871 // native channel mask
5872 (channelMask == mChannelMask) &&
5873 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005874 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005875 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005876 hasFastCapture() &&
5877 // there are sufficient fast track slots available
5878 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005879 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005880 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005881 frameCount, mFrameCount);
5882 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005883 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5884 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005885 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005886 frameCount, mFrameCount, mPipeFramesP2,
5887 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5888 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005889 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005890 }
5891 }
5892
5893 // compute track buffer size in frames, and suggest the notification frame count
5894 if (*flags & IAudioFlinger::TRACK_FAST) {
5895 // fast track: frame count is exactly the pipe depth
5896 frameCount = mPipeFramesP2;
5897 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5898 *notificationFrames = mFrameCount;
5899 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005900 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5901 // or 20 ms if there is a fast capture
5902 // TODO This could be a roundupRatio inline, and const
5903 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5904 * sampleRate + mSampleRate - 1) / mSampleRate;
5905 // minimum number of notification periods is at least kMinNotifications,
5906 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5907 static const size_t kMinNotifications = 3;
5908 static const uint32_t kMinMs = 30;
5909 // TODO This could be a roundupRatio inline
5910 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5911 // TODO This could be a roundupRatio inline
5912 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5913 maxNotificationFrames;
5914 const size_t minFrameCount = maxNotificationFrames *
5915 max(kMinNotifications, minNotificationsByMs);
5916 frameCount = max(frameCount, minFrameCount);
5917 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5918 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005919 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005920 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005921 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005922
Glenn Kasten15e57982013-09-24 11:52:37 -07005923 lStatus = initCheck();
5924 if (lStatus != NO_ERROR) {
5925 ALOGE("createRecordTrack_l() audio driver not initialized");
5926 goto Exit;
5927 }
Eric Laurent81784c32012-11-19 14:55:58 -08005928
5929 { // scope for mLock
5930 Mutex::Autolock _l(mLock);
5931
5932 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005933 format, channelMask, frameCount, NULL, sessionId, uid,
5934 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005935
Glenn Kasten03003332013-08-06 15:40:54 -07005936 lStatus = track->initCheck();
5937 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005938 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005939 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005940 goto Exit;
5941 }
5942 mTracks.add(track);
5943
5944 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5945 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5946 mAudioFlinger->btNrecIsOff();
5947 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5948 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005949
5950 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5951 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5952 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5953 // so ask activity manager to do this on our behalf
5954 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5955 }
Eric Laurent81784c32012-11-19 14:55:58 -08005956 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005957
Eric Laurent81784c32012-11-19 14:55:58 -08005958 lStatus = NO_ERROR;
5959
5960Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005961 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005962 return track;
5963}
5964
5965status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5966 AudioSystem::sync_event_t event,
5967 int triggerSession)
5968{
5969 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5970 sp<ThreadBase> strongMe = this;
5971 status_t status = NO_ERROR;
5972
5973 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005974 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005975 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005976 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005977 triggerSession,
5978 recordTrack->sessionId(),
5979 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005980 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005981 // Sync event can be cancelled by the trigger session if the track is not in a
5982 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005983 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005984 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005985 } else {
5986 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005987 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005988 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005989 }
5990 }
5991
5992 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005993 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005994 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005995 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5996 if (recordTrack->mState == TrackBase::PAUSING) {
5997 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005998 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005999 } else {
6000 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006001 }
6002 return status;
6003 }
6004
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006005 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6006 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6007 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006008 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006009 mActiveTracks.add(recordTrack);
6010 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006011 status_t status = NO_ERROR;
6012 if (recordTrack->isExternalTrack()) {
6013 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006014 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006015 mLock.lock();
6016 // FIXME should verify that recordTrack is still in mActiveTracks
6017 if (status != NO_ERROR) {
6018 mActiveTracks.remove(recordTrack);
6019 mActiveTracksGen++;
6020 recordTrack->clearSyncStartEvent();
6021 ALOGV("RecordThread::start error %d", status);
6022 return status;
6023 }
Eric Laurent81784c32012-11-19 14:55:58 -08006024 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006025 // Catch up with current buffer indices if thread is already running.
6026 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6027 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6028 // see previously buffered data before it called start(), but with greater risk of overrun.
6029
6030 recordTrack->mRsmpInFront = mRsmpInRear;
6031 recordTrack->mRsmpInUnrel = 0;
6032 // FIXME why reset?
6033 if (recordTrack->mResampler != NULL) {
6034 recordTrack->mResampler->reset();
Eric Laurent81784c32012-11-19 14:55:58 -08006035 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006036 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006037 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006038 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006039 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006040 ALOGV("Record failed to start");
6041 status = BAD_VALUE;
6042 goto startError;
6043 }
Eric Laurent81784c32012-11-19 14:55:58 -08006044 return status;
6045 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006046
Eric Laurent81784c32012-11-19 14:55:58 -08006047startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006048 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006049 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006050 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006051 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006052 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006053 return status;
6054}
6055
Eric Laurent81784c32012-11-19 14:55:58 -08006056void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6057{
6058 sp<SyncEvent> strongEvent = event.promote();
6059
6060 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006061 sp<RefBase> ptr = strongEvent->cookie().promote();
6062 if (ptr != 0) {
6063 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6064 recordTrack->handleSyncStartEvent(strongEvent);
6065 }
Eric Laurent81784c32012-11-19 14:55:58 -08006066 }
6067}
6068
Glenn Kastena8356f62013-07-25 14:37:52 -07006069bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006070 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006071 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006072 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006073 return false;
6074 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006075 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006076 recordTrack->mState = TrackBase::PAUSING;
6077 // do not wait for mStartStopCond if exiting
6078 if (exitPending()) {
6079 return true;
6080 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006081 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006082 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006083 // if we have been restarted, recordTrack is in mActiveTracks here
6084 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006085 ALOGV("Record stopped OK");
6086 return true;
6087 }
6088 return false;
6089}
6090
Glenn Kasten0f11b512014-01-31 16:18:54 -08006091bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006092{
6093 return false;
6094}
6095
Glenn Kasten0f11b512014-01-31 16:18:54 -08006096status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006097{
6098#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6099 if (!isValidSyncEvent(event)) {
6100 return BAD_VALUE;
6101 }
6102
6103 int eventSession = event->triggerSession();
6104 status_t ret = NAME_NOT_FOUND;
6105
6106 Mutex::Autolock _l(mLock);
6107
6108 for (size_t i = 0; i < mTracks.size(); i++) {
6109 sp<RecordTrack> track = mTracks[i];
6110 if (eventSession == track->sessionId()) {
6111 (void) track->setSyncEvent(event);
6112 ret = NO_ERROR;
6113 }
6114 }
6115 return ret;
6116#else
6117 return BAD_VALUE;
6118#endif
6119}
6120
6121// destroyTrack_l() must be called with ThreadBase::mLock held
6122void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6123{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006124 track->terminate();
6125 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006126 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006127 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006128 removeTrack_l(track);
6129 }
6130}
6131
6132void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6133{
6134 mTracks.remove(track);
6135 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006136 if (track->isFastTrack()) {
6137 ALOG_ASSERT(!mFastTrackAvail);
6138 mFastTrackAvail = true;
6139 }
Eric Laurent81784c32012-11-19 14:55:58 -08006140}
6141
6142void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6143{
6144 dumpInternals(fd, args);
6145 dumpTracks(fd, args);
6146 dumpEffectChains(fd, args);
6147}
6148
6149void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6150{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006151 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006152
Glenn Kasten2b806402013-11-20 16:37:38 -08006153 if (mActiveTracks.size() > 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006154 dprintf(fd, " Buffer size: %zu bytes\n", mBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006155 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006156 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006157 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006158 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006159 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Eric Laurent81784c32012-11-19 14:55:58 -08006160
Eric Laurent81784c32012-11-19 14:55:58 -08006161 dumpBase(fd, args);
6162}
6163
Glenn Kasten0f11b512014-01-31 16:18:54 -08006164void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006165{
6166 const size_t SIZE = 256;
6167 char buffer[SIZE];
6168 String8 result;
6169
Marco Nelissenb2208842014-02-07 14:00:50 -08006170 size_t numtracks = mTracks.size();
6171 size_t numactive = mActiveTracks.size();
6172 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006173 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006174 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006175 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006176 RecordTrack::appendDumpHeader(result);
6177 for (size_t i = 0; i < numtracks ; ++i) {
6178 sp<RecordTrack> track = mTracks[i];
6179 if (track != 0) {
6180 bool active = mActiveTracks.indexOf(track) >= 0;
6181 if (active) {
6182 numactiveseen++;
6183 }
6184 track->dump(buffer, SIZE, active);
6185 result.append(buffer);
6186 }
Eric Laurent81784c32012-11-19 14:55:58 -08006187 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006188 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006189 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006190 }
6191
Marco Nelissenb2208842014-02-07 14:00:50 -08006192 if (numactiveseen != numactive) {
6193 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6194 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006195 result.append(buffer);
6196 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006197 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006198 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006199 if (mTracks.indexOf(track) < 0) {
6200 track->dump(buffer, SIZE, true);
6201 result.append(buffer);
6202 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006203 }
Eric Laurent81784c32012-11-19 14:55:58 -08006204
6205 }
6206 write(fd, result.string(), result.size());
6207}
6208
6209// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006210status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6211 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006212{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006213 RecordTrack *activeTrack = mRecordTrack;
6214 sp<ThreadBase> threadBase = activeTrack->mThread.promote();
6215 if (threadBase == 0) {
6216 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006217 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006218 return NOT_ENOUGH_DATA;
6219 }
6220 RecordThread *recordThread = (RecordThread *) threadBase.get();
6221 int32_t rear = recordThread->mRsmpInRear;
6222 int32_t front = activeTrack->mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006223 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 // FIXME should not be P2 (don't want to increase latency)
6225 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006226 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006227 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006228 front &= recordThread->mRsmpInFramesP2 - 1;
6229 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006230 if (part1 > (size_t) filled) {
6231 part1 = filled;
6232 }
6233 size_t ask = buffer->frameCount;
6234 ALOG_ASSERT(ask > 0);
6235 if (part1 > ask) {
6236 part1 = ask;
6237 }
6238 if (part1 == 0) {
6239 // Higher-level should keep mRsmpInBuffer full, and not call resampler if empty
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006240 LOG_ALWAYS_FATAL("RecordThread::getNextBuffer() starved");
Glenn Kasten85948432013-08-19 12:09:05 -07006241 buffer->raw = NULL;
6242 buffer->frameCount = 0;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006243 activeTrack->mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006244 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
6246
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006247 buffer->raw = recordThread->mRsmpInBuffer + front * recordThread->mChannelCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006248 buffer->frameCount = part1;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006249 activeTrack->mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006250 return NO_ERROR;
6251}
6252
6253// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006254void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6255 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006256{
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006257 RecordTrack *activeTrack = mRecordTrack;
Glenn Kasten85948432013-08-19 12:09:05 -07006258 size_t stepCount = buffer->frameCount;
6259 if (stepCount == 0) {
6260 return;
6261 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006262 ALOG_ASSERT(stepCount <= activeTrack->mRsmpInUnrel);
6263 activeTrack->mRsmpInUnrel -= stepCount;
6264 activeTrack->mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006265 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006266 buffer->frameCount = 0;
6267}
6268
Eric Laurent10351942014-05-08 18:49:52 -07006269bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6270 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006271{
6272 bool reconfig = false;
6273
Eric Laurent10351942014-05-08 18:49:52 -07006274 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006275
Eric Laurent10351942014-05-08 18:49:52 -07006276 audio_format_t reqFormat = mFormat;
6277 uint32_t samplingRate = mSampleRate;
6278 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6279
6280 AudioParameter param = AudioParameter(keyValuePair);
6281 int value;
6282 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6283 // channel count change can be requested. Do we mandate the first client defines the
6284 // HAL sampling rate and channel count or do we allow changes on the fly?
6285 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6286 samplingRate = value;
6287 reconfig = true;
6288 }
6289 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
6290 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
6291 status = BAD_VALUE;
6292 } else {
6293 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006294 reconfig = true;
6295 }
Eric Laurent10351942014-05-08 18:49:52 -07006296 }
6297 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6298 audio_channel_mask_t mask = (audio_channel_mask_t) value;
6299 if (mask != AUDIO_CHANNEL_IN_MONO && mask != AUDIO_CHANNEL_IN_STEREO) {
6300 status = BAD_VALUE;
6301 } else {
6302 channelMask = mask;
6303 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006304 }
Eric Laurent10351942014-05-08 18:49:52 -07006305 }
6306 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6307 // do not accept frame count changes if tracks are open as the track buffer
6308 // size depends on frame count and correct behavior would not be guaranteed
6309 // if frame count is changed after track creation
6310 if (mActiveTracks.size() > 0) {
6311 status = INVALID_OPERATION;
6312 } else {
6313 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006314 }
Eric Laurent10351942014-05-08 18:49:52 -07006315 }
6316 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6317 // forward device change to effects that have requested to be
6318 // aware of attached audio device.
6319 for (size_t i = 0; i < mEffectChains.size(); i++) {
6320 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006321 }
Eric Laurent81784c32012-11-19 14:55:58 -08006322
Eric Laurent10351942014-05-08 18:49:52 -07006323 // store input device and output device but do not forward output device to audio HAL.
6324 // Note that status is ignored by the caller for output device
6325 // (see AudioFlinger::setParameters()
6326 if (audio_is_output_devices(value)) {
6327 mOutDevice = value;
6328 status = BAD_VALUE;
6329 } else {
6330 mInDevice = value;
6331 // disable AEC and NS if the device is a BT SCO headset supporting those
6332 // pre processings
6333 if (mTracks.size() > 0) {
6334 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6335 mAudioFlinger->btNrecIsOff();
6336 for (size_t i = 0; i < mTracks.size(); i++) {
6337 sp<RecordTrack> track = mTracks[i];
6338 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6339 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006340 }
6341 }
6342 }
Eric Laurent10351942014-05-08 18:49:52 -07006343 }
6344 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6345 mAudioSource != (audio_source_t)value) {
6346 // forward device change to effects that have requested to be
6347 // aware of attached audio device.
6348 for (size_t i = 0; i < mEffectChains.size(); i++) {
6349 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006350 }
Eric Laurent10351942014-05-08 18:49:52 -07006351 mAudioSource = (audio_source_t)value;
6352 }
Glenn Kastene198c362013-08-13 09:13:36 -07006353
Eric Laurent10351942014-05-08 18:49:52 -07006354 if (status == NO_ERROR) {
6355 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6356 keyValuePair.string());
6357 if (status == INVALID_OPERATION) {
6358 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006359 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6360 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006361 }
6362 if (reconfig) {
6363 if (status == BAD_VALUE &&
6364 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
6365 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
6366 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
6367 <= (2 * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006368 audio_channel_count_from_in_mask(
6369 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006370 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6371 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6372 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006373 }
Eric Laurent10351942014-05-08 18:49:52 -07006374 if (status == NO_ERROR) {
6375 readInputParameters_l();
6376 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006377 }
6378 }
Eric Laurent81784c32012-11-19 14:55:58 -08006379 }
Eric Laurent10351942014-05-08 18:49:52 -07006380
Eric Laurent81784c32012-11-19 14:55:58 -08006381 return reconfig;
6382}
6383
6384String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6385{
Eric Laurent81784c32012-11-19 14:55:58 -08006386 Mutex::Autolock _l(mLock);
6387 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006388 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006389 }
6390
Glenn Kastend8ea6992013-07-16 14:17:15 -07006391 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6392 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006393 free(s);
6394 return out_s8;
6395}
6396
Eric Laurent021cf962014-05-13 10:18:14 -07006397void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006398 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006399 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006400
6401 switch (event) {
6402 case AudioSystem::INPUT_OPENED:
6403 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006404 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006405 desc.samplingRate = mSampleRate;
6406 desc.format = mFormat;
6407 desc.frameCount = mFrameCount;
6408 desc.latency = 0;
6409 param2 = &desc;
6410 break;
6411
6412 case AudioSystem::INPUT_CLOSED:
6413 default:
6414 break;
6415 }
Eric Laurent021cf962014-05-13 10:18:14 -07006416 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006417}
6418
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006419void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006420{
Eric Laurent81784c32012-11-19 14:55:58 -08006421 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6422 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006423 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07006424 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6425 mFormat = mHALFormat;
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006426 if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08006427 ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006428 }
Eric Laurent665470b2014-07-03 16:37:08 -07006429 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006430 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6431 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006433 // 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 -07006434 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006435 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006436 // A larger value should allow more old data to be read after a track calls start(),
6437 // without increasing latency.
Glenn Kastene8426142014-02-28 16:45:03 -08006438 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006439 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006440 delete[] mRsmpInBuffer;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006441
6442 // TODO optimize audio capture buffer sizes ...
6443 // Here we calculate the size of the sliding buffer used as a source
6444 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6445 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6446 // be better to have it derived from the pipe depth in the long term.
6447 // The current value is higher than necessary. However it should not add to latency.
6448
Glenn Kasten85948432013-08-19 12:09:05 -07006449 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
6450 mRsmpInBuffer = new int16_t[(mRsmpInFramesP2 + mFrameCount - 1) * mChannelCount];
Eric Laurent81784c32012-11-19 14:55:58 -08006451
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006452 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6453 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006454}
6455
Glenn Kasten5f972c02014-01-13 09:59:31 -08006456uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006457{
6458 Mutex::Autolock _l(mLock);
6459 if (initCheck() != NO_ERROR) {
6460 return 0;
6461 }
6462
6463 return mInput->stream->get_input_frames_lost(mInput->stream);
6464}
6465
6466uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6467{
6468 Mutex::Autolock _l(mLock);
6469 uint32_t result = 0;
6470 if (getEffectChain_l(sessionId) != 0) {
6471 result = EFFECT_SESSION;
6472 }
6473
6474 for (size_t i = 0; i < mTracks.size(); ++i) {
6475 if (sessionId == mTracks[i]->sessionId()) {
6476 result |= TRACK_SESSION;
6477 break;
6478 }
6479 }
6480
6481 return result;
6482}
6483
6484KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6485{
6486 KeyedVector<int, bool> ids;
6487 Mutex::Autolock _l(mLock);
6488 for (size_t j = 0; j < mTracks.size(); ++j) {
6489 sp<RecordThread::RecordTrack> track = mTracks[j];
6490 int sessionId = track->sessionId();
6491 if (ids.indexOfKey(sessionId) < 0) {
6492 ids.add(sessionId, true);
6493 }
6494 }
6495 return ids;
6496}
6497
6498AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6499{
6500 Mutex::Autolock _l(mLock);
6501 AudioStreamIn *input = mInput;
6502 mInput = NULL;
6503 return input;
6504}
6505
6506// this method must always be called either with ThreadBase mLock held or inside the thread loop
6507audio_stream_t* AudioFlinger::RecordThread::stream() const
6508{
6509 if (mInput == NULL) {
6510 return NULL;
6511 }
6512 return &mInput->stream->common;
6513}
6514
6515status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6516{
6517 // only one chain per input thread
6518 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006519 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006520 return INVALID_OPERATION;
6521 }
6522 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006523 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006524 chain->setInBuffer(NULL);
6525 chain->setOutBuffer(NULL);
6526
6527 checkSuspendOnAddEffectChain_l(chain);
6528
Eric Laurent1b928682014-10-02 19:41:47 -07006529 // make sure enabled pre processing effects state is communicated to the HAL as we
6530 // just moved them to a new input stream.
6531 chain->syncHalEffectsState();
6532
Eric Laurent81784c32012-11-19 14:55:58 -08006533 mEffectChains.add(chain);
6534
6535 return NO_ERROR;
6536}
6537
6538size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6539{
6540 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6541 ALOGW_IF(mEffectChains.size() != 1,
6542 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6543 chain.get(), mEffectChains.size(), this);
6544 if (mEffectChains.size() == 1) {
6545 mEffectChains.removeAt(0);
6546 }
6547 return 0;
6548}
6549
Eric Laurent1c333e22014-05-20 10:48:17 -07006550status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6551 audio_patch_handle_t *handle)
6552{
6553 status_t status = NO_ERROR;
6554 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6555 // store new device and send to effects
6556 mInDevice = patch->sources[0].ext.device.type;
6557 for (size_t i = 0; i < mEffectChains.size(); i++) {
6558 mEffectChains[i]->setDevice_l(mInDevice);
6559 }
6560
6561 // disable AEC and NS if the device is a BT SCO headset supporting those
6562 // pre processings
6563 if (mTracks.size() > 0) {
6564 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6565 mAudioFlinger->btNrecIsOff();
6566 for (size_t i = 0; i < mTracks.size(); i++) {
6567 sp<RecordTrack> track = mTracks[i];
6568 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6569 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6570 }
6571 }
6572
6573 // store new source and send to effects
6574 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6575 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6576 for (size_t i = 0; i < mEffectChains.size(); i++) {
6577 mEffectChains[i]->setAudioSource_l(mAudioSource);
6578 }
6579 }
6580
6581 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6582 status = hwDevice->create_audio_patch(hwDevice,
6583 patch->num_sources,
6584 patch->sources,
6585 patch->num_sinks,
6586 patch->sinks,
6587 handle);
6588 } else {
6589 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6590 }
6591 return status;
6592}
6593
6594status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6595{
6596 status_t status = NO_ERROR;
6597 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6598 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6599 status = hwDevice->release_audio_patch(hwDevice, handle);
6600 } else {
6601 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6602 }
6603 return status;
6604}
6605
Eric Laurent83b88082014-06-20 18:31:16 -07006606void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6607{
6608 Mutex::Autolock _l(mLock);
6609 mTracks.add(record);
6610}
6611
6612void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6613{
6614 Mutex::Autolock _l(mLock);
6615 destroyTrack_l(record);
6616}
6617
6618void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6619{
6620 ThreadBase::getAudioPortConfig(config);
6621 config->role = AUDIO_PORT_ROLE_SINK;
6622 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6623 config->ext.mix.usecase.source = mAudioSource;
6624}
Eric Laurent1c333e22014-05-20 10:48:17 -07006625
Glenn Kasten63238ef2015-03-02 15:50:29 -08006626} // namespace android