blob: 4039564a6872f0d3f03110500de69cfc926b49db [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Eric Laurent81784c32012-11-19 14:55:58 -080032#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080033#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034
35#include <private/media/AudioTrackShared.h>
36#include <hardware/audio.h>
37#include <audio_effects/effect_ns.h>
38#include <audio_effects/effect_aec.h>
39#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070044#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045#include <media/nbaio/AudioStreamOutSink.h>
46#include <media/nbaio/MonoPipe.h>
47#include <media/nbaio/MonoPipeReader.h>
48#include <media/nbaio/Pipe.h>
49#include <media/nbaio/PipeReader.h>
50#include <media/nbaio/SourceAudioBufferProvider.h>
51
52#include <powermanager/PowerManager.h>
53
54#include <common_time/cc_helper.h>
55#include <common_time/local_clock.h>
56
57#include "AudioFlinger.h"
58#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070059#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
63#include "SchedulingPolicyService.h"
64
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
75// ----------------------------------------------------------------------------
76
77// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
89
Andy Hung6770c6f2015-04-07 13:43:36 -070090// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070091#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070092template <typename T>
93static inline T min(const T& a, const T& b)
94{
95 return a < b ? a : b;
96}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070097
Andy Hungd330ee42015-04-20 13:23:41 -070098#ifndef ARRAY_SIZE
99#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
100#endif
101
Eric Laurent81784c32012-11-19 14:55:58 -0800102namespace android {
103
104// retry counts for buffer fill timeout
105// 50 * ~20msecs = 1 second
106static const int8_t kMaxTrackRetries = 50;
107static const int8_t kMaxTrackStartupRetries = 50;
108// allow less retry attempts on direct output thread.
109// direct outputs can be a scarce resource in audio hardware and should
110// be released as quickly as possible.
111static const int8_t kMaxTrackRetriesDirect = 2;
112
113// don't warn about blocked writes or record buffer overflows more often than this
114static const nsecs_t kWarningThrottleNs = seconds(5);
115
116// RecordThread loop sleep time upon application overrun or audio HAL read error
117static const int kRecordThreadSleepUs = 5000;
118
Eric Laurent10351942014-05-08 18:49:52 -0700119// maximum time to wait in sendConfigEvent_l() for a status to be received
120static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// minimum sleep time for the mixer thread loop when tracks are active but in underrun
123static const uint32_t kMinThreadSleepTimeUs = 5000;
124// maximum divider applied to the active sleep time in the mixer thread loop
125static const uint32_t kMaxThreadSleepTimeShift = 2;
126
Andy Hung09a50072014-02-27 14:30:47 -0800127// minimum normal sink buffer size, expressed in milliseconds rather than frames
128static const uint32_t kMinNormalSinkBufferSizeMs = 20;
129// maximum normal sink buffer size
130static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800131
Eric Laurent972a1732013-09-04 09:42:59 -0700132// Offloaded output thread standby delay: allows track transition without going to standby
133static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// Whether to use fast mixer
136static const enum {
137 FastMixer_Never, // never initialize or use: for debugging only
138 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
139 // normal mixer multiplier is 1
140 FastMixer_Static, // initialize if needed, then use all the time if initialized,
141 // multiplier is calculated based on min & max normal mixer buffer size
142 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
143 // multiplier is calculated based on min & max normal mixer buffer size
144 // FIXME for FastMixer_Dynamic:
145 // Supporting this option will require fixing HALs that can't handle large writes.
146 // For example, one HAL implementation returns an error from a large write,
147 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
148 // We could either fix the HAL implementations, or provide a wrapper that breaks
149 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
150} kUseFastMixer = FastMixer_Static;
151
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700152// Whether to use fast capture
153static const enum {
154 FastCapture_Never, // never initialize or use: for debugging only
155 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
156 FastCapture_Static, // initialize if needed, then use all the time if initialized
157} kUseFastCapture = FastCapture_Static;
158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Priorities for requestPriority
160static const int kPriorityAudioApp = 2;
161static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
165// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800166// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
167// So for now we just assume that client is double-buffered for fast tracks.
168// FIXME It would be better for client to tell AudioFlinger the value of N,
169// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800170// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700171
172// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800173static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasten03490092014-05-27 12:30:54 -0700175// The minimum and maximum allowed values
176static const int kFastTrackMultiplierMin = 1;
177static const int kFastTrackMultiplierMax = 2;
178
179// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
180static int sFastTrackMultiplier = kFastTrackMultiplier;
181
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700182// See Thread::readOnlyHeap().
183// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
184// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
185// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700186static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// ----------------------------------------------------------------------------
189
Glenn Kasten03490092014-05-27 12:30:54 -0700190static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
191
192static void sFastTrackMultiplierInit()
193{
194 char value[PROPERTY_VALUE_MAX];
195 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
196 char *endptr;
197 unsigned long ul = strtoul(value, &endptr, 0);
198 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
199 sFastTrackMultiplier = (int) ul;
200 }
201 }
202}
203
204// ----------------------------------------------------------------------------
205
Eric Laurent81784c32012-11-19 14:55:58 -0800206#ifdef ADD_BATTERY_DATA
207// To collect the amplifier usage
208static void addBatteryData(uint32_t params) {
209 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
210 if (service == NULL) {
211 // it already logged
212 return;
213 }
214
215 service->addBatteryData(params);
216}
217#endif
218
219
220// ----------------------------------------------------------------------------
221// CPU Stats
222// ----------------------------------------------------------------------------
223
224class CpuStats {
225public:
226 CpuStats();
227 void sample(const String8 &title);
228#ifdef DEBUG_CPU_USAGE
229private:
230 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
231 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
232
233 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
234
235 int mCpuNum; // thread's current CPU number
236 int mCpukHz; // frequency of thread's current CPU in kHz
237#endif
238};
239
240CpuStats::CpuStats()
241#ifdef DEBUG_CPU_USAGE
242 : mCpuNum(-1), mCpukHz(-1)
243#endif
244{
245}
246
Glenn Kasten0f11b512014-01-31 16:18:54 -0800247void CpuStats::sample(const String8 &title
248#ifndef DEBUG_CPU_USAGE
249 __unused
250#endif
251 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800252#ifdef DEBUG_CPU_USAGE
253 // get current thread's delta CPU time in wall clock ns
254 double wcNs;
255 bool valid = mCpuUsage.sampleAndEnable(wcNs);
256
257 // record sample for wall clock statistics
258 if (valid) {
259 mWcStats.sample(wcNs);
260 }
261
262 // get the current CPU number
263 int cpuNum = sched_getcpu();
264
265 // get the current CPU frequency in kHz
266 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
267
268 // check if either CPU number or frequency changed
269 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
270 mCpuNum = cpuNum;
271 mCpukHz = cpukHz;
272 // ignore sample for purposes of cycles
273 valid = false;
274 }
275
276 // if no change in CPU number or frequency, then record sample for cycle statistics
277 if (valid && mCpukHz > 0) {
278 double cycles = wcNs * cpukHz * 0.000001;
279 mHzStats.sample(cycles);
280 }
281
282 unsigned n = mWcStats.n();
283 // mCpuUsage.elapsed() is expensive, so don't call it every loop
284 if ((n & 127) == 1) {
285 long long elapsed = mCpuUsage.elapsed();
286 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
287 double perLoop = elapsed / (double) n;
288 double perLoop100 = perLoop * 0.01;
289 double perLoop1k = perLoop * 0.001;
290 double mean = mWcStats.mean();
291 double stddev = mWcStats.stddev();
292 double minimum = mWcStats.minimum();
293 double maximum = mWcStats.maximum();
294 double meanCycles = mHzStats.mean();
295 double stddevCycles = mHzStats.stddev();
296 double minCycles = mHzStats.minimum();
297 double maxCycles = mHzStats.maximum();
298 mCpuUsage.resetElapsed();
299 mWcStats.reset();
300 mHzStats.reset();
301 ALOGD("CPU usage for %s over past %.1f secs\n"
302 " (%u mixer loops at %.1f mean ms per loop):\n"
303 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
304 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
305 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
306 title.string(),
307 elapsed * .000000001, n, perLoop * .000001,
308 mean * .001,
309 stddev * .001,
310 minimum * .001,
311 maximum * .001,
312 mean / perLoop100,
313 stddev / perLoop100,
314 minimum / perLoop100,
315 maximum / perLoop100,
316 meanCycles / perLoop1k,
317 stddevCycles / perLoop1k,
318 minCycles / perLoop1k,
319 maxCycles / perLoop1k);
320
321 }
322 }
323#endif
324};
325
326// ----------------------------------------------------------------------------
327// ThreadBase
328// ----------------------------------------------------------------------------
329
Glenn Kasten97b7b752014-09-28 13:04:24 -0700330// static
331const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
332{
333 switch (type) {
334 case MIXER:
335 return "MIXER";
336 case DIRECT:
337 return "DIRECT";
338 case DUPLICATING:
339 return "DUPLICATING";
340 case RECORD:
341 return "RECORD";
342 case OFFLOAD:
343 return "OFFLOAD";
344 default:
345 return "unknown";
346 }
347}
348
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800349String8 devicesToString(audio_devices_t devices)
350{
351 static const struct mapping {
352 audio_devices_t mDevices;
353 const char * mString;
354 } mappingsOut[] = {
355 AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE",
356 AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER",
357 AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET",
358 AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE",
359 AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX",
360 AUDIO_DEVICE_NONE, "NONE", // must be last
361 }, mappingsIn[] = {
362 AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC",
363 AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET",
364 AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL",
365 AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX",
366 AUDIO_DEVICE_NONE, "NONE", // must be last
367 };
368 String8 result;
369 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
370 const mapping *entry;
371 if (devices & AUDIO_DEVICE_BIT_IN) {
372 devices &= ~AUDIO_DEVICE_BIT_IN;
373 entry = mappingsIn;
374 } else {
375 entry = mappingsOut;
376 }
377 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
378 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
379 if (devices & entry->mDevices) {
380 if (!result.isEmpty()) {
381 result.append("|");
382 }
383 result.append(entry->mString);
384 }
385 }
386 if (devices & ~allDevices) {
387 if (!result.isEmpty()) {
388 result.append("|");
389 }
390 result.appendFormat("0x%X", devices & ~allDevices);
391 }
392 if (result.isEmpty()) {
393 result.append(entry->mString);
394 }
395 return result;
396}
397
398String8 inputFlagsToString(audio_input_flags_t flags)
399{
400 static const struct mapping {
401 audio_input_flags_t mFlag;
402 const char * mString;
403 } mappings[] = {
404 AUDIO_INPUT_FLAG_FAST, "FAST",
405 AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD",
406 AUDIO_INPUT_FLAG_NONE, "NONE", // must be last
407 };
408 String8 result;
409 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
410 const mapping *entry;
411 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
412 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
413 if (flags & entry->mFlag) {
414 if (!result.isEmpty()) {
415 result.append("|");
416 }
417 result.append(entry->mString);
418 }
419 }
420 if (flags & ~allFlags) {
421 if (!result.isEmpty()) {
422 result.append("|");
423 }
424 result.appendFormat("0x%X", flags & ~allFlags);
425 }
426 if (result.isEmpty()) {
427 result.append(entry->mString);
428 }
429 return result;
430}
431
432String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700433{
434 static const struct mapping {
435 audio_output_flags_t mFlag;
436 const char * mString;
437 } mappings[] = {
438 AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT",
439 AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY",
440 AUDIO_OUTPUT_FLAG_FAST, "FAST",
441 AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER",
Glenn Kastendfb0e112015-02-18 14:33:39 -0800442 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD, "COMPRESS_OFFLOAD",
Glenn Kasten97b7b752014-09-28 13:04:24 -0700443 AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING",
444 AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC",
445 AUDIO_OUTPUT_FLAG_NONE, "NONE", // must be last
446 };
447 String8 result;
448 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
449 const mapping *entry;
450 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
451 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
452 if (flags & entry->mFlag) {
453 if (!result.isEmpty()) {
454 result.append("|");
455 }
456 result.append(entry->mString);
457 }
458 }
459 if (flags & ~allFlags) {
460 if (!result.isEmpty()) {
461 result.append("|");
462 }
463 result.appendFormat("0x%X", flags & ~allFlags);
464 }
465 if (result.isEmpty()) {
466 result.append(entry->mString);
467 }
468 return result;
469}
470
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471const char *sourceToString(audio_source_t source)
472{
473 switch (source) {
474 case AUDIO_SOURCE_DEFAULT: return "default";
475 case AUDIO_SOURCE_MIC: return "mic";
476 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
477 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
478 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
479 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
480 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
481 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
482 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
483 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
484 case AUDIO_SOURCE_HOTWORD: return "hotword";
485 default: return "unknown";
486 }
487}
488
Eric Laurent81784c32012-11-19 14:55:58 -0800489AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
490 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
491 : Thread(false /*canCallJava*/),
492 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700493 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700494 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800495 // are set by PlaybackThread::readOutputParameters_l() or
496 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700497 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800498 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
499 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
500 // mName will be set by concrete (non-virtual) subclass
501 mDeathRecipient(new PMDeathRecipient(this))
502{
503}
504
505AudioFlinger::ThreadBase::~ThreadBase()
506{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700507 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700508 mConfigEvents.clear();
509
Eric Laurent81784c32012-11-19 14:55:58 -0800510 // do not lock the mutex in destructor
511 releaseWakeLock_l();
512 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800513 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800514 binder->unlinkToDeath(mDeathRecipient);
515 }
516}
517
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700518status_t AudioFlinger::ThreadBase::readyToRun()
519{
520 status_t status = initCheck();
521 if (status == NO_ERROR) {
522 ALOGI("AudioFlinger's thread %p ready to run", this);
523 } else {
524 ALOGE("No working audio driver found.");
525 }
526 return status;
527}
528
Eric Laurent81784c32012-11-19 14:55:58 -0800529void AudioFlinger::ThreadBase::exit()
530{
531 ALOGV("ThreadBase::exit");
532 // do any cleanup required for exit to succeed
533 preExit();
534 {
535 // This lock prevents the following race in thread (uniprocessor for illustration):
536 // if (!exitPending()) {
537 // // context switch from here to exit()
538 // // exit() calls requestExit(), what exitPending() observes
539 // // exit() calls signal(), which is dropped since no waiters
540 // // context switch back from exit() to here
541 // mWaitWorkCV.wait(...);
542 // // now thread is hung
543 // }
544 AutoMutex lock(mLock);
545 requestExit();
546 mWaitWorkCV.broadcast();
547 }
548 // When Thread::requestExitAndWait is made virtual and this method is renamed to
549 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
550 requestExitAndWait();
551}
552
553status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
554{
555 status_t status;
556
557 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
558 Mutex::Autolock _l(mLock);
559
Eric Laurent10351942014-05-08 18:49:52 -0700560 return sendSetParameterConfigEvent_l(keyValuePairs);
561}
562
563// sendConfigEvent_l() must be called with ThreadBase::mLock held
564// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
565status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
566{
567 status_t status = NO_ERROR;
568
569 mConfigEvents.add(event);
570 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800571 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700572 mLock.unlock();
573 {
574 Mutex::Autolock _l(event->mLock);
575 while (event->mWaitStatus) {
576 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
577 event->mStatus = TIMED_OUT;
578 event->mWaitStatus = false;
579 }
580 }
581 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800582 }
Eric Laurent10351942014-05-08 18:49:52 -0700583 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800584 return status;
585}
586
587void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
588{
589 Mutex::Autolock _l(mLock);
590 sendIoConfigEvent_l(event, param);
591}
592
593// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
594void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
595{
Eric Laurent10351942014-05-08 18:49:52 -0700596 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, param);
597 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800598}
599
600// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
601void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
602{
Eric Laurent10351942014-05-08 18:49:52 -0700603 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
604 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800605}
606
Eric Laurent10351942014-05-08 18:49:52 -0700607// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
608status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800609{
Eric Laurent10351942014-05-08 18:49:52 -0700610 sp<ConfigEvent> configEvent = (ConfigEvent *)new SetParameterConfigEvent(keyValuePair);
611 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700612}
613
Eric Laurent1c333e22014-05-20 10:48:17 -0700614status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
615 const struct audio_patch *patch,
616 audio_patch_handle_t *handle)
617{
618 Mutex::Autolock _l(mLock);
619 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
620 status_t status = sendConfigEvent_l(configEvent);
621 if (status == NO_ERROR) {
622 CreateAudioPatchConfigEventData *data =
623 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
624 *handle = data->mHandle;
625 }
626 return status;
627}
628
629status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
630 const audio_patch_handle_t handle)
631{
632 Mutex::Autolock _l(mLock);
633 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
634 return sendConfigEvent_l(configEvent);
635}
636
637
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700638// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700639void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700640{
Eric Laurent10351942014-05-08 18:49:52 -0700641 bool configChanged = false;
642
Eric Laurent81784c32012-11-19 14:55:58 -0800643 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700644 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
645 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800646 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700647 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700648 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700649 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
650 // FIXME Need to understand why this has to be done asynchronously
651 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700652 true /*asynchronous*/);
653 if (err != 0) {
654 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700655 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700656 }
657 } break;
658 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700659 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent021cf962014-05-13 10:18:14 -0700660 audioConfigChanged(data->mEvent, data->mParam);
Eric Laurent10351942014-05-08 18:49:52 -0700661 } break;
662 case CFG_EVENT_SET_PARAMETER: {
663 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
664 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
665 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700666 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700667 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700668 case CFG_EVENT_CREATE_AUDIO_PATCH: {
669 CreateAudioPatchConfigEventData *data =
670 (CreateAudioPatchConfigEventData *)event->mData.get();
671 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
672 } break;
673 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
674 ReleaseAudioPatchConfigEventData *data =
675 (ReleaseAudioPatchConfigEventData *)event->mData.get();
676 event->mStatus = releaseAudioPatch_l(data->mHandle);
677 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700678 default:
Eric Laurent10351942014-05-08 18:49:52 -0700679 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700680 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800681 }
Eric Laurent10351942014-05-08 18:49:52 -0700682 {
683 Mutex::Autolock _l(event->mLock);
684 if (event->mWaitStatus) {
685 event->mWaitStatus = false;
686 event->mCond.signal();
687 }
688 }
689 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
690 }
691
692 if (configChanged) {
693 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
Eric Laurent81784c32012-11-19 14:55:58 -0800695}
696
Marco Nelissenb2208842014-02-07 14:00:50 -0800697String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
698 String8 s;
699 if (output) {
700 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
701 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
702 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
703 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
704 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
705 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
706 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
707 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
708 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
709 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
710 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
711 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
712 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
713 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
714 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
715 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
716 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
717 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
718 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
719 } else {
720 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
721 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
722 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
723 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
724 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
725 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
726 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
727 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
728 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
729 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
730 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
731 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
732 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
733 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
734 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
735 }
736 int len = s.length();
737 if (s.length() > 2) {
738 char *str = s.lockBuffer(len);
739 s.unlockBuffer(len - 2);
740 }
741 return s;
742}
743
Glenn Kasten0f11b512014-01-31 16:18:54 -0800744void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800745{
746 const size_t SIZE = 256;
747 char buffer[SIZE];
748 String8 result;
749
750 bool locked = AudioFlinger::dumpTryLock(mLock);
751 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700752 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800753 }
754
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800755 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700756 dprintf(fd, " I/O handle: %d\n", mId);
757 dprintf(fd, " TID: %d\n", getTid());
758 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700759 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700760 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700761 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700762 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700763 dprintf(fd, " Channel count: %u\n", mChannelCount);
764 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800765 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kasten97b7b752014-09-28 13:04:24 -0700766 dprintf(fd, " Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
767 dprintf(fd, " Frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700768 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800769 size_t numConfig = mConfigEvents.size();
770 if (numConfig) {
771 for (size_t i = 0; i < numConfig; i++) {
772 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700773 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800774 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700775 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800776 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700777 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800778 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800779 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
780 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
781 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800782
783 if (locked) {
784 mLock.unlock();
785 }
786}
787
788void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
789{
790 const size_t SIZE = 256;
791 char buffer[SIZE];
792 String8 result;
793
Marco Nelissenb2208842014-02-07 14:00:50 -0800794 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000795 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800796 write(fd, buffer, strlen(buffer));
797
Marco Nelissenb2208842014-02-07 14:00:50 -0800798 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800799 sp<EffectChain> chain = mEffectChains[i];
800 if (chain != 0) {
801 chain->dump(fd, args);
802 }
803 }
804}
805
Marco Nelissene14a5d62013-10-03 08:51:24 -0700806void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800807{
808 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700809 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -0800810}
811
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100812String16 AudioFlinger::ThreadBase::getWakeLockTag()
813{
814 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800815 case MIXER:
816 return String16("AudioMix");
817 case DIRECT:
818 return String16("AudioDirectOut");
819 case DUPLICATING:
820 return String16("AudioDup");
821 case RECORD:
822 return String16("AudioIn");
823 case OFFLOAD:
824 return String16("AudioOffload");
825 default:
826 ALOG_ASSERT(false);
827 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100828 }
829}
830
Marco Nelissene14a5d62013-10-03 08:51:24 -0700831void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800832{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800833 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800834 if (mPowerManager != 0) {
835 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -0700836 status_t status;
837 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -0700838 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700839 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100840 getWakeLockTag(),
Marco Nelissene14a5d62013-10-03 08:51:24 -0700841 String16("media"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700842 uid,
843 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700844 } else {
Eric Laurent547789d2013-10-04 11:46:55 -0700845 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700846 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100847 getWakeLockTag(),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700848 String16("media"),
849 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -0700850 }
Eric Laurent81784c32012-11-19 14:55:58 -0800851 if (status == NO_ERROR) {
852 mWakeLockToken = binder;
853 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800854 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800855 }
856}
857
858void AudioFlinger::ThreadBase::releaseWakeLock()
859{
860 Mutex::Autolock _l(mLock);
861 releaseWakeLock_l();
862}
863
864void AudioFlinger::ThreadBase::releaseWakeLock_l()
865{
866 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800867 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800868 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700869 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
870 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800871 }
872 mWakeLockToken.clear();
873 }
874}
875
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800876void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
877 Mutex::Autolock _l(mLock);
878 updateWakeLockUids_l(uids);
879}
880
881void AudioFlinger::ThreadBase::getPowerManager_l() {
882
883 if (mPowerManager == 0) {
884 // use checkService() to avoid blocking if power service is not up yet
885 sp<IBinder> binder =
886 defaultServiceManager()->checkService(String16("power"));
887 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800888 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800889 } else {
890 mPowerManager = interface_cast<IPowerManager>(binder);
891 binder->linkToDeath(mDeathRecipient);
892 }
893 }
894}
895
896void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
897
898 getPowerManager_l();
899 if (mWakeLockToken == NULL) {
900 ALOGE("no wake lock to update!");
901 return;
902 }
903 if (mPowerManager != 0) {
904 sp<IBinder> binder = new BBinder();
905 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700906 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
907 true /* FIXME force oneway contrary to .aidl */);
Glenn Kastend7dca052015-03-05 16:05:54 -0800908 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800909 }
910}
911
Eric Laurent81784c32012-11-19 14:55:58 -0800912void AudioFlinger::ThreadBase::clearPowerManager()
913{
914 Mutex::Autolock _l(mLock);
915 releaseWakeLock_l();
916 mPowerManager.clear();
917}
918
Glenn Kasten0f11b512014-01-31 16:18:54 -0800919void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800920{
921 sp<ThreadBase> thread = mThread.promote();
922 if (thread != 0) {
923 thread->clearPowerManager();
924 }
925 ALOGW("power manager service died !!!");
926}
927
928void AudioFlinger::ThreadBase::setEffectSuspended(
929 const effect_uuid_t *type, bool suspend, int sessionId)
930{
931 Mutex::Autolock _l(mLock);
932 setEffectSuspended_l(type, suspend, sessionId);
933}
934
935void AudioFlinger::ThreadBase::setEffectSuspended_l(
936 const effect_uuid_t *type, bool suspend, int sessionId)
937{
938 sp<EffectChain> chain = getEffectChain_l(sessionId);
939 if (chain != 0) {
940 if (type != NULL) {
941 chain->setEffectSuspended_l(type, suspend);
942 } else {
943 chain->setEffectSuspendedAll_l(suspend);
944 }
945 }
946
947 updateSuspendedSessions_l(type, suspend, sessionId);
948}
949
950void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
951{
952 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
953 if (index < 0) {
954 return;
955 }
956
957 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
958 mSuspendedSessions.valueAt(index);
959
960 for (size_t i = 0; i < sessionEffects.size(); i++) {
961 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
962 for (int j = 0; j < desc->mRefCount; j++) {
963 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
964 chain->setEffectSuspendedAll_l(true);
965 } else {
966 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
967 desc->mType.timeLow);
968 chain->setEffectSuspended_l(&desc->mType, true);
969 }
970 }
971 }
972}
973
974void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
975 bool suspend,
976 int sessionId)
977{
978 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
979
980 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
981
982 if (suspend) {
983 if (index >= 0) {
984 sessionEffects = mSuspendedSessions.valueAt(index);
985 } else {
986 mSuspendedSessions.add(sessionId, sessionEffects);
987 }
988 } else {
989 if (index < 0) {
990 return;
991 }
992 sessionEffects = mSuspendedSessions.valueAt(index);
993 }
994
995
996 int key = EffectChain::kKeyForSuspendAll;
997 if (type != NULL) {
998 key = type->timeLow;
999 }
1000 index = sessionEffects.indexOfKey(key);
1001
1002 sp<SuspendedSessionDesc> desc;
1003 if (suspend) {
1004 if (index >= 0) {
1005 desc = sessionEffects.valueAt(index);
1006 } else {
1007 desc = new SuspendedSessionDesc();
1008 if (type != NULL) {
1009 desc->mType = *type;
1010 }
1011 sessionEffects.add(key, desc);
1012 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1013 }
1014 desc->mRefCount++;
1015 } else {
1016 if (index < 0) {
1017 return;
1018 }
1019 desc = sessionEffects.valueAt(index);
1020 if (--desc->mRefCount == 0) {
1021 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1022 sessionEffects.removeItemsAt(index);
1023 if (sessionEffects.isEmpty()) {
1024 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1025 sessionId);
1026 mSuspendedSessions.removeItem(sessionId);
1027 }
1028 }
1029 }
1030 if (!sessionEffects.isEmpty()) {
1031 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1032 }
1033}
1034
1035void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1036 bool enabled,
1037 int sessionId)
1038{
1039 Mutex::Autolock _l(mLock);
1040 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1041}
1042
1043void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1044 bool enabled,
1045 int sessionId)
1046{
1047 if (mType != RECORD) {
1048 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1049 // another session. This gives the priority to well behaved effect control panels
1050 // and applications not using global effects.
1051 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1052 // global effects
1053 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1054 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1055 }
1056 }
1057
1058 sp<EffectChain> chain = getEffectChain_l(sessionId);
1059 if (chain != 0) {
1060 chain->checkSuspendOnEffectEnabled(effect, enabled);
1061 }
1062}
1063
1064// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1065sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1066 const sp<AudioFlinger::Client>& client,
1067 const sp<IEffectClient>& effectClient,
1068 int32_t priority,
1069 int sessionId,
1070 effect_descriptor_t *desc,
1071 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001072 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001073{
1074 sp<EffectModule> effect;
1075 sp<EffectHandle> handle;
1076 status_t lStatus;
1077 sp<EffectChain> chain;
1078 bool chainCreated = false;
1079 bool effectCreated = false;
1080 bool effectRegistered = false;
1081
1082 lStatus = initCheck();
1083 if (lStatus != NO_ERROR) {
1084 ALOGW("createEffect_l() Audio driver not initialized.");
1085 goto Exit;
1086 }
1087
Andy Hung98ef9782014-03-04 14:46:50 -08001088 // Reject any effect on Direct output threads for now, since the format of
1089 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1090 if (mType == DIRECT) {
1091 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001092 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001093 lStatus = BAD_VALUE;
1094 goto Exit;
1095 }
1096
Andy Hung389cfdb2014-08-07 17:49:53 -07001097 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001098 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001099 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1100 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1101 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001102 lStatus = BAD_VALUE;
1103 goto Exit;
1104 }
1105
Eric Laurent5baf2af2013-09-12 17:37:00 -07001106 // Allow global effects only on offloaded and mixer threads
1107 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1108 switch (mType) {
1109 case MIXER:
1110 case OFFLOAD:
1111 break;
1112 case DIRECT:
1113 case DUPLICATING:
1114 case RECORD:
1115 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001116 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1117 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001118 lStatus = BAD_VALUE;
1119 goto Exit;
1120 }
Eric Laurent81784c32012-11-19 14:55:58 -08001121 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001122
Eric Laurent81784c32012-11-19 14:55:58 -08001123 // Only Pre processor effects are allowed on input threads and only on input threads
1124 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1125 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1126 desc->name, desc->flags, mType);
1127 lStatus = BAD_VALUE;
1128 goto Exit;
1129 }
1130
1131 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1132
1133 { // scope for mLock
1134 Mutex::Autolock _l(mLock);
1135
1136 // check for existing effect chain with the requested audio session
1137 chain = getEffectChain_l(sessionId);
1138 if (chain == 0) {
1139 // create a new chain for this session
1140 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1141 chain = new EffectChain(this, sessionId);
1142 addEffectChain_l(chain);
1143 chain->setStrategy(getStrategyForSession_l(sessionId));
1144 chainCreated = true;
1145 } else {
1146 effect = chain->getEffectFromDesc_l(desc);
1147 }
1148
1149 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1150
1151 if (effect == 0) {
1152 int id = mAudioFlinger->nextUniqueId();
1153 // Check CPU and memory usage
1154 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1155 if (lStatus != NO_ERROR) {
1156 goto Exit;
1157 }
1158 effectRegistered = true;
1159 // create a new effect module if none present in the chain
1160 effect = new EffectModule(this, chain, desc, id, sessionId);
1161 lStatus = effect->status();
1162 if (lStatus != NO_ERROR) {
1163 goto Exit;
1164 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001165 effect->setOffloaded(mType == OFFLOAD, mId);
1166
Eric Laurent81784c32012-11-19 14:55:58 -08001167 lStatus = chain->addEffect_l(effect);
1168 if (lStatus != NO_ERROR) {
1169 goto Exit;
1170 }
1171 effectCreated = true;
1172
1173 effect->setDevice(mOutDevice);
1174 effect->setDevice(mInDevice);
1175 effect->setMode(mAudioFlinger->getMode());
1176 effect->setAudioSource(mAudioSource);
1177 }
1178 // create effect handle and connect it to effect module
1179 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001180 lStatus = handle->initCheck();
1181 if (lStatus == OK) {
1182 lStatus = effect->addHandle(handle.get());
1183 }
Eric Laurent81784c32012-11-19 14:55:58 -08001184 if (enabled != NULL) {
1185 *enabled = (int)effect->isEnabled();
1186 }
1187 }
1188
1189Exit:
1190 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1191 Mutex::Autolock _l(mLock);
1192 if (effectCreated) {
1193 chain->removeEffect_l(effect);
1194 }
1195 if (effectRegistered) {
1196 AudioSystem::unregisterEffect(effect->id());
1197 }
1198 if (chainCreated) {
1199 removeEffectChain_l(chain);
1200 }
1201 handle.clear();
1202 }
1203
Glenn Kasten9156ef32013-08-06 15:39:08 -07001204 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001205 return handle;
1206}
1207
1208sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1209{
1210 Mutex::Autolock _l(mLock);
1211 return getEffect_l(sessionId, effectId);
1212}
1213
1214sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1215{
1216 sp<EffectChain> chain = getEffectChain_l(sessionId);
1217 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1218}
1219
1220// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1221// PlaybackThread::mLock held
1222status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1223{
1224 // check for existing effect chain with the requested audio session
1225 int sessionId = effect->sessionId();
1226 sp<EffectChain> chain = getEffectChain_l(sessionId);
1227 bool chainCreated = false;
1228
Eric Laurent5baf2af2013-09-12 17:37:00 -07001229 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1230 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1231 this, effect->desc().name, effect->desc().flags);
1232
Eric Laurent81784c32012-11-19 14:55:58 -08001233 if (chain == 0) {
1234 // create a new chain for this session
1235 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1236 chain = new EffectChain(this, sessionId);
1237 addEffectChain_l(chain);
1238 chain->setStrategy(getStrategyForSession_l(sessionId));
1239 chainCreated = true;
1240 }
1241 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1242
1243 if (chain->getEffectFromId_l(effect->id()) != 0) {
1244 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1245 this, effect->desc().name, chain.get());
1246 return BAD_VALUE;
1247 }
1248
Eric Laurent5baf2af2013-09-12 17:37:00 -07001249 effect->setOffloaded(mType == OFFLOAD, mId);
1250
Eric Laurent81784c32012-11-19 14:55:58 -08001251 status_t status = chain->addEffect_l(effect);
1252 if (status != NO_ERROR) {
1253 if (chainCreated) {
1254 removeEffectChain_l(chain);
1255 }
1256 return status;
1257 }
1258
1259 effect->setDevice(mOutDevice);
1260 effect->setDevice(mInDevice);
1261 effect->setMode(mAudioFlinger->getMode());
1262 effect->setAudioSource(mAudioSource);
1263 return NO_ERROR;
1264}
1265
1266void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1267
1268 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1269 effect_descriptor_t desc = effect->desc();
1270 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1271 detachAuxEffect_l(effect->id());
1272 }
1273
1274 sp<EffectChain> chain = effect->chain().promote();
1275 if (chain != 0) {
1276 // remove effect chain if removing last effect
1277 if (chain->removeEffect_l(effect) == 0) {
1278 removeEffectChain_l(chain);
1279 }
1280 } else {
1281 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1282 }
1283}
1284
1285void AudioFlinger::ThreadBase::lockEffectChains_l(
1286 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1287{
1288 effectChains = mEffectChains;
1289 for (size_t i = 0; i < mEffectChains.size(); i++) {
1290 mEffectChains[i]->lock();
1291 }
1292}
1293
1294void AudioFlinger::ThreadBase::unlockEffectChains(
1295 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1296{
1297 for (size_t i = 0; i < effectChains.size(); i++) {
1298 effectChains[i]->unlock();
1299 }
1300}
1301
1302sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1303{
1304 Mutex::Autolock _l(mLock);
1305 return getEffectChain_l(sessionId);
1306}
1307
1308sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1309{
1310 size_t size = mEffectChains.size();
1311 for (size_t i = 0; i < size; i++) {
1312 if (mEffectChains[i]->sessionId() == sessionId) {
1313 return mEffectChains[i];
1314 }
1315 }
1316 return 0;
1317}
1318
1319void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1320{
1321 Mutex::Autolock _l(mLock);
1322 size_t size = mEffectChains.size();
1323 for (size_t i = 0; i < size; i++) {
1324 mEffectChains[i]->setMode_l(mode);
1325 }
1326}
1327
Eric Laurent83b88082014-06-20 18:31:16 -07001328void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1329{
1330 config->type = AUDIO_PORT_TYPE_MIX;
1331 config->ext.mix.handle = mId;
1332 config->sample_rate = mSampleRate;
1333 config->format = mFormat;
1334 config->channel_mask = mChannelMask;
1335 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1336 AUDIO_PORT_CONFIG_FORMAT;
1337}
1338
1339
Eric Laurent81784c32012-11-19 14:55:58 -08001340// ----------------------------------------------------------------------------
1341// Playback
1342// ----------------------------------------------------------------------------
1343
1344AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1345 AudioStreamOut* output,
1346 audio_io_handle_t id,
1347 audio_devices_t device,
1348 type_t type)
1349 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Andy Hung2098f272014-02-27 14:00:06 -08001350 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001351 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001352 mMixerBuffer(NULL),
1353 mMixerBufferSize(0),
1354 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1355 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001356 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001357 mEffectBuffer(NULL),
1358 mEffectBufferSize(0),
1359 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1360 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001361 mSuspended(0), mBytesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001362 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001363 // mStreamTypes[] initialized in constructor body
1364 mOutput(output),
1365 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1366 mMixerStatus(MIXER_IDLE),
1367 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
1368 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001369 mBytesRemaining(0),
1370 mCurrentWriteLength(0),
1371 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001372 mWriteAckSequence(0),
1373 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001374 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001375 mScreenState(AudioFlinger::mScreenState),
1376 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001377 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Eric Laurentd1f69b02014-12-15 14:33:13 -08001378 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001379 // mLatchD, mLatchQ,
1380 mLatchDValid(false), mLatchQValid(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001381{
Glenn Kastend7dca052015-03-05 16:05:54 -08001382 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1383 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001384
1385 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1386 // it would be safer to explicitly pass initial masterVolume/masterMute as
1387 // parameter.
1388 //
1389 // If the HAL we are using has support for master volume or master mute,
1390 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1391 // and the mute set to false).
1392 mMasterVolume = audioFlinger->masterVolume_l();
1393 mMasterMute = audioFlinger->masterMute_l();
1394 if (mOutput && mOutput->audioHwDev) {
1395 if (mOutput->audioHwDev->canSetMasterVolume()) {
1396 mMasterVolume = 1.0;
1397 }
1398
1399 if (mOutput->audioHwDev->canSetMasterMute()) {
1400 mMasterMute = false;
1401 }
1402 }
1403
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001404 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001405
Eric Laurent223fd5c2014-11-11 13:43:36 -08001406 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001407 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001408 stream = (audio_stream_type_t) (stream + 1)) {
1409 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1410 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1411 }
Eric Laurent81784c32012-11-19 14:55:58 -08001412}
1413
1414AudioFlinger::PlaybackThread::~PlaybackThread()
1415{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001416 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001417 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001418 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001419 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001420}
1421
1422void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1423{
1424 dumpInternals(fd, args);
1425 dumpTracks(fd, args);
1426 dumpEffectChains(fd, args);
1427}
1428
Glenn Kasten0f11b512014-01-31 16:18:54 -08001429void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001430{
1431 const size_t SIZE = 256;
1432 char buffer[SIZE];
1433 String8 result;
1434
Marco Nelissenb2208842014-02-07 14:00:50 -08001435 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001436 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1437 const stream_type_t *st = &mStreamTypes[i];
1438 if (i > 0) {
1439 result.appendFormat(", ");
1440 }
1441 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1442 if (st->mute) {
1443 result.append("M");
1444 }
1445 }
1446 result.append("\n");
1447 write(fd, result.string(), result.length());
1448 result.clear();
1449
Eric Laurent81784c32012-11-19 14:55:58 -08001450 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1451 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001452 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001453 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001454
1455 size_t numtracks = mTracks.size();
1456 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001457 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001458 size_t numactiveseen = 0;
1459 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001460 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001461 Track::appendDumpHeader(result);
1462 for (size_t i = 0; i < numtracks; ++i) {
1463 sp<Track> track = mTracks[i];
1464 if (track != 0) {
1465 bool active = mActiveTracks.indexOf(track) >= 0;
1466 if (active) {
1467 numactiveseen++;
1468 }
1469 track->dump(buffer, SIZE, active);
1470 result.append(buffer);
1471 }
1472 }
1473 } else {
1474 result.append("\n");
1475 }
1476 if (numactiveseen != numactive) {
1477 // some tracks in the active list were not in the tracks list
1478 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1479 " not in the track list\n");
1480 result.append(buffer);
1481 Track::appendDumpHeader(result);
1482 for (size_t i = 0; i < numactive; ++i) {
1483 sp<Track> track = mActiveTracks[i].promote();
1484 if (track != 0 && mTracks.indexOf(track) < 0) {
1485 track->dump(buffer, SIZE, true);
1486 result.append(buffer);
1487 }
1488 }
1489 }
1490
1491 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001492}
1493
1494void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1495{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001496 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001497
1498 dumpBase(fd, args);
1499
Elliott Hughes87cebad2014-05-22 10:14:43 -07001500 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1501 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1502 dprintf(fd, " Total writes: %d\n", mNumWrites);
1503 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1504 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1505 dprintf(fd, " Suspend count: %d\n", mSuspended);
1506 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1507 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1508 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1509 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001510 AudioStreamOut *output = mOutput;
1511 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1512 String8 flagsAsString = outputFlagsToString(flags);
1513 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001514}
1515
1516// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001517
1518void AudioFlinger::PlaybackThread::onFirstRef()
1519{
Glenn Kastend7dca052015-03-05 16:05:54 -08001520 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001521}
1522
1523// ThreadBase virtuals
1524void AudioFlinger::PlaybackThread::preExit()
1525{
1526 ALOGV(" preExit()");
1527 // FIXME this is using hard-coded strings but in the future, this functionality will be
1528 // converted to use audio HAL extensions required to support tunneling
1529 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1530}
1531
1532// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1533sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1534 const sp<AudioFlinger::Client>& client,
1535 audio_stream_type_t streamType,
1536 uint32_t sampleRate,
1537 audio_format_t format,
1538 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001539 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001540 const sp<IMemory>& sharedBuffer,
1541 int sessionId,
1542 IAudioFlinger::track_flags_t *flags,
1543 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001544 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001545 status_t *status)
1546{
Glenn Kasten74935e42013-12-19 08:56:45 -08001547 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001548 sp<Track> track;
1549 status_t lStatus;
1550
1551 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
1552
1553 // client expresses a preference for FAST, but we get the final say
1554 if (*flags & IAudioFlinger::TRACK_FAST) {
1555 if (
1556 // not timed
1557 (!isTimed) &&
1558 // either of these use cases:
1559 (
1560 // use case 1: shared buffer with any frame count
1561 (
1562 (sharedBuffer != 0)
1563 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001564 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001565 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001566 // we formerly checked for a callback handler (non-0 tid),
1567 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001568 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001569 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001570 )
1571 ) &&
1572 // PCM data
1573 audio_is_linear_pcm(format) &&
Andy Hung9a592762014-07-21 21:56:01 -07001574 // identical channel mask to sink, or mono in and stereo sink
1575 (channelMask == mChannelMask ||
1576 (channelMask == AUDIO_CHANNEL_OUT_MONO &&
1577 mChannelMask == AUDIO_CHANNEL_OUT_STEREO)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001578 // hardware sample rate
1579 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001580 // normal mixer has an associated fast mixer
1581 hasFastMixer() &&
1582 // there are sufficient fast track slots available
1583 (mFastTrackAvailMask != 0)
1584 // FIXME test that MixerThread for this fast track has a capable output HAL
1585 // FIXME add a permission test also?
1586 ) {
1587 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1588 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001589 // read the fast track multiplier property the first time it is needed
1590 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1591 if (ok != 0) {
1592 ALOGE("%s pthread_once failed: %d", __func__, ok);
1593 }
1594 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001595 }
1596 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1597 frameCount, mFrameCount);
1598 } else {
1599 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001600 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1601 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001602 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Andy Hung6146c082014-03-18 11:56:15 -07001603 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001604 audio_is_linear_pcm(format),
1605 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1606 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001607 }
1608 }
1609 // For normal PCM streaming tracks, update minimum frame count.
1610 // For compatibility with AudioTrack calculation, buffer depth is forced
1611 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1612 // This is probably too conservative, but legacy application code may depend on it.
1613 // If you change this calculation, also review the start threshold which is related.
1614 if (!(*flags & IAudioFlinger::TRACK_FAST)
1615 && audio_is_linear_pcm(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001616 // this must match AudioTrack.cpp calculateMinFrameCount().
1617 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001618 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1619 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1620 if (minBufCount < 2) {
1621 minBufCount = 2;
1622 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001623 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1624 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001625 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001626 minBufCount * sourceFramesNeededWithTimestretch(
1627 sampleRate, mNormalFrameCount,
1628 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001629 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001630 frameCount = minFrameCount;
1631 }
Eric Laurent81784c32012-11-19 14:55:58 -08001632 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001633 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001634
Glenn Kastenc3df8382014-03-13 15:05:25 -07001635 switch (mType) {
1636
1637 case DIRECT:
Glenn Kasten993fa062014-05-02 11:14:34 -07001638 if (audio_is_linear_pcm(format)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001639 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001640 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1641 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001642 sampleRate, format, channelMask, mOutput, mFormat);
1643 lStatus = BAD_VALUE;
1644 goto Exit;
1645 }
1646 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001647 break;
1648
1649 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001650 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001651 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1652 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001653 sampleRate, format, channelMask, mOutput, mFormat);
1654 lStatus = BAD_VALUE;
1655 goto Exit;
1656 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001657 break;
1658
1659 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001660 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001661 ALOGE("createTrack_l() Bad parameter: format %#x \""
1662 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663 format, mOutput, mFormat);
1664 lStatus = BAD_VALUE;
1665 goto Exit;
1666 }
Andy Hungcd044842014-08-07 11:04:34 -07001667 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001668 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1669 lStatus = BAD_VALUE;
1670 goto Exit;
1671 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001672 break;
1673
Eric Laurent81784c32012-11-19 14:55:58 -08001674 }
1675
1676 lStatus = initCheck();
1677 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001678 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001679 goto Exit;
1680 }
1681
1682 { // scope for mLock
1683 Mutex::Autolock _l(mLock);
1684
1685 // all tracks in same audio session must share the same routing strategy otherwise
1686 // conflicts will happen when tracks are moved from one output to another by audio policy
1687 // manager
1688 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1689 for (size_t i = 0; i < mTracks.size(); ++i) {
1690 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001691 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001692 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1693 if (sessionId == t->sessionId() && strategy != actual) {
1694 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1695 strategy, actual);
1696 lStatus = BAD_VALUE;
1697 goto Exit;
1698 }
1699 }
1700 }
1701
1702 if (!isTimed) {
1703 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent83b88082014-06-20 18:31:16 -07001704 channelMask, frameCount, NULL, sharedBuffer,
1705 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08001706 } else {
1707 track = TimedTrack::create(this, client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001708 channelMask, frameCount, sharedBuffer, sessionId, uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001709 }
Glenn Kasten03003332013-08-06 15:40:54 -07001710
1711 // new Track always returns non-NULL,
1712 // but TimedTrack::create() is a factory that could fail by returning NULL
1713 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1714 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001715 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001716 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001717 goto Exit;
1718 }
1719 mTracks.add(track);
1720
1721 sp<EffectChain> chain = getEffectChain_l(sessionId);
1722 if (chain != 0) {
1723 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1724 track->setMainBuffer(chain->inBuffer());
1725 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1726 chain->incTrackCnt();
1727 }
1728
1729 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1730 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1731 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1732 // so ask activity manager to do this on our behalf
1733 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1734 }
1735 }
1736
1737 lStatus = NO_ERROR;
1738
1739Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001740 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001741 return track;
1742}
1743
1744uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1745{
1746 return latency;
1747}
1748
1749uint32_t AudioFlinger::PlaybackThread::latency() const
1750{
1751 Mutex::Autolock _l(mLock);
1752 return latency_l();
1753}
1754uint32_t AudioFlinger::PlaybackThread::latency_l() const
1755{
1756 if (initCheck() == NO_ERROR) {
1757 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1758 } else {
1759 return 0;
1760 }
1761}
1762
1763void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1764{
1765 Mutex::Autolock _l(mLock);
1766 // Don't apply master volume in SW if our HAL can do it for us.
1767 if (mOutput && mOutput->audioHwDev &&
1768 mOutput->audioHwDev->canSetMasterVolume()) {
1769 mMasterVolume = 1.0;
1770 } else {
1771 mMasterVolume = value;
1772 }
1773}
1774
1775void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1776{
1777 Mutex::Autolock _l(mLock);
1778 // Don't apply master mute in SW if our HAL can do it for us.
1779 if (mOutput && mOutput->audioHwDev &&
1780 mOutput->audioHwDev->canSetMasterMute()) {
1781 mMasterMute = false;
1782 } else {
1783 mMasterMute = muted;
1784 }
1785}
1786
1787void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1788{
1789 Mutex::Autolock _l(mLock);
1790 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001791 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001792}
1793
1794void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1795{
1796 Mutex::Autolock _l(mLock);
1797 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001798 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001799}
1800
1801float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1802{
1803 Mutex::Autolock _l(mLock);
1804 return mStreamTypes[stream].volume;
1805}
1806
1807// addTrack_l() must be called with ThreadBase::mLock held
1808status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1809{
1810 status_t status = ALREADY_EXISTS;
1811
1812 // set retry count for buffer fill
1813 track->mRetryCount = kMaxTrackStartupRetries;
1814 if (mActiveTracks.indexOf(track) < 0) {
1815 // the track is newly added, make sure it fills up all its
1816 // buffers before playing. This is to ensure the client will
1817 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07001818 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001819 TrackBase::track_state state = track->mState;
1820 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001821 status = AudioSystem::startOutput(mId, track->streamType(),
1822 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001823 mLock.lock();
1824 // abort track was stopped/paused while we released the lock
1825 if (state != track->mState) {
1826 if (status == NO_ERROR) {
1827 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08001828 AudioSystem::stopOutput(mId, track->streamType(),
1829 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001830 mLock.lock();
1831 }
1832 return INVALID_OPERATION;
1833 }
1834 // abort if start is rejected by audio policy manager
1835 if (status != NO_ERROR) {
1836 return PERMISSION_DENIED;
1837 }
1838#ifdef ADD_BATTERY_DATA
1839 // to track the speaker usage
1840 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
1841#endif
1842 }
1843
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001844 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08001845 track->mResetDone = false;
1846 track->mPresentationCompleteFrames = 0;
1847 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001848 mWakeLockUids.add(track->uid());
1849 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07001850 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07001851 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1852 if (chain != 0) {
1853 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1854 track->sessionId());
1855 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08001856 }
1857
1858 status = NO_ERROR;
1859 }
1860
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08001861 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001862 return status;
1863}
1864
Eric Laurentbfb1b832013-01-07 09:53:42 -08001865bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08001866{
Eric Laurentbfb1b832013-01-07 09:53:42 -08001867 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08001868 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001869 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
1870 track->mState = TrackBase::STOPPED;
1871 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08001872 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07001873 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08001874 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08001875 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001876
1877 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08001878}
1879
1880void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1881{
1882 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
1883 mTracks.remove(track);
1884 deleteTrackName_l(track->name());
1885 // redundant as track is about to be destroyed, for dumpsys only
1886 track->mName = -1;
1887 if (track->isFastTrack()) {
1888 int index = track->mFastIndex;
1889 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
1890 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1891 mFastTrackAvailMask |= 1 << index;
1892 // redundant as track is about to be destroyed, for dumpsys only
1893 track->mFastIndex = -1;
1894 }
1895 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1896 if (chain != 0) {
1897 chain->decTrackCnt();
1898 }
1899}
1900
Eric Laurentede6c3b2013-09-19 14:37:46 -07001901void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001902{
1903 // Thread could be blocked waiting for async
1904 // so signal it to handle state changes immediately
1905 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1906 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1907 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07001908 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001909}
1910
Eric Laurent81784c32012-11-19 14:55:58 -08001911String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1912{
Eric Laurent81784c32012-11-19 14:55:58 -08001913 Mutex::Autolock _l(mLock);
1914 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07001915 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08001916 }
1917
Glenn Kastend8ea6992013-07-16 14:17:15 -07001918 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1919 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08001920 free(s);
1921 return out_s8;
1922}
1923
Eric Laurent021cf962014-05-13 10:18:14 -07001924void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
Eric Laurent81784c32012-11-19 14:55:58 -08001925 AudioSystem::OutputDescriptor desc;
1926 void *param2 = NULL;
1927
Eric Laurent021cf962014-05-13 10:18:14 -07001928 ALOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event,
Eric Laurent81784c32012-11-19 14:55:58 -08001929 param);
1930
1931 switch (event) {
1932 case AudioSystem::OUTPUT_OPENED:
1933 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07001934 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08001935 desc.samplingRate = mSampleRate;
1936 desc.format = mFormat;
1937 desc.frameCount = mNormalFrameCount; // FIXME see
1938 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent10351942014-05-08 18:49:52 -07001939 desc.latency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001940 param2 = &desc;
1941 break;
1942
1943 case AudioSystem::STREAM_CONFIG_CHANGED:
1944 param2 = &param;
1945 case AudioSystem::OUTPUT_CLOSED:
1946 default:
1947 break;
1948 }
Eric Laurent021cf962014-05-13 10:18:14 -07001949 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08001950}
1951
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952void AudioFlinger::PlaybackThread::writeCallback()
1953{
1954 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001955 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001956}
1957
1958void AudioFlinger::PlaybackThread::drainCallback()
1959{
1960 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001961 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001962}
1963
Eric Laurent3b4529e2013-09-05 18:09:19 -07001964void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965{
1966 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001967 // reject out of sequence requests
1968 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
1969 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001970 mWaitWorkCV.signal();
1971 }
1972}
1973
Eric Laurent3b4529e2013-09-05 18:09:19 -07001974void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975{
1976 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07001977 // reject out of sequence requests
1978 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
1979 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 mWaitWorkCV.signal();
1981 }
1982}
1983
1984// static
1985int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08001986 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08001987 void *cookie)
1988{
1989 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
1990 ALOGV("asyncCallback() event %d", event);
1991 switch (event) {
1992 case STREAM_CBK_EVENT_WRITE_READY:
1993 me->writeCallback();
1994 break;
1995 case STREAM_CBK_EVENT_DRAIN_READY:
1996 me->drainCallback();
1997 break;
1998 default:
1999 ALOGW("asyncCallback() unknown event %d", event);
2000 break;
2001 }
2002 return 0;
2003}
2004
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002005void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002006{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002007 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Eric Laurent81784c32012-11-19 14:55:58 -08002008 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
2009 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002010 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002011 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002012 }
Andy Hung9a592762014-07-21 21:56:01 -07002013 if ((mType == MIXER || mType == DUPLICATING)
2014 && !isValidPcmSinkChannelMask(mChannelMask)) {
2015 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2016 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002017 }
Andy Hunge5412692014-05-16 11:25:07 -07002018 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung463be252014-07-10 16:56:07 -07002019 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
2020 mFormat = mHALFormat;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002021 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002022 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002023 }
Andy Hung6146c082014-03-18 11:56:15 -07002024 if ((mType == MIXER || mType == DUPLICATING)
2025 && !isValidPcmSinkFormat(mFormat)) {
2026 LOG_FATAL("HAL format %#x not supported for mixed output",
2027 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002028 }
Phil Burk062e67a2015-02-11 13:40:50 -08002029 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002030 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2031 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002032 if (mFrameCount & 15) {
2033 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2034 mFrameCount);
2035 }
2036
Eric Laurentbfb1b832013-01-07 09:53:42 -08002037 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2038 (mOutput->stream->set_callback != NULL)) {
2039 if (mOutput->stream->set_callback(mOutput->stream,
2040 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2041 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002042 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 }
2044 }
2045
Eric Laurentd1f69b02014-12-15 14:33:13 -08002046 mHwSupportsPause = false;
2047 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2048 if (mOutput->stream->pause != NULL) {
2049 if (mOutput->stream->resume != NULL) {
2050 mHwSupportsPause = true;
2051 } else {
2052 ALOGW("direct output implements pause but not resume");
2053 }
2054 } else if (mOutput->stream->resume != NULL) {
2055 ALOGW("direct output implements resume but not pause");
2056 }
2057 }
2058
Andy Hungfbfc3952015-01-15 13:33:51 -08002059 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2060 // For best precision, we use float instead of the associated output
2061 // device format (typically PCM 16 bit).
2062
2063 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2064 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2065 mBufferSize = mFrameSize * mFrameCount;
2066
2067 // TODO: We currently use the associated output device channel mask and sample rate.
2068 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2069 // (if a valid mask) to avoid premature downmix.
2070 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2071 // instead of the output device sample rate to avoid loss of high frequency information.
2072 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2073 }
2074
Andy Hung09a50072014-02-27 14:30:47 -08002075 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002076 double multiplier = 1.0;
2077 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2078 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002079 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2080 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002081 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2082 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2083 maxNormalFrameCount = maxNormalFrameCount & ~15;
2084 if (maxNormalFrameCount < minNormalFrameCount) {
2085 maxNormalFrameCount = minNormalFrameCount;
2086 }
2087 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2088 if (multiplier <= 1.0) {
2089 multiplier = 1.0;
2090 } else if (multiplier <= 2.0) {
2091 if (2 * mFrameCount <= maxNormalFrameCount) {
2092 multiplier = 2.0;
2093 } else {
2094 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2095 }
2096 } else {
2097 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002098 // 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 -08002099 // track, but we sometimes have to do this to satisfy the maximum frame count
2100 // constraint)
2101 // FIXME this rounding up should not be done if no HAL SRC
2102 uint32_t truncMult = (uint32_t) multiplier;
2103 if ((truncMult & 1)) {
2104 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2105 ++truncMult;
2106 }
2107 }
2108 multiplier = (double) truncMult;
2109 }
2110 }
2111 mNormalFrameCount = multiplier * mFrameCount;
2112 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002113 if (mType == MIXER || mType == DUPLICATING) {
2114 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2115 }
Andy Hung09a50072014-02-27 14:30:47 -08002116 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002117 mNormalFrameCount);
2118
Andy Hung010a1a12014-03-13 13:57:33 -07002119 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2120 // Originally this was int16_t[] array, need to remove legacy implications.
2121 free(mSinkBuffer);
2122 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002123 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2124 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2125 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002126 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002127
Andy Hung69aed5f2014-02-25 17:24:40 -08002128 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2129 // drives the output.
2130 free(mMixerBuffer);
2131 mMixerBuffer = NULL;
2132 if (mMixerBufferEnabled) {
2133 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2134 mMixerBufferSize = mNormalFrameCount * mChannelCount
2135 * audio_bytes_per_sample(mMixerBufferFormat);
2136 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2137 }
Andy Hung98ef9782014-03-04 14:46:50 -08002138 free(mEffectBuffer);
2139 mEffectBuffer = NULL;
2140 if (mEffectBufferEnabled) {
2141 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2142 mEffectBufferSize = mNormalFrameCount * mChannelCount
2143 * audio_bytes_per_sample(mEffectBufferFormat);
2144 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2145 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002146
Eric Laurent81784c32012-11-19 14:55:58 -08002147 // force reconfiguration of effect chains and engines to take new buffer size and audio
2148 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002149 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002150 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2151 // matter.
2152 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2153 Vector< sp<EffectChain> > effectChains = mEffectChains;
2154 for (size_t i = 0; i < effectChains.size(); i ++) {
2155 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2156 }
2157}
2158
2159
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002160status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002161{
2162 if (halFrames == NULL || dspFrames == NULL) {
2163 return BAD_VALUE;
2164 }
2165 Mutex::Autolock _l(mLock);
2166 if (initCheck() != NO_ERROR) {
2167 return INVALID_OPERATION;
2168 }
2169 size_t framesWritten = mBytesWritten / mFrameSize;
2170 *halFrames = framesWritten;
2171
2172 if (isSuspended()) {
2173 // return an estimation of rendered frames when the output is suspended
2174 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
2175 *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
2176 return NO_ERROR;
2177 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002178 status_t status;
2179 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002180 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002181 *dspFrames = (size_t)frames;
2182 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002183 }
2184}
2185
2186uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2187{
2188 Mutex::Autolock _l(mLock);
2189 uint32_t result = 0;
2190 if (getEffectChain_l(sessionId) != 0) {
2191 result = EFFECT_SESSION;
2192 }
2193
2194 for (size_t i = 0; i < mTracks.size(); ++i) {
2195 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002196 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002197 result |= TRACK_SESSION;
2198 break;
2199 }
2200 }
2201
2202 return result;
2203}
2204
2205uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2206{
2207 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2208 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2209 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2210 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2211 }
2212 for (size_t i = 0; i < mTracks.size(); i++) {
2213 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002214 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002215 return AudioSystem::getStrategyForStream(track->streamType());
2216 }
2217 }
2218 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2219}
2220
2221
Phil Burk062e67a2015-02-11 13:40:50 -08002222AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002223{
2224 Mutex::Autolock _l(mLock);
2225 return mOutput;
2226}
2227
Phil Burk062e67a2015-02-11 13:40:50 -08002228AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002229{
2230 Mutex::Autolock _l(mLock);
2231 AudioStreamOut *output = mOutput;
2232 mOutput = NULL;
2233 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2234 // must push a NULL and wait for ack
2235 mOutputSink.clear();
2236 mPipeSink.clear();
2237 mNormalSink.clear();
2238 return output;
2239}
2240
2241// this method must always be called either with ThreadBase mLock held or inside the thread loop
2242audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2243{
2244 if (mOutput == NULL) {
2245 return NULL;
2246 }
2247 return &mOutput->stream->common;
2248}
2249
2250uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2251{
2252 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2253}
2254
2255status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2256{
2257 if (!isValidSyncEvent(event)) {
2258 return BAD_VALUE;
2259 }
2260
2261 Mutex::Autolock _l(mLock);
2262
2263 for (size_t i = 0; i < mTracks.size(); ++i) {
2264 sp<Track> track = mTracks[i];
2265 if (event->triggerSession() == track->sessionId()) {
2266 (void) track->setSyncEvent(event);
2267 return NO_ERROR;
2268 }
2269 }
2270
2271 return NAME_NOT_FOUND;
2272}
2273
2274bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2275{
2276 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2277}
2278
2279void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2280 const Vector< sp<Track> >& tracksToRemove)
2281{
2282 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002283 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002284 for (size_t i = 0 ; i < count ; i++) {
2285 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002286 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002287 AudioSystem::stopOutput(mId, track->streamType(),
2288 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002289#ifdef ADD_BATTERY_DATA
2290 // to track the speaker usage
2291 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2292#endif
2293 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002294 AudioSystem::releaseOutput(mId, track->streamType(),
2295 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002296 }
Eric Laurent81784c32012-11-19 14:55:58 -08002297 }
2298 }
2299 }
Eric Laurent81784c32012-11-19 14:55:58 -08002300}
2301
2302void AudioFlinger::PlaybackThread::checkSilentMode_l()
2303{
2304 if (!mMasterMute) {
2305 char value[PROPERTY_VALUE_MAX];
2306 if (property_get("ro.audio.silent", value, "0") > 0) {
2307 char *endptr;
2308 unsigned long ul = strtoul(value, &endptr, 0);
2309 if (*endptr == '\0' && ul != 0) {
2310 ALOGD("Silence is golden");
2311 // The setprop command will not allow a property to be changed after
2312 // the first time it is set, so we don't have to worry about un-muting.
2313 setMasterMute_l(true);
2314 }
2315 }
2316 }
2317}
2318
2319// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002320ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002321{
2322 // FIXME rewrite to reduce number of system calls
2323 mLastWriteTime = systemTime();
2324 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002326 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002327
2328 // If an NBAIO sink is present, use it to write the normal mixer's submix
2329 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002330
Andy Hung010a1a12014-03-13 13:57:33 -07002331 const size_t count = mBytesRemaining / mFrameSize;
2332
Simon Wilson2d590962012-11-29 15:18:50 -08002333 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002334 // update the setpoint when AudioFlinger::mScreenState changes
2335 uint32_t screenState = AudioFlinger::mScreenState;
2336 if (screenState != mScreenState) {
2337 mScreenState = screenState;
2338 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2339 if (pipe != NULL) {
2340 pipe->setAvgFrames((mScreenState & 1) ?
2341 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2342 }
2343 }
Andy Hung010a1a12014-03-13 13:57:33 -07002344 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002345 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002346 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002347 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002348 } else {
2349 bytesWritten = framesWritten;
2350 }
Glenn Kastenefaa7ab2014-08-20 08:48:54 -07002351 mLatchDValid = false;
Glenn Kasten767094d2013-08-23 13:51:43 -07002352 status_t status = mNormalSink->getTimestamp(mLatchD.mTimestamp);
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002353 if (status == NO_ERROR) {
2354 size_t totalFramesWritten = mNormalSink->framesWritten();
2355 if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
2356 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002357 // mLatchD.mFramesReleased is set immediately before D is clocked into Q
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002358 mLatchDValid = true;
2359 }
2360 }
Eric Laurent81784c32012-11-19 14:55:58 -08002361 // otherwise use the HAL / AudioStreamOut directly
2362 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002363 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002364
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002366 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2367 mWriteAckSequence += 2;
2368 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002369 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002370 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002371 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002372 // FIXME We should have an implementation of timestamps for direct output threads.
2373 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002374 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002375 if (mUseAsyncWrite &&
2376 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2377 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002378 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002379 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002380 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 }
Eric Laurent81784c32012-11-19 14:55:58 -08002382 }
2383
Eric Laurent81784c32012-11-19 14:55:58 -08002384 mNumWrites++;
2385 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002386 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002387 return bytesWritten;
2388}
2389
2390void AudioFlinger::PlaybackThread::threadLoop_drain()
2391{
2392 if (mOutput->stream->drain) {
2393 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2394 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002395 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2396 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002397 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002398 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002399 }
2400 mOutput->stream->drain(mOutput->stream,
2401 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2402 : AUDIO_DRAIN_ALL);
2403 }
2404}
2405
2406void AudioFlinger::PlaybackThread::threadLoop_exit()
2407{
Eric Laurent275e8e92014-11-30 15:14:47 -08002408 {
2409 Mutex::Autolock _l(mLock);
2410 for (size_t i = 0; i < mTracks.size(); i++) {
2411 sp<Track> track = mTracks[i];
2412 track->invalidate();
2413 }
2414 }
Eric Laurent81784c32012-11-19 14:55:58 -08002415}
2416
2417/*
2418The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002419 - mSinkBufferSize from frame count * frame size
Eric Laurent81784c32012-11-19 14:55:58 -08002420 - activeSleepTime from activeSleepTimeUs()
2421 - idleSleepTime from idleSleepTimeUs()
2422 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
2423 - maxPeriod from frame count and sample rate (MIXER only)
2424
2425The parameters that affect these derived values are:
2426 - frame count
2427 - frame size
2428 - sample rate
2429 - device type: A2DP or not
2430 - device latency
2431 - format: PCM or not
2432 - active sleep time
2433 - idle sleep time
2434*/
2435
2436void AudioFlinger::PlaybackThread::cacheParameters_l()
2437{
Andy Hung25c2dac2014-02-27 14:56:00 -08002438 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002439 activeSleepTime = activeSleepTimeUs();
2440 idleSleepTime = idleSleepTimeUs();
2441}
2442
2443void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2444{
Glenn Kasten7c027242012-12-26 14:43:16 -08002445 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002446 this, streamType, mTracks.size());
2447 Mutex::Autolock _l(mLock);
2448
2449 size_t size = mTracks.size();
2450 for (size_t i = 0; i < size; i++) {
2451 sp<Track> t = mTracks[i];
2452 if (t->streamType() == streamType) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002453 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002454 }
2455 }
2456}
2457
2458status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2459{
2460 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002461 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2462 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002463 bool ownsBuffer = false;
2464
2465 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2466 if (session > 0) {
2467 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002468 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002469 if (mType != DIRECT) {
2470 size_t numSamples = mNormalFrameCount * mChannelCount;
2471 buffer = new int16_t[numSamples];
2472 memset(buffer, 0, numSamples * sizeof(int16_t));
2473 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2474 ownsBuffer = true;
2475 }
2476
2477 // Attach all tracks with same session ID to this chain.
2478 for (size_t i = 0; i < mTracks.size(); ++i) {
2479 sp<Track> track = mTracks[i];
2480 if (session == track->sessionId()) {
2481 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2482 buffer);
2483 track->setMainBuffer(buffer);
2484 chain->incTrackCnt();
2485 }
2486 }
2487
2488 // indicate all active tracks in the chain
2489 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2490 sp<Track> track = mActiveTracks[i].promote();
2491 if (track == 0) {
2492 continue;
2493 }
2494 if (session == track->sessionId()) {
2495 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2496 chain->incActiveTrackCnt();
2497 }
2498 }
2499 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002500 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002501 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002502 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2503 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002504 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2505 // chains list in order to be processed last as it contains output stage effects
2506 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2507 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2508 // after track specific effects and before output stage
2509 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2510 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2511 // Effect chain for other sessions are inserted at beginning of effect
2512 // chains list to be processed before output mix effects. Relative order between other
2513 // sessions is not important
2514 size_t size = mEffectChains.size();
2515 size_t i = 0;
2516 for (i = 0; i < size; i++) {
2517 if (mEffectChains[i]->sessionId() < session) {
2518 break;
2519 }
2520 }
2521 mEffectChains.insertAt(chain, i);
2522 checkSuspendOnAddEffectChain_l(chain);
2523
2524 return NO_ERROR;
2525}
2526
2527size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2528{
2529 int session = chain->sessionId();
2530
2531 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2532
2533 for (size_t i = 0; i < mEffectChains.size(); i++) {
2534 if (chain == mEffectChains[i]) {
2535 mEffectChains.removeAt(i);
2536 // detach all active tracks from the chain
2537 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2538 sp<Track> track = mActiveTracks[i].promote();
2539 if (track == 0) {
2540 continue;
2541 }
2542 if (session == track->sessionId()) {
2543 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2544 chain.get(), session);
2545 chain->decActiveTrackCnt();
2546 }
2547 }
2548
2549 // detach all tracks with same session ID from this chain
2550 for (size_t i = 0; i < mTracks.size(); ++i) {
2551 sp<Track> track = mTracks[i];
2552 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002553 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002554 chain->decTrackCnt();
2555 }
2556 }
2557 break;
2558 }
2559 }
2560 return mEffectChains.size();
2561}
2562
2563status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2564 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2565{
2566 Mutex::Autolock _l(mLock);
2567 return attachAuxEffect_l(track, EffectId);
2568}
2569
2570status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2571 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2572{
2573 status_t status = NO_ERROR;
2574
2575 if (EffectId == 0) {
2576 track->setAuxBuffer(0, NULL);
2577 } else {
2578 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2579 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2580 if (effect != 0) {
2581 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2582 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2583 } else {
2584 status = INVALID_OPERATION;
2585 }
2586 } else {
2587 status = BAD_VALUE;
2588 }
2589 }
2590 return status;
2591}
2592
2593void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2594{
2595 for (size_t i = 0; i < mTracks.size(); ++i) {
2596 sp<Track> track = mTracks[i];
2597 if (track->auxEffectId() == effectId) {
2598 attachAuxEffect_l(track, 0);
2599 }
2600 }
2601}
2602
2603bool AudioFlinger::PlaybackThread::threadLoop()
2604{
2605 Vector< sp<Track> > tracksToRemove;
2606
2607 standbyTime = systemTime();
2608
2609 // MIXER
2610 nsecs_t lastWarning = 0;
2611
2612 // DUPLICATING
2613 // FIXME could this be made local to while loop?
2614 writeFrames = 0;
2615
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002616 int lastGeneration = 0;
2617
Eric Laurent81784c32012-11-19 14:55:58 -08002618 cacheParameters_l();
2619 sleepTime = idleSleepTime;
2620
2621 if (mType == MIXER) {
2622 sleepTimeShift = 0;
2623 }
2624
2625 CpuStats cpuStats;
2626 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2627
2628 acquireWakeLock();
2629
Glenn Kasten9e58b552013-01-18 15:09:48 -08002630 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2631 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2632 // and then that string will be logged at the next convenient opportunity.
2633 const char *logString = NULL;
2634
Eric Laurent664539d2013-09-23 18:24:31 -07002635 checkSilentMode_l();
2636
Eric Laurent81784c32012-11-19 14:55:58 -08002637 while (!exitPending())
2638 {
2639 cpuStats.sample(myName);
2640
2641 Vector< sp<EffectChain> > effectChains;
2642
Eric Laurent81784c32012-11-19 14:55:58 -08002643 { // scope for mLock
2644
2645 Mutex::Autolock _l(mLock);
2646
Eric Laurent021cf962014-05-13 10:18:14 -07002647 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002648
Glenn Kasten9e58b552013-01-18 15:09:48 -08002649 if (logString != NULL) {
2650 mNBLogWriter->logTimestamp();
2651 mNBLogWriter->log(logString);
2652 logString = NULL;
2653 }
2654
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002655 // Gather the framesReleased counters for all active tracks,
2656 // and latch them atomically with the timestamp.
2657 // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
2658 mLatchD.mFramesReleased.clear();
2659 size_t size = mActiveTracks.size();
2660 for (size_t i = 0; i < size; i++) {
2661 sp<Track> t = mActiveTracks[i].promote();
2662 if (t != 0) {
2663 mLatchD.mFramesReleased.add(t.get(),
2664 t->mAudioTrackServerProxy->framesReleased());
2665 }
2666 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002667 if (mLatchDValid) {
2668 mLatchQ = mLatchD;
2669 mLatchDValid = false;
2670 mLatchQValid = true;
2671 }
2672
Eric Laurent81784c32012-11-19 14:55:58 -08002673 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 if (mSignalPending) {
2675 // A signal was raised while we were unlocked
2676 mSignalPending = false;
2677 } else if (waitingAsyncCallback_l()) {
2678 if (exitPending()) {
2679 break;
2680 }
2681 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002682 mWakeLockUids.clear();
2683 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684 ALOGV("wait async completion");
2685 mWaitWorkCV.wait(mLock);
2686 ALOGV("async completion/wake");
2687 acquireWakeLock_l();
Eric Laurent972a1732013-09-04 09:42:59 -07002688 standbyTime = systemTime() + standbyDelay;
2689 sleepTime = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002690
2691 continue;
2692 }
2693 if ((!mActiveTracks.size() && systemTime() > standbyTime) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002694 isSuspended()) {
2695 // put audio hardware into standby after short delay
2696 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002697
2698 threadLoop_standby();
2699
2700 mStandby = true;
2701 }
2702
2703 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2704 // we're about to wait, flush the binder command buffer
2705 IPCThreadState::self()->flushCommands();
2706
2707 clearOutputTracks();
2708
2709 if (exitPending()) {
2710 break;
2711 }
2712
2713 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002714 mWakeLockUids.clear();
2715 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002716 // wait until we have something to do...
2717 ALOGV("%s going to sleep", myName.string());
2718 mWaitWorkCV.wait(mLock);
2719 ALOGV("%s waking up", myName.string());
2720 acquireWakeLock_l();
2721
2722 mMixerStatus = MIXER_IDLE;
2723 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2724 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002725 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002726 checkSilentMode_l();
2727
2728 standbyTime = systemTime() + standbyDelay;
2729 sleepTime = idleSleepTime;
2730 if (mType == MIXER) {
2731 sleepTimeShift = 0;
2732 }
2733
2734 continue;
2735 }
2736 }
Eric Laurent81784c32012-11-19 14:55:58 -08002737 // mMixerStatusIgnoringFastTracks is also updated internally
2738 mMixerStatus = prepareTracks_l(&tracksToRemove);
2739
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002740 // compare with previously applied list
2741 if (lastGeneration != mActiveTracksGeneration) {
2742 // update wakelock
2743 updateWakeLockUids_l(mWakeLockUids);
2744 lastGeneration = mActiveTracksGeneration;
2745 }
2746
Eric Laurent81784c32012-11-19 14:55:58 -08002747 // prevent any changes in effect chain list and in each effect chain
2748 // during mixing and effect process as the audio buffers could be deleted
2749 // or modified if an effect is created or deleted
2750 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002751 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08002752
Eric Laurentbfb1b832013-01-07 09:53:42 -08002753 if (mBytesRemaining == 0) {
2754 mCurrentWriteLength = 0;
2755 if (mMixerStatus == MIXER_TRACKS_READY) {
2756 // threadLoop_mix() sets mCurrentWriteLength
2757 threadLoop_mix();
2758 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
2759 && (mMixerStatus != MIXER_DRAIN_ALL)) {
2760 // threadLoop_sleepTime sets sleepTime to 0 if data
2761 // must be written to HAL
2762 threadLoop_sleepTime();
2763 if (sleepTime == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08002764 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 }
2766 }
Andy Hung98ef9782014-03-04 14:46:50 -08002767 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
2768 // mMixerBuffer with data if mMixerBufferValid is true and sleepTime == 0.
2769 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
2770 // or mSinkBuffer (if there are no effects).
2771 //
2772 // This is done pre-effects computation; if effects change to
2773 // support higher precision, this needs to move.
2774 //
2775 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
2776 // TODO use sleepTime == 0 as an additional condition.
2777 if (mMixerBufferValid) {
2778 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
2779 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
2780
2781 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
2782 mNormalFrameCount * mChannelCount);
2783 }
2784
Eric Laurentbfb1b832013-01-07 09:53:42 -08002785 mBytesRemaining = mCurrentWriteLength;
2786 if (isSuspended()) {
2787 sleepTime = suspendSleepTimeUs();
2788 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08002789 mBytesWritten += mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002790 mBytesRemaining = 0;
2791 }
Eric Laurent81784c32012-11-19 14:55:58 -08002792
Eric Laurentbfb1b832013-01-07 09:53:42 -08002793 // only process effects if we're going to write
Eric Laurent59fe0102013-09-27 18:48:26 -07002794 if (sleepTime == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002795 for (size_t i = 0; i < effectChains.size(); i ++) {
2796 effectChains[i]->process_l();
2797 }
Eric Laurent81784c32012-11-19 14:55:58 -08002798 }
2799 }
Eric Laurent59fe0102013-09-27 18:48:26 -07002800 // Process effect chains for offloaded thread even if no audio
2801 // was read from audio track: process only updates effect state
2802 // and thus does have to be synchronized with audio writes but may have
2803 // to be called while waiting for async write callback
2804 if (mType == OFFLOAD) {
2805 for (size_t i = 0; i < effectChains.size(); i ++) {
2806 effectChains[i]->process_l();
2807 }
2808 }
Eric Laurent81784c32012-11-19 14:55:58 -08002809
Andy Hung98ef9782014-03-04 14:46:50 -08002810 // Only if the Effects buffer is enabled and there is data in the
2811 // Effects buffer (buffer valid), we need to
2812 // copy into the sink buffer.
2813 // TODO use sleepTime == 0 as an additional condition.
2814 if (mEffectBufferValid) {
2815 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
2816 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
2817 mNormalFrameCount * mChannelCount);
2818 }
2819
Eric Laurent81784c32012-11-19 14:55:58 -08002820 // enable changes in effect chain
2821 unlockEffectChains(effectChains);
2822
Eric Laurentbfb1b832013-01-07 09:53:42 -08002823 if (!waitingAsyncCallback()) {
2824 // sleepTime == 0 means we must write to audio hardware
2825 if (sleepTime == 0) {
2826 if (mBytesRemaining) {
2827 ssize_t ret = threadLoop_write();
2828 if (ret < 0) {
2829 mBytesRemaining = 0;
2830 } else {
2831 mBytesWritten += ret;
2832 mBytesRemaining -= ret;
2833 }
2834 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
2835 (mMixerStatus == MIXER_DRAIN_ALL)) {
2836 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08002837 }
Glenn Kasten4944acb2013-08-19 08:39:20 -07002838 if (mType == MIXER) {
2839 // write blocked detection
2840 nsecs_t now = systemTime();
2841 nsecs_t delta = now - mLastWriteTime;
2842 if (!mStandby && delta > maxPeriod) {
2843 mNumDelayedWrites++;
2844 if ((now - lastWarning) > kWarningThrottleNs) {
2845 ATRACE_NAME("underrun");
2846 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2847 ns2ms(delta), mNumDelayedWrites, this);
2848 lastWarning = now;
2849 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850 }
2851 }
Eric Laurent81784c32012-11-19 14:55:58 -08002852
Eric Laurentbfb1b832013-01-07 09:53:42 -08002853 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07002854 ATRACE_BEGIN("sleep");
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855 usleep(sleepTime);
Glenn Kastene7754022014-10-31 12:11:26 -07002856 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002857 }
Eric Laurent81784c32012-11-19 14:55:58 -08002858 }
2859
2860 // Finally let go of removed track(s), without the lock held
2861 // since we can't guarantee the destructors won't acquire that
2862 // same lock. This will also mutate and push a new fast mixer state.
2863 threadLoop_removeTracks(tracksToRemove);
2864 tracksToRemove.clear();
2865
2866 // FIXME I don't understand the need for this here;
2867 // it was in the original code but maybe the
2868 // assignment in saveOutputTracks() makes this unnecessary?
2869 clearOutputTracks();
2870
2871 // Effect chains will be actually deleted here if they were removed from
2872 // mEffectChains list during mixing or effects processing
2873 effectChains.clear();
2874
2875 // FIXME Note that the above .clear() is no longer necessary since effectChains
2876 // is now local to this block, but will keep it for now (at least until merge done).
2877 }
2878
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 threadLoop_exit();
2880
Eric Laurentcf817a22014-08-04 20:36:31 -07002881 if (!mStandby) {
2882 threadLoop_standby();
2883 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002884 }
2885
2886 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002887 mWakeLockUids.clear();
2888 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002889
2890 ALOGV("Thread %p type %d exiting", this, mType);
2891 return false;
2892}
2893
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894// removeTracks_l() must be called with ThreadBase::mLock held
2895void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
2896{
2897 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002898 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 for (size_t i=0 ; i<count ; i++) {
2900 const sp<Track>& track = tracksToRemove.itemAt(i);
2901 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002902 mWakeLockUids.remove(track->uid());
2903 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
2905 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2906 if (chain != 0) {
2907 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
2908 track->sessionId());
2909 chain->decActiveTrackCnt();
2910 }
2911 if (track->isTerminated()) {
2912 removeTrack_l(track);
2913 }
2914 }
2915 }
2916
2917}
Eric Laurent81784c32012-11-19 14:55:58 -08002918
Eric Laurentaccc1472013-09-20 09:36:34 -07002919status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
2920{
2921 if (mNormalSink != 0) {
2922 return mNormalSink->getTimestamp(timestamp);
2923 }
Andy Hung9a1c8892014-12-03 11:37:42 -08002924 if ((mType == OFFLOAD || mType == DIRECT)
2925 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07002926 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08002927 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07002928 if (ret == 0) {
2929 timestamp.mPosition = (uint32_t)position64;
2930 return NO_ERROR;
2931 }
2932 }
2933 return INVALID_OPERATION;
2934}
Eric Laurent1c333e22014-05-20 10:48:17 -07002935
2936status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
2937 audio_patch_handle_t *handle)
2938{
2939 status_t status = NO_ERROR;
2940 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2941 // store new device and send to effects
2942 audio_devices_t type = AUDIO_DEVICE_NONE;
2943 for (unsigned int i = 0; i < patch->num_sinks; i++) {
2944 type |= patch->sinks[i].ext.device.type;
2945 }
2946 mOutDevice = type;
2947 for (size_t i = 0; i < mEffectChains.size(); i++) {
2948 mEffectChains[i]->setDevice_l(mOutDevice);
2949 }
2950
2951 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2952 status = hwDevice->create_audio_patch(hwDevice,
2953 patch->num_sources,
2954 patch->sources,
2955 patch->num_sinks,
2956 patch->sinks,
2957 handle);
2958 } else {
2959 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
2960 }
2961 return status;
2962}
2963
2964status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
2965{
2966 status_t status = NO_ERROR;
2967 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
2968 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
2969 status = hwDevice->release_audio_patch(hwDevice, handle);
2970 } else {
2971 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
2972 }
2973 return status;
2974}
2975
Eric Laurent83b88082014-06-20 18:31:16 -07002976void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
2977{
2978 Mutex::Autolock _l(mLock);
2979 mTracks.add(track);
2980}
2981
2982void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
2983{
2984 Mutex::Autolock _l(mLock);
2985 destroyTrack_l(track);
2986}
2987
2988void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
2989{
2990 ThreadBase::getAudioPortConfig(config);
2991 config->role = AUDIO_PORT_ROLE_SOURCE;
2992 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
2993 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
2994}
2995
Eric Laurent81784c32012-11-19 14:55:58 -08002996// ----------------------------------------------------------------------------
2997
2998AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
2999 audio_io_handle_t id, audio_devices_t device, type_t type)
3000 : PlaybackThread(audioFlinger, output, id, device, type),
3001 // mAudioMixer below
3002 // mFastMixer below
3003 mFastMixerFutex(0)
3004 // mOutputSink below
3005 // mPipeSink below
3006 // mNormalSink below
3007{
3008 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003009 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003010 "mFrameCount=%d, mNormalFrameCount=%d",
3011 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3012 mNormalFrameCount);
3013 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3014
Andy Hungfbfc3952015-01-15 13:33:51 -08003015 if (type == DUPLICATING) {
3016 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3017 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3018 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3019 return;
3020 }
Eric Laurent81784c32012-11-19 14:55:58 -08003021 // create an NBAIO sink for the HAL output stream, and negotiate
3022 mOutputSink = new AudioStreamOutSink(output->stream);
3023 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003024 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003025 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3026 ALOG_ASSERT(index == 0);
3027
3028 // initialize fast mixer depending on configuration
3029 bool initFastMixer;
3030 switch (kUseFastMixer) {
3031 case FastMixer_Never:
3032 initFastMixer = false;
3033 break;
3034 case FastMixer_Always:
3035 initFastMixer = true;
3036 break;
3037 case FastMixer_Static:
3038 case FastMixer_Dynamic:
3039 initFastMixer = mFrameCount < mNormalFrameCount;
3040 break;
3041 }
3042 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003043 audio_format_t fastMixerFormat;
3044 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3045 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3046 } else {
3047 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3048 }
3049 if (mFormat != fastMixerFormat) {
3050 // change our Sink format to accept our intermediate precision
3051 mFormat = fastMixerFormat;
3052 free(mSinkBuffer);
3053 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3054 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3055 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3056 }
Eric Laurent81784c32012-11-19 14:55:58 -08003057
3058 // create a MonoPipe to connect our submix to FastMixer
3059 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003060 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003061 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003062 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003063 format.mFormat = fastMixerFormat;
3064 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3065
Eric Laurent81784c32012-11-19 14:55:58 -08003066 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3067 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3068 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3069 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3070 const NBAIO_Format offers[1] = {format};
3071 size_t numCounterOffers = 0;
3072 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3073 ALOG_ASSERT(index == 0);
3074 monoPipe->setAvgFrames((mScreenState & 1) ?
3075 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3076 mPipeSink = monoPipe;
3077
Glenn Kasten46909e72013-02-26 09:20:22 -08003078#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003079 if (mTeeSinkOutputEnabled) {
3080 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003081 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3082 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003083 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003084 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003085 ALOG_ASSERT(index == 0);
3086 mTeeSink = teeSink;
3087 PipeReader *teeSource = new PipeReader(*teeSink);
3088 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003089 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003090 ALOG_ASSERT(index == 0);
3091 mTeeSource = teeSource;
3092 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003093#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003094
3095 // create fast mixer and configure it initially with just one fast track for our submix
3096 mFastMixer = new FastMixer();
3097 FastMixerStateQueue *sq = mFastMixer->sq();
3098#ifdef STATE_QUEUE_DUMP
3099 sq->setObserverDump(&mStateQueueObserverDump);
3100 sq->setMutatorDump(&mStateQueueMutatorDump);
3101#endif
3102 FastMixerState *state = sq->begin();
3103 FastTrack *fastTrack = &state->mFastTracks[0];
3104 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3105 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3106 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003107 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3108 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003109 fastTrack->mGeneration++;
3110 state->mFastTracksGen++;
3111 state->mTrackMask = 1;
3112 // fast mixer will use the HAL output sink
3113 state->mOutputSink = mOutputSink.get();
3114 state->mOutputSinkGen++;
3115 state->mFrameCount = mFrameCount;
3116 state->mCommand = FastMixerState::COLD_IDLE;
3117 // already done in constructor initialization list
3118 //mFastMixerFutex = 0;
3119 state->mColdFutexAddr = &mFastMixerFutex;
3120 state->mColdGen++;
3121 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003122#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003123 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003124#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003125 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3126 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003127 sq->end();
3128 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3129
3130 // start the fast mixer
3131 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3132 pid_t tid = mFastMixer->getTid();
3133 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3134 if (err != 0) {
3135 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3136 kPriorityFastMixer, getpid_cached, tid, err);
3137 }
3138
3139#ifdef AUDIO_WATCHDOG
3140 // create and start the watchdog
3141 mAudioWatchdog = new AudioWatchdog();
3142 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3143 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3144 tid = mAudioWatchdog->getTid();
3145 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
3146 if (err != 0) {
3147 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
3148 kPriorityFastMixer, getpid_cached, tid, err);
3149 }
3150#endif
3151
Eric Laurent81784c32012-11-19 14:55:58 -08003152 }
3153
3154 switch (kUseFastMixer) {
3155 case FastMixer_Never:
3156 case FastMixer_Dynamic:
3157 mNormalSink = mOutputSink;
3158 break;
3159 case FastMixer_Always:
3160 mNormalSink = mPipeSink;
3161 break;
3162 case FastMixer_Static:
3163 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3164 break;
3165 }
3166}
3167
3168AudioFlinger::MixerThread::~MixerThread()
3169{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003170 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003171 FastMixerStateQueue *sq = mFastMixer->sq();
3172 FastMixerState *state = sq->begin();
3173 if (state->mCommand == FastMixerState::COLD_IDLE) {
3174 int32_t old = android_atomic_inc(&mFastMixerFutex);
3175 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003176 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003177 }
3178 }
3179 state->mCommand = FastMixerState::EXIT;
3180 sq->end();
3181 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3182 mFastMixer->join();
3183 // Though the fast mixer thread has exited, it's state queue is still valid.
3184 // We'll use that extract the final state which contains one remaining fast track
3185 // corresponding to our sub-mix.
3186 state = sq->begin();
3187 ALOG_ASSERT(state->mTrackMask == 1);
3188 FastTrack *fastTrack = &state->mFastTracks[0];
3189 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3190 delete fastTrack->mBufferProvider;
3191 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003192 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003193#ifdef AUDIO_WATCHDOG
3194 if (mAudioWatchdog != 0) {
3195 mAudioWatchdog->requestExit();
3196 mAudioWatchdog->requestExitAndWait();
3197 mAudioWatchdog.clear();
3198 }
3199#endif
3200 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003201 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003202 delete mAudioMixer;
3203}
3204
3205
3206uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3207{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003208 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003209 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3210 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3211 }
3212 return latency;
3213}
3214
3215
3216void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3217{
3218 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3219}
3220
Eric Laurentbfb1b832013-01-07 09:53:42 -08003221ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003222{
3223 // FIXME we should only do one push per cycle; confirm this is true
3224 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003225 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003226 FastMixerStateQueue *sq = mFastMixer->sq();
3227 FastMixerState *state = sq->begin();
3228 if (state->mCommand != FastMixerState::MIX_WRITE &&
3229 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3230 if (state->mCommand == FastMixerState::COLD_IDLE) {
3231 int32_t old = android_atomic_inc(&mFastMixerFutex);
3232 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003233 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003234 }
3235#ifdef AUDIO_WATCHDOG
3236 if (mAudioWatchdog != 0) {
3237 mAudioWatchdog->resume();
3238 }
3239#endif
3240 }
3241 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003242#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003243 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003244 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003245#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003246 sq->end();
3247 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3248 if (kUseFastMixer == FastMixer_Dynamic) {
3249 mNormalSink = mPipeSink;
3250 }
3251 } else {
3252 sq->end(false /*didModify*/);
3253 }
3254 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003255 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003256}
3257
3258void AudioFlinger::MixerThread::threadLoop_standby()
3259{
3260 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003261 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003262 FastMixerStateQueue *sq = mFastMixer->sq();
3263 FastMixerState *state = sq->begin();
3264 if (!(state->mCommand & FastMixerState::IDLE)) {
3265 state->mCommand = FastMixerState::COLD_IDLE;
3266 state->mColdFutexAddr = &mFastMixerFutex;
3267 state->mColdGen++;
3268 mFastMixerFutex = 0;
3269 sq->end();
3270 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3271 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3272 if (kUseFastMixer == FastMixer_Dynamic) {
3273 mNormalSink = mOutputSink;
3274 }
3275#ifdef AUDIO_WATCHDOG
3276 if (mAudioWatchdog != 0) {
3277 mAudioWatchdog->pause();
3278 }
3279#endif
3280 } else {
3281 sq->end(false /*didModify*/);
3282 }
3283 }
3284 PlaybackThread::threadLoop_standby();
3285}
3286
Eric Laurentbfb1b832013-01-07 09:53:42 -08003287bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3288{
3289 return false;
3290}
3291
3292bool AudioFlinger::PlaybackThread::shouldStandby_l()
3293{
3294 return !mStandby;
3295}
3296
3297bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3298{
3299 Mutex::Autolock _l(mLock);
3300 return waitingAsyncCallback_l();
3301}
3302
Eric Laurent81784c32012-11-19 14:55:58 -08003303// shared by MIXER and DIRECT, overridden by DUPLICATING
3304void AudioFlinger::PlaybackThread::threadLoop_standby()
3305{
3306 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003307 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003308 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003309 // discard any pending drain or write ack by incrementing sequence
3310 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3311 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003312 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003313 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3314 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003315 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003316 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003317}
3318
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003319void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3320{
3321 ALOGV("signal playback thread");
3322 broadcast_l();
3323}
3324
Eric Laurent81784c32012-11-19 14:55:58 -08003325void AudioFlinger::MixerThread::threadLoop_mix()
3326{
3327 // obtain the presentation timestamp of the next output buffer
3328 int64_t pts;
3329 status_t status = INVALID_OPERATION;
3330
3331 if (mNormalSink != 0) {
3332 status = mNormalSink->getNextWriteTimestamp(&pts);
3333 } else {
3334 status = mOutputSink->getNextWriteTimestamp(&pts);
3335 }
3336
3337 if (status != NO_ERROR) {
3338 pts = AudioBufferProvider::kInvalidPTS;
3339 }
3340
3341 // mix buffers...
3342 mAudioMixer->process(pts);
Andy Hung25c2dac2014-02-27 14:56:00 -08003343 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003344 // increase sleep time progressively when application underrun condition clears.
3345 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3346 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3347 // such that we would underrun the audio HAL.
3348 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
3349 sleepTimeShift--;
3350 }
3351 sleepTime = 0;
3352 standbyTime = systemTime() + standbyDelay;
3353 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003354
Eric Laurent81784c32012-11-19 14:55:58 -08003355}
3356
3357void AudioFlinger::MixerThread::threadLoop_sleepTime()
3358{
3359 // If no tracks are ready, sleep once for the duration of an output
3360 // buffer size, then write 0s to the output
3361 if (sleepTime == 0) {
3362 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3363 sleepTime = activeSleepTime >> sleepTimeShift;
3364 if (sleepTime < kMinThreadSleepTimeUs) {
3365 sleepTime = kMinThreadSleepTimeUs;
3366 }
3367 // reduce sleep time in case of consecutive application underruns to avoid
3368 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3369 // duration we would end up writing less data than needed by the audio HAL if
3370 // the condition persists.
3371 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3372 sleepTimeShift++;
3373 }
3374 } else {
3375 sleepTime = idleSleepTime;
3376 }
3377 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003378 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3379 // before effects processing or output.
3380 if (mMixerBufferValid) {
3381 memset(mMixerBuffer, 0, mMixerBufferSize);
3382 } else {
3383 memset(mSinkBuffer, 0, mSinkBufferSize);
3384 }
Eric Laurent81784c32012-11-19 14:55:58 -08003385 sleepTime = 0;
3386 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3387 "anticipated start");
3388 }
3389 // TODO add standby time extension fct of effect tail
3390}
3391
3392// prepareTracks_l() must be called with ThreadBase::mLock held
3393AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3394 Vector< sp<Track> > *tracksToRemove)
3395{
3396
3397 mixer_state mixerStatus = MIXER_IDLE;
3398 // find out which tracks need to be processed
3399 size_t count = mActiveTracks.size();
3400 size_t mixedTracks = 0;
3401 size_t tracksWithEffect = 0;
3402 // counts only _active_ fast tracks
3403 size_t fastTracks = 0;
3404 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3405
3406 float masterVolume = mMasterVolume;
3407 bool masterMute = mMasterMute;
3408
3409 if (masterMute) {
3410 masterVolume = 0;
3411 }
3412 // Delegate master volume control to effect in output mix effect chain if needed
3413 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3414 if (chain != 0) {
3415 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3416 chain->setVolume_l(&v, &v);
3417 masterVolume = (float)((v + (1 << 23)) >> 24);
3418 chain.clear();
3419 }
3420
3421 // prepare a new state to push
3422 FastMixerStateQueue *sq = NULL;
3423 FastMixerState *state = NULL;
3424 bool didModify = false;
3425 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003426 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003427 sq = mFastMixer->sq();
3428 state = sq->begin();
3429 }
3430
Andy Hung69aed5f2014-02-25 17:24:40 -08003431 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003432 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003433
Eric Laurent81784c32012-11-19 14:55:58 -08003434 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003435 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003436 if (t == 0) {
3437 continue;
3438 }
3439
3440 // this const just means the local variable doesn't change
3441 Track* const track = t.get();
3442
3443 // process fast tracks
3444 if (track->isFastTrack()) {
3445
3446 // It's theoretically possible (though unlikely) for a fast track to be created
3447 // and then removed within the same normal mix cycle. This is not a problem, as
3448 // the track never becomes active so it's fast mixer slot is never touched.
3449 // The converse, of removing an (active) track and then creating a new track
3450 // at the identical fast mixer slot within the same normal mix cycle,
3451 // is impossible because the slot isn't marked available until the end of each cycle.
3452 int j = track->mFastIndex;
3453 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3454 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3455 FastTrack *fastTrack = &state->mFastTracks[j];
3456
3457 // Determine whether the track is currently in underrun condition,
3458 // and whether it had a recent underrun.
3459 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3460 FastTrackUnderruns underruns = ftDump->mUnderruns;
3461 uint32_t recentFull = (underruns.mBitFields.mFull -
3462 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3463 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3464 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3465 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3466 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3467 uint32_t recentUnderruns = recentPartial + recentEmpty;
3468 track->mObservedUnderruns = underruns;
3469 // don't count underruns that occur while stopping or pausing
3470 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003471 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3472 recentUnderruns > 0) {
3473 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3474 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003475 }
3476
3477 // This is similar to the state machine for normal tracks,
3478 // with a few modifications for fast tracks.
3479 bool isActive = true;
3480 switch (track->mState) {
3481 case TrackBase::STOPPING_1:
3482 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003483 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003484 track->mState = TrackBase::STOPPING_2;
3485 }
3486 break;
3487 case TrackBase::PAUSING:
3488 // ramp down is not yet implemented
3489 track->setPaused();
3490 break;
3491 case TrackBase::RESUMING:
3492 // ramp up is not yet implemented
3493 track->mState = TrackBase::ACTIVE;
3494 break;
3495 case TrackBase::ACTIVE:
3496 if (recentFull > 0 || recentPartial > 0) {
3497 // track has provided at least some frames recently: reset retry count
3498 track->mRetryCount = kMaxTrackRetries;
3499 }
3500 if (recentUnderruns == 0) {
3501 // no recent underruns: stay active
3502 break;
3503 }
3504 // there has recently been an underrun of some kind
3505 if (track->sharedBuffer() == 0) {
3506 // were any of the recent underruns "empty" (no frames available)?
3507 if (recentEmpty == 0) {
3508 // no, then ignore the partial underruns as they are allowed indefinitely
3509 break;
3510 }
3511 // there has recently been an "empty" underrun: decrement the retry counter
3512 if (--(track->mRetryCount) > 0) {
3513 break;
3514 }
3515 // indicate to client process that the track was disabled because of underrun;
3516 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003517 android_atomic_or(CBLK_DISABLED, &track->mCblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003518 // remove from active list, but state remains ACTIVE [confusing but true]
3519 isActive = false;
3520 break;
3521 }
3522 // fall through
3523 case TrackBase::STOPPING_2:
3524 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003525 case TrackBase::STOPPED:
3526 case TrackBase::FLUSHED: // flush() while active
3527 // Check for presentation complete if track is inactive
3528 // We have consumed all the buffers of this track.
3529 // This would be incomplete if we auto-paused on underrun
3530 {
3531 size_t audioHALFrames =
3532 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3533 size_t framesWritten = mBytesWritten / mFrameSize;
3534 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3535 // track stays in active list until presentation is complete
3536 break;
3537 }
3538 }
3539 if (track->isStopping_2()) {
3540 track->mState = TrackBase::STOPPED;
3541 }
3542 if (track->isStopped()) {
3543 // Can't reset directly, as fast mixer is still polling this track
3544 // track->reset();
3545 // So instead mark this track as needing to be reset after push with ack
3546 resetMask |= 1 << i;
3547 }
3548 isActive = false;
3549 break;
3550 case TrackBase::IDLE:
3551 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003552 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08003553 }
3554
3555 if (isActive) {
3556 // was it previously inactive?
3557 if (!(state->mTrackMask & (1 << j))) {
3558 ExtendedAudioBufferProvider *eabp = track;
3559 VolumeProvider *vp = track;
3560 fastTrack->mBufferProvider = eabp;
3561 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08003562 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003563 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08003564 fastTrack->mGeneration++;
3565 state->mTrackMask |= 1 << j;
3566 didModify = true;
3567 // no acknowledgement required for newly active tracks
3568 }
3569 // cache the combined master volume and stream type volume for fast mixer; this
3570 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08003571 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08003572 ++fastTracks;
3573 } else {
3574 // was it previously active?
3575 if (state->mTrackMask & (1 << j)) {
3576 fastTrack->mBufferProvider = NULL;
3577 fastTrack->mGeneration++;
3578 state->mTrackMask &= ~(1 << j);
3579 didModify = true;
3580 // If any fast tracks were removed, we must wait for acknowledgement
3581 // because we're about to decrement the last sp<> on those tracks.
3582 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3583 } else {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003584 LOG_ALWAYS_FATAL("fast track %d should have been active", j);
Eric Laurent81784c32012-11-19 14:55:58 -08003585 }
3586 tracksToRemove->add(track);
3587 // Avoids a misleading display in dumpsys
3588 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
3589 }
3590 continue;
3591 }
3592
3593 { // local variable scope to avoid goto warning
3594
3595 audio_track_cblk_t* cblk = track->cblk();
3596
3597 // The first time a track is added we wait
3598 // for all its buffers to be filled before processing it
3599 int name = track->name();
3600 // make sure that we have enough frames to mix one full buffer.
3601 // enforce this condition only once to enable draining the buffer in case the client
3602 // app does not call stop() and relies on underrun to stop:
3603 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
3604 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003605 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07003606 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003607 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003608
3609 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003610 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003611 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
3612 // add frames already consumed but not yet released by the resampler
3613 // because mAudioTrackServerProxy->framesReady() will include these frames
3614 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
3615
Eric Laurent81784c32012-11-19 14:55:58 -08003616 uint32_t minFrames = 1;
3617 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
3618 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003619 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08003620 }
Eric Laurent13e4c962013-12-20 17:36:01 -08003621
3622 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07003623 if (ATRACE_ENABLED()) {
3624 // I wish we had formatted trace names
3625 char traceName[16];
3626 strcpy(traceName, "nRdy");
3627 int name = track->name();
3628 if (AudioMixer::TRACK0 <= name &&
3629 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
3630 name -= AudioMixer::TRACK0;
3631 traceName[4] = (name / 10) + '0';
3632 traceName[5] = (name % 10) + '0';
3633 } else {
3634 traceName[4] = '?';
3635 traceName[5] = '?';
3636 }
3637 traceName[6] = '\0';
3638 ATRACE_INT(traceName, framesReady);
3639 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003640 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08003641 !track->isPaused() && !track->isTerminated())
3642 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003643 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003644
3645 mixedTracks++;
3646
Andy Hung69aed5f2014-02-25 17:24:40 -08003647 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
3648 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08003649 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08003650 if (track->mainBuffer() != mSinkBuffer &&
3651 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08003652 if (mEffectBufferEnabled) {
3653 mEffectBufferValid = true; // Later can set directly.
3654 }
Eric Laurent81784c32012-11-19 14:55:58 -08003655 chain = getEffectChain_l(track->sessionId());
3656 // Delegate volume control to effect in track effect chain if needed
3657 if (chain != 0) {
3658 tracksWithEffect++;
3659 } else {
3660 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3661 "session %d",
3662 name, track->sessionId());
3663 }
3664 }
3665
3666
3667 int param = AudioMixer::VOLUME;
3668 if (track->mFillingUpStatus == Track::FS_FILLED) {
3669 // no ramp for the first volume setting
3670 track->mFillingUpStatus = Track::FS_ACTIVE;
3671 if (track->mState == TrackBase::RESUMING) {
3672 track->mState = TrackBase::ACTIVE;
3673 param = AudioMixer::RAMP_VOLUME;
3674 }
3675 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003676 // FIXME should not make a decision based on mServer
3677 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003678 // If the track is stopped before the first frame was mixed,
3679 // do not apply ramp
3680 param = AudioMixer::RAMP_VOLUME;
3681 }
3682
3683 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07003684 uint32_t vl, vr; // in U8.24 integer format
3685 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08003686 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07003687 vl = vr = 0;
3688 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08003689 if (track->isPausing()) {
3690 track->setPaused();
3691 }
3692 } else {
3693
3694 // read original volumes with volume control
3695 float typeVolume = mStreamTypes[track->streamType()].volume;
3696 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003697 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07003698 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07003699 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
3700 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08003701 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07003702 if (vlf > GAIN_FLOAT_UNITY) {
3703 ALOGV("Track left volume out of range: %.3g", vlf);
3704 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003705 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07003706 if (vrf > GAIN_FLOAT_UNITY) {
3707 ALOGV("Track right volume out of range: %.3g", vrf);
3708 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08003709 }
3710 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07003711 vlf *= v;
3712 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08003713 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07003714 // then derive vl and vr as U8.24 versions for the effect chain
3715 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
3716 vl = (uint32_t) (scaleto8_24 * vlf);
3717 vr = (uint32_t) (scaleto8_24 * vrf);
3718 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08003719 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08003720 // send level comes from shared memory and so may be corrupt
3721 if (sendLevel > MAX_GAIN_INT) {
3722 ALOGV("Track send level out of range: %04X", sendLevel);
3723 sendLevel = MAX_GAIN_INT;
3724 }
Andy Hung6be49402014-05-30 10:42:03 -07003725 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
3726 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08003727 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003728
Eric Laurent81784c32012-11-19 14:55:58 -08003729 // Delegate volume control to effect in track effect chain if needed
3730 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3731 // Do not ramp volume if volume is controlled by effect
3732 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08003733 // Update remaining floating point volume levels
3734 vlf = (float)vl / (1 << 24);
3735 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08003736 track->mHasVolumeController = true;
3737 } else {
3738 // force no volume ramp when volume controller was just disabled or removed
3739 // from effect chain to avoid volume spike
3740 if (track->mHasVolumeController) {
3741 param = AudioMixer::VOLUME;
3742 }
3743 track->mHasVolumeController = false;
3744 }
3745
Eric Laurent81784c32012-11-19 14:55:58 -08003746 // XXX: these things DON'T need to be done each time
3747 mAudioMixer->setBufferProvider(name, track);
3748 mAudioMixer->enable(name);
3749
Andy Hung6be49402014-05-30 10:42:03 -07003750 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
3751 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
3752 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08003753 mAudioMixer->setParameter(
3754 name,
3755 AudioMixer::TRACK,
3756 AudioMixer::FORMAT, (void *)track->format());
3757 mAudioMixer->setParameter(
3758 name,
3759 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003760 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07003761 mAudioMixer->setParameter(
3762 name,
3763 AudioMixer::TRACK,
3764 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08003765 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07003766 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003767 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08003768 if (reqSampleRate == 0) {
3769 reqSampleRate = mSampleRate;
3770 } else if (reqSampleRate > maxSampleRate) {
3771 reqSampleRate = maxSampleRate;
3772 }
Eric Laurent81784c32012-11-19 14:55:58 -08003773 mAudioMixer->setParameter(
3774 name,
3775 AudioMixer::RESAMPLE,
3776 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003777 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003778
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003779 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07003780 mAudioMixer->setParameter(
3781 name,
3782 AudioMixer::TIMESTRETCH,
3783 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07003784 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07003785
Andy Hung69aed5f2014-02-25 17:24:40 -08003786 /*
3787 * Select the appropriate output buffer for the track.
3788 *
Andy Hung98ef9782014-03-04 14:46:50 -08003789 * Tracks with effects go into their own effects chain buffer
3790 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08003791 *
3792 * Other tracks can use mMixerBuffer for higher precision
3793 * channel accumulation. If this buffer is enabled
3794 * (mMixerBufferEnabled true), then selected tracks will accumulate
3795 * into it.
3796 *
3797 */
3798 if (mMixerBufferEnabled
3799 && (track->mainBuffer() == mSinkBuffer
3800 || track->mainBuffer() == mMixerBuffer)) {
3801 mAudioMixer->setParameter(
3802 name,
3803 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003804 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08003805 mAudioMixer->setParameter(
3806 name,
3807 AudioMixer::TRACK,
3808 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
3809 // TODO: override track->mainBuffer()?
3810 mMixerBufferValid = true;
3811 } else {
3812 mAudioMixer->setParameter(
3813 name,
3814 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08003815 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08003816 mAudioMixer->setParameter(
3817 name,
3818 AudioMixer::TRACK,
3819 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3820 }
Eric Laurent81784c32012-11-19 14:55:58 -08003821 mAudioMixer->setParameter(
3822 name,
3823 AudioMixer::TRACK,
3824 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3825
3826 // reset retry count
3827 track->mRetryCount = kMaxTrackRetries;
3828
3829 // If one track is ready, set the mixer ready if:
3830 // - the mixer was not ready during previous round OR
3831 // - no other track is not ready
3832 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
3833 mixerStatus != MIXER_TRACKS_ENABLED) {
3834 mixerStatus = MIXER_TRACKS_READY;
3835 }
3836 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003837 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Glenn Kasten82aaf942013-07-17 16:05:07 -07003838 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08003839 }
Eric Laurent81784c32012-11-19 14:55:58 -08003840 // clear effect chain input buffer if an active track underruns to avoid sending
3841 // previous audio buffer again to effects
3842 chain = getEffectChain_l(track->sessionId());
3843 if (chain != 0) {
3844 chain->clearInputBuffer();
3845 }
3846
Glenn Kastenf20e1d82013-07-12 09:45:18 -07003847 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003848 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3849 track->isStopped() || track->isPaused()) {
3850 // We have consumed all the buffers of this track.
3851 // Remove it from the list of active tracks.
3852 // TODO: use actual buffer filling status instead of latency when available from
3853 // audio HAL
3854 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
3855 size_t framesWritten = mBytesWritten / mFrameSize;
3856 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
3857 if (track->isStopped()) {
3858 track->reset();
3859 }
3860 tracksToRemove->add(track);
3861 }
3862 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08003863 // No buffers for this track. Give it a few chances to
3864 // fill a buffer, then remove it from active list.
3865 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08003866 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08003867 tracksToRemove->add(track);
3868 // indicate to client process that the track was disabled because of underrun;
3869 // it will then automatically call start() when data is available
Glenn Kasten96f60d82013-07-12 10:21:18 -07003870 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurent81784c32012-11-19 14:55:58 -08003871 // If one track is not ready, mark the mixer also not ready if:
3872 // - the mixer was ready during previous round OR
3873 // - no other track is ready
3874 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
3875 mixerStatus != MIXER_TRACKS_READY) {
3876 mixerStatus = MIXER_TRACKS_ENABLED;
3877 }
3878 }
3879 mAudioMixer->disable(name);
3880 }
3881
3882 } // local variable scope to avoid goto warning
3883track_is_ready: ;
3884
3885 }
3886
3887 // Push the new FastMixer state if necessary
3888 bool pauseAudioWatchdog = false;
3889 if (didModify) {
3890 state->mFastTracksGen++;
3891 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3892 if (kUseFastMixer == FastMixer_Dynamic &&
3893 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3894 state->mCommand = FastMixerState::COLD_IDLE;
3895 state->mColdFutexAddr = &mFastMixerFutex;
3896 state->mColdGen++;
3897 mFastMixerFutex = 0;
3898 if (kUseFastMixer == FastMixer_Dynamic) {
3899 mNormalSink = mOutputSink;
3900 }
3901 // If we go into cold idle, need to wait for acknowledgement
3902 // so that fast mixer stops doing I/O.
3903 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3904 pauseAudioWatchdog = true;
3905 }
Eric Laurent81784c32012-11-19 14:55:58 -08003906 }
3907 if (sq != NULL) {
3908 sq->end(didModify);
3909 sq->push(block);
3910 }
3911#ifdef AUDIO_WATCHDOG
3912 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3913 mAudioWatchdog->pause();
3914 }
3915#endif
3916
3917 // Now perform the deferred reset on fast tracks that have stopped
3918 while (resetMask != 0) {
3919 size_t i = __builtin_ctz(resetMask);
3920 ALOG_ASSERT(i < count);
3921 resetMask &= ~(1 << i);
3922 sp<Track> t = mActiveTracks[i].promote();
3923 if (t == 0) {
3924 continue;
3925 }
3926 Track* track = t.get();
3927 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3928 track->reset();
3929 }
3930
3931 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08003932 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08003933
Eric Laurent97d547d2014-09-02 14:45:53 -07003934 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
3935 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07003936 }
3937
3938 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07003939 // as long as there are effects we should clear the effects buffer, to avoid
3940 // passing a non-clean buffer to the effect chain
3941 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07003942 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003943 // sink or mix buffer must be cleared if all tracks are connected to an
3944 // effect chain as in this case the mixer will not write to the sink or mix buffer
3945 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08003946 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3947 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08003948 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08003949 if (mMixerBufferValid) {
3950 memset(mMixerBuffer, 0, mMixerBufferSize);
3951 // TODO: In testing, mSinkBuffer below need not be cleared because
3952 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
3953 // after mixing.
3954 //
3955 // To enforce this guarantee:
3956 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3957 // (mixedTracks == 0 && fastTracks > 0))
3958 // must imply MIXER_TRACKS_READY.
3959 // Later, we may clear buffers regardless, and skip much of this logic.
3960 }
Andy Hung98ef9782014-03-04 14:46:50 -08003961 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07003962 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003963 }
3964
3965 // if any fast tracks, then status is ready
3966 mMixerStatusIgnoringFastTracks = mixerStatus;
3967 if (fastTracks > 0) {
3968 mixerStatus = MIXER_TRACKS_READY;
3969 }
3970 return mixerStatus;
3971}
3972
3973// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07003974int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
3975 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003976{
Andy Hunge8a1ced2014-05-09 15:02:21 -07003977 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08003978}
3979
3980// deleteTrackName_l() must be called with ThreadBase::mLock held
3981void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3982{
3983 ALOGV("remove track (%d) and delete from mixer", name);
3984 mAudioMixer->deleteTrackName(name);
3985}
3986
Eric Laurent10351942014-05-08 18:49:52 -07003987// checkForNewParameter_l() must be called with ThreadBase::mLock held
3988bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
3989 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08003990{
Eric Laurent81784c32012-11-19 14:55:58 -08003991 bool reconfig = false;
3992
Eric Laurent10351942014-05-08 18:49:52 -07003993 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08003994
Eric Laurent10351942014-05-08 18:49:52 -07003995 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3996 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003997 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07003998 FastMixerStateQueue *sq = mFastMixer->sq();
3999 FastMixerState *state = sq->begin();
4000 if (!(state->mCommand & FastMixerState::IDLE)) {
4001 previousCommand = state->mCommand;
4002 state->mCommand = FastMixerState::HOT_IDLE;
4003 sq->end();
4004 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4005 } else {
4006 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004007 }
Eric Laurent10351942014-05-08 18:49:52 -07004008 }
Eric Laurent81784c32012-11-19 14:55:58 -08004009
Eric Laurent10351942014-05-08 18:49:52 -07004010 AudioParameter param = AudioParameter(keyValuePair);
4011 int value;
4012 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4013 reconfig = true;
4014 }
4015 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004016 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004017 status = BAD_VALUE;
4018 } else {
4019 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004020 reconfig = true;
4021 }
Eric Laurent10351942014-05-08 18:49:52 -07004022 }
4023 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004024 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004025 status = BAD_VALUE;
4026 } else {
4027 // no need to save value, since it's constant
4028 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004029 }
Eric Laurent10351942014-05-08 18:49:52 -07004030 }
4031 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4032 // do not accept frame count changes if tracks are open as the track buffer
4033 // size depends on frame count and correct behavior would not be guaranteed
4034 // if frame count is changed after track creation
4035 if (!mTracks.isEmpty()) {
4036 status = INVALID_OPERATION;
4037 } else {
4038 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004039 }
Eric Laurent10351942014-05-08 18:49:52 -07004040 }
4041 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004042#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004043 // when changing the audio output device, call addBatteryData to notify
4044 // the change
4045 if (mOutDevice != value) {
4046 uint32_t params = 0;
4047 // check whether speaker is on
4048 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4049 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004050 }
Eric Laurent10351942014-05-08 18:49:52 -07004051
4052 audio_devices_t deviceWithoutSpeaker
4053 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4054 // check if any other device (except speaker) is on
4055 if (value & deviceWithoutSpeaker ) {
4056 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4057 }
4058
4059 if (params != 0) {
4060 addBatteryData(params);
4061 }
4062 }
Eric Laurent81784c32012-11-19 14:55:58 -08004063#endif
4064
Eric Laurent10351942014-05-08 18:49:52 -07004065 // forward device change to effects that have requested to be
4066 // aware of attached audio device.
4067 if (value != AUDIO_DEVICE_NONE) {
4068 mOutDevice = value;
4069 for (size_t i = 0; i < mEffectChains.size(); i++) {
4070 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004071 }
4072 }
Eric Laurent10351942014-05-08 18:49:52 -07004073 }
Eric Laurent81784c32012-11-19 14:55:58 -08004074
Eric Laurent10351942014-05-08 18:49:52 -07004075 if (status == NO_ERROR) {
4076 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4077 keyValuePair.string());
4078 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004079 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004080 mStandby = true;
4081 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004082 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004083 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004084 }
Eric Laurent10351942014-05-08 18:49:52 -07004085 if (status == NO_ERROR && reconfig) {
4086 readOutputParameters_l();
4087 delete mAudioMixer;
4088 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4089 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004090 int name = getTrackName_l(mTracks[i]->mChannelMask,
4091 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004092 if (name < 0) {
4093 break;
4094 }
4095 mTracks[i]->mName = name;
4096 }
4097 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4098 }
Eric Laurent81784c32012-11-19 14:55:58 -08004099 }
4100
4101 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004102 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004103 FastMixerStateQueue *sq = mFastMixer->sq();
4104 FastMixerState *state = sq->begin();
4105 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4106 state->mCommand = previousCommand;
4107 sq->end();
4108 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4109 }
4110
4111 return reconfig;
4112}
4113
4114
4115void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4116{
4117 const size_t SIZE = 256;
4118 char buffer[SIZE];
4119 String8 result;
4120
4121 PlaybackThread::dumpInternals(fd, args);
4122
Elliott Hughes87cebad2014-05-22 10:14:43 -07004123 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Eric Laurent81784c32012-11-19 14:55:58 -08004124
4125 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004126 const FastMixerDumpState copy(mFastMixerDumpState);
Eric Laurent81784c32012-11-19 14:55:58 -08004127 copy.dump(fd);
4128
4129#ifdef STATE_QUEUE_DUMP
4130 // Similar for state queue
4131 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4132 observerCopy.dump(fd);
4133 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4134 mutatorCopy.dump(fd);
4135#endif
4136
Glenn Kasten46909e72013-02-26 09:20:22 -08004137#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004138 // Write the tee output to a .wav file
4139 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004140#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004141
4142#ifdef AUDIO_WATCHDOG
4143 if (mAudioWatchdog != 0) {
4144 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4145 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4146 wdCopy.dump(fd);
4147 }
4148#endif
4149}
4150
4151uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4152{
4153 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4154}
4155
4156uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4157{
4158 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4159}
4160
4161void AudioFlinger::MixerThread::cacheParameters_l()
4162{
4163 PlaybackThread::cacheParameters_l();
4164
4165 // FIXME: Relaxed timing because of a certain device that can't meet latency
4166 // Should be reduced to 2x after the vendor fixes the driver issue
4167 // increase threshold again due to low power audio mode. The way this warning
4168 // threshold is calculated and its usefulness should be reconsidered anyway.
4169 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4170}
4171
4172// ----------------------------------------------------------------------------
4173
4174AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4175 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
4176 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
4177 // mLeftVolFloat, mRightVolFloat
4178{
4179}
4180
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4182 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
4183 ThreadBase::type_t type)
4184 : PlaybackThread(audioFlinger, output, id, device, type)
4185 // mLeftVolFloat, mRightVolFloat
4186{
4187}
4188
Eric Laurent81784c32012-11-19 14:55:58 -08004189AudioFlinger::DirectOutputThread::~DirectOutputThread()
4190{
4191}
4192
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4194{
4195 audio_track_cblk_t* cblk = track->cblk();
4196 float left, right;
4197
4198 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4199 left = right = 0;
4200 } else {
4201 float typeVolume = mStreamTypes[track->streamType()].volume;
4202 float v = mMasterVolume * typeVolume;
4203 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004204 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4205 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4206 if (left > GAIN_FLOAT_UNITY) {
4207 left = GAIN_FLOAT_UNITY;
4208 }
4209 left *= v;
4210 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4211 if (right > GAIN_FLOAT_UNITY) {
4212 right = GAIN_FLOAT_UNITY;
4213 }
4214 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004215 }
4216
4217 if (lastTrack) {
4218 if (left != mLeftVolFloat || right != mRightVolFloat) {
4219 mLeftVolFloat = left;
4220 mRightVolFloat = right;
4221
4222 // Convert volumes from float to 8.24
4223 uint32_t vl = (uint32_t)(left * (1 << 24));
4224 uint32_t vr = (uint32_t)(right * (1 << 24));
4225
4226 // Delegate volume control to effect in track effect chain if needed
4227 // only one effect chain can be present on DirectOutputThread, so if
4228 // there is one, the track is connected to it
4229 if (!mEffectChains.isEmpty()) {
4230 mEffectChains[0]->setVolume_l(&vl, &vr);
4231 left = (float)vl / (1 << 24);
4232 right = (float)vr / (1 << 24);
4233 }
4234 if (mOutput->stream->set_volume) {
4235 mOutput->stream->set_volume(mOutput->stream, left, right);
4236 }
4237 }
4238 }
4239}
4240
4241
Eric Laurent81784c32012-11-19 14:55:58 -08004242AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4243 Vector< sp<Track> > *tracksToRemove
4244)
4245{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004246 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004247 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004248 bool doHwPause = false;
4249 bool doHwResume = false;
4250 bool flushPending = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004251
4252 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004253 for (size_t i = 0; i < count; i++) {
4254 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004255 // The track died recently
4256 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004257 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004258 }
4259
4260 Track* const track = t.get();
4261 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004262 // Only consider last track started for volume and mixer state control.
4263 // In theory an older track could underrun and restart after the new one starts
4264 // but as we only care about the transition phase between two tracks on a
4265 // direct output, it is not a problem to ignore the underrun case.
4266 sp<Track> l = mLatestActiveTrack.promote();
4267 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004268
Eric Laurentd1f69b02014-12-15 14:33:13 -08004269 if (mHwSupportsPause && track->isPausing()) {
4270 track->setPaused();
4271 if (last && !mHwPaused) {
4272 doHwPause = true;
4273 mHwPaused = true;
4274 }
4275 tracksToRemove->add(track);
4276 } else if (track->isFlushPending()) {
4277 track->flushAck();
4278 if (last) {
4279 flushPending = true;
4280 }
4281 } else if (mHwSupportsPause && track->isResumePending()){
4282 track->resumeAck();
4283 if (last) {
4284 if (mHwPaused) {
4285 doHwResume = true;
4286 mHwPaused = false;
4287 }
4288 }
4289 }
4290
Eric Laurent81784c32012-11-19 14:55:58 -08004291 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004292 // for all its buffers to be filled before processing it.
4293 // Allow draining the buffer in case the client
4294 // app does not call stop() and relies on underrun to stop:
4295 // hence the test on (track->mRetryCount > 1).
4296 // If retryCount<=1 then track is about to underrun and be removed.
Eric Laurent81784c32012-11-19 14:55:58 -08004297 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004298 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
4299 && (track->mRetryCount > 1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004300 minFrames = mNormalFrameCount;
4301 } else {
4302 minFrames = 1;
4303 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004304
Eric Laurentab5cdba2014-06-09 17:22:27 -07004305 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4306 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004307 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004308 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004309
4310 if (track->mFillingUpStatus == Track::FS_FILLED) {
4311 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004312 // make sure processVolume_l() will apply new volume even if 0
4313 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004314 if (!mHwSupportsPause) {
4315 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004316 }
4317 }
4318
4319 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004320 processVolume_l(track, last);
4321 if (last) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004322 // reset retry count
4323 track->mRetryCount = kMaxTrackRetriesDirect;
4324 mActiveTrack = t;
4325 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004326 if (usesHwAvSync() && mHwPaused) {
4327 doHwResume = true;
4328 mHwPaused = false;
4329 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004330 }
Eric Laurent81784c32012-11-19 14:55:58 -08004331 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004332 // clear effect chain input buffer if the last active track started underruns
4333 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004334 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004335 mEffectChains[0]->clearInputBuffer();
4336 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004337 if (track->isStopping_1()) {
4338 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004339 if (last && mHwPaused) {
4340 doHwResume = true;
4341 mHwPaused = false;
4342 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004343 }
4344 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4345 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004346 // We have consumed all the buffers of this track.
4347 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004348 size_t audioHALFrames;
4349 if (audio_is_linear_pcm(mFormat)) {
4350 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4351 } else {
4352 audioHALFrames = 0;
4353 }
4354
Eric Laurent81784c32012-11-19 14:55:58 -08004355 size_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004356 if (mStandby || !last ||
4357 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004358 if (track->isStopping_2()) {
4359 track->mState = TrackBase::STOPPED;
4360 }
Eric Laurent81784c32012-11-19 14:55:58 -08004361 if (track->isStopped()) {
4362 track->reset();
4363 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004364 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004365 }
4366 } else {
4367 // No buffers for this track. Give it a few chances to
4368 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004369 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004370 if (--(track->mRetryCount) <= 0) {
4371 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004372 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004373 // indicate to client process that the track was disabled because of underrun;
4374 // it will then automatically call start() when data is available
4375 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004376 } else if (last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004377 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004378 if (usesHwAvSync() && !mHwPaused && !mStandby) {
4379 doHwPause = true;
4380 mHwPaused = true;
4381 }
Eric Laurent81784c32012-11-19 14:55:58 -08004382 }
4383 }
4384 }
4385 }
4386
Eric Laurentd1f69b02014-12-15 14:33:13 -08004387 // if an active track did not command a flush, check for pending flush on stopped tracks
4388 if (!flushPending) {
4389 for (size_t i = 0; i < mTracks.size(); i++) {
4390 if (mTracks[i]->isFlushPending()) {
4391 mTracks[i]->flushAck();
4392 flushPending = true;
4393 }
4394 }
4395 }
4396
4397 // make sure the pause/flush/resume sequence is executed in the right order.
4398 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4399 // before flush and then resume HW. This can happen in case of pause/flush/resume
4400 // if resume is received before pause is executed.
4401 if (mHwSupportsPause && !mStandby &&
4402 (doHwPause || (flushPending && !mHwPaused && (count != 0)))) {
4403 mOutput->stream->pause(mOutput->stream);
4404 }
4405 if (flushPending) {
4406 flushHw_l();
4407 }
4408 if (mHwSupportsPause && !mStandby && doHwResume) {
4409 mOutput->stream->resume(mOutput->stream);
4410 }
Eric Laurent81784c32012-11-19 14:55:58 -08004411 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004412 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004413
4414 return mixerStatus;
4415}
4416
4417void AudioFlinger::DirectOutputThread::threadLoop_mix()
4418{
Eric Laurent81784c32012-11-19 14:55:58 -08004419 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004420 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004421 // output audio to hardware
4422 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004423 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004424 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004425 status_t status = mActiveTrack->getNextBuffer(&buffer);
4426 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent81784c32012-11-19 14:55:58 -08004427 memset(curBuf, 0, frameCount * mFrameSize);
4428 break;
4429 }
4430 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4431 frameCount -= buffer.frameCount;
4432 curBuf += buffer.frameCount * mFrameSize;
4433 mActiveTrack->releaseBuffer(&buffer);
4434 }
Andy Hung2098f272014-02-27 14:00:06 -08004435 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004436 sleepTime = 0;
4437 standbyTime = systemTime() + standbyDelay;
4438 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004439}
4440
4441void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4442{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004443 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004444 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004445 sleepTime = idleSleepTime;
4446 return;
4447 }
Eric Laurent81784c32012-11-19 14:55:58 -08004448 if (sleepTime == 0) {
4449 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4450 sleepTime = activeSleepTime;
4451 } else {
4452 sleepTime = idleSleepTime;
4453 }
4454 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004455 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004456 sleepTime = 0;
4457 }
4458}
4459
Eric Laurentd1f69b02014-12-15 14:33:13 -08004460void AudioFlinger::DirectOutputThread::threadLoop_exit()
4461{
4462 {
4463 Mutex::Autolock _l(mLock);
4464 bool flushPending = false;
4465 for (size_t i = 0; i < mTracks.size(); i++) {
4466 if (mTracks[i]->isFlushPending()) {
4467 mTracks[i]->flushAck();
4468 flushPending = true;
4469 }
4470 }
4471 if (flushPending) {
4472 flushHw_l();
4473 }
4474 }
4475 PlaybackThread::threadLoop_exit();
4476}
4477
4478// must be called with thread mutex locked
4479bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4480{
4481 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004482 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004483
4484 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4485 // after a timeout and we will enter standby then.
4486 if (mTracks.size() > 0) {
4487 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004488 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4489 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004490 }
4491
Eric Laurentb369caf2015-03-30 20:51:47 -07004492 return !mStandby && !(trackPaused || (usesHwAvSync() && mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08004493}
4494
Eric Laurent81784c32012-11-19 14:55:58 -08004495// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004496int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07004497 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004498{
4499 return 0;
4500}
4501
4502// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08004503void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08004504{
4505}
4506
Eric Laurent10351942014-05-08 18:49:52 -07004507// checkForNewParameter_l() must be called with ThreadBase::mLock held
4508bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
4509 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004510{
4511 bool reconfig = false;
4512
Eric Laurent10351942014-05-08 18:49:52 -07004513 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004514
Eric Laurent10351942014-05-08 18:49:52 -07004515 AudioParameter param = AudioParameter(keyValuePair);
4516 int value;
4517 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4518 // forward device change to effects that have requested to be
4519 // aware of attached audio device.
4520 if (value != AUDIO_DEVICE_NONE) {
4521 mOutDevice = value;
4522 for (size_t i = 0; i < mEffectChains.size(); i++) {
4523 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07004524 }
4525 }
Eric Laurent81784c32012-11-19 14:55:58 -08004526 }
Eric Laurent10351942014-05-08 18:49:52 -07004527 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4528 // do not accept frame count changes if tracks are open as the track buffer
4529 // size depends on frame count and correct behavior would not be garantied
4530 // if frame count is changed after track creation
4531 if (!mTracks.isEmpty()) {
4532 status = INVALID_OPERATION;
4533 } else {
4534 reconfig = true;
4535 }
4536 }
4537 if (status == NO_ERROR) {
4538 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4539 keyValuePair.string());
4540 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004541 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004542 mStandby = true;
4543 mBytesWritten = 0;
4544 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4545 keyValuePair.string());
4546 }
4547 if (status == NO_ERROR && reconfig) {
4548 readOutputParameters_l();
4549 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
4550 }
4551 }
4552
Eric Laurent81784c32012-11-19 14:55:58 -08004553 return reconfig;
4554}
4555
4556uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
4557{
4558 uint32_t time;
4559 if (audio_is_linear_pcm(mFormat)) {
4560 time = PlaybackThread::activeSleepTimeUs();
4561 } else {
4562 time = 10000;
4563 }
4564 return time;
4565}
4566
4567uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
4568{
4569 uint32_t time;
4570 if (audio_is_linear_pcm(mFormat)) {
4571 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
4572 } else {
4573 time = 10000;
4574 }
4575 return time;
4576}
4577
4578uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
4579{
4580 uint32_t time;
4581 if (audio_is_linear_pcm(mFormat)) {
4582 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4583 } else {
4584 time = 10000;
4585 }
4586 return time;
4587}
4588
4589void AudioFlinger::DirectOutputThread::cacheParameters_l()
4590{
4591 PlaybackThread::cacheParameters_l();
4592
4593 // use shorter standby delay as on normal output to release
4594 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07004595 // no delay on outputs with HW A/V sync
4596 if (usesHwAvSync()) {
4597 standbyDelay = 0;
4598 } else if (audio_is_linear_pcm(mFormat)) {
Eric Laurent972a1732013-09-04 09:42:59 -07004599 standbyDelay = microseconds(activeSleepTime*2);
4600 } else {
4601 standbyDelay = kOffloadStandbyDelayNs;
4602 }
Eric Laurent81784c32012-11-19 14:55:58 -08004603}
4604
Eric Laurente659ef42014-09-29 13:06:46 -07004605void AudioFlinger::DirectOutputThread::flushHw_l()
4606{
Phil Burk062e67a2015-02-11 13:40:50 -08004607 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08004608 mHwPaused = false;
Eric Laurente659ef42014-09-29 13:06:46 -07004609}
4610
Eric Laurent81784c32012-11-19 14:55:58 -08004611// ----------------------------------------------------------------------------
4612
Eric Laurentbfb1b832013-01-07 09:53:42 -08004613AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07004614 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004615 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07004616 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07004617 mWriteAckSequence(0),
4618 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004619{
4620}
4621
4622AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
4623{
4624}
4625
4626void AudioFlinger::AsyncCallbackThread::onFirstRef()
4627{
4628 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
4629}
4630
4631bool AudioFlinger::AsyncCallbackThread::threadLoop()
4632{
4633 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004634 uint32_t writeAckSequence;
4635 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004636
4637 {
4638 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08004639 while (!((mWriteAckSequence & 1) ||
4640 (mDrainSequence & 1) ||
4641 exitPending())) {
4642 mWaitWorkCV.wait(mLock);
4643 }
4644
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645 if (exitPending()) {
4646 break;
4647 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004648 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
4649 mWriteAckSequence, mDrainSequence);
4650 writeAckSequence = mWriteAckSequence;
4651 mWriteAckSequence &= ~1;
4652 drainSequence = mDrainSequence;
4653 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004654 }
4655 {
Eric Laurent4de95592013-09-26 15:28:21 -07004656 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
4657 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004658 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004659 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004660 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07004661 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07004662 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004663 }
4664 }
4665 }
4666 }
4667 return false;
4668}
4669
4670void AudioFlinger::AsyncCallbackThread::exit()
4671{
4672 ALOGV("AsyncCallbackThread::exit");
4673 Mutex::Autolock _l(mLock);
4674 requestExit();
4675 mWaitWorkCV.broadcast();
4676}
4677
Eric Laurent3b4529e2013-09-05 18:09:19 -07004678void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004679{
4680 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004681 // bit 0 is cleared
4682 mWriteAckSequence = sequence << 1;
4683}
4684
4685void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
4686{
4687 Mutex::Autolock _l(mLock);
4688 // ignore unexpected callbacks
4689 if (mWriteAckSequence & 2) {
4690 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004691 mWaitWorkCV.signal();
4692 }
4693}
4694
Eric Laurent3b4529e2013-09-05 18:09:19 -07004695void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004696{
4697 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004698 // bit 0 is cleared
4699 mDrainSequence = sequence << 1;
4700}
4701
4702void AudioFlinger::AsyncCallbackThread::resetDraining()
4703{
4704 Mutex::Autolock _l(mLock);
4705 // ignore unexpected callbacks
4706 if (mDrainSequence & 2) {
4707 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004708 mWaitWorkCV.signal();
4709 }
4710}
4711
4712
4713// ----------------------------------------------------------------------------
4714AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
4715 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
4716 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD),
Eric Laurentd7e59222013-11-15 12:02:28 -08004717 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718{
Eric Laurentfd477972013-10-25 18:10:40 -07004719 //FIXME: mStandby should be set to true by ThreadBase constructor
4720 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004721}
4722
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723void AudioFlinger::OffloadThread::threadLoop_exit()
4724{
4725 if (mFlushPending || mHwPaused) {
4726 // If a flush is pending or track was paused, just discard buffered data
4727 flushHw_l();
4728 } else {
4729 mMixerStatus = MIXER_DRAIN_ALL;
4730 threadLoop_drain();
4731 }
Uday Gupta56604aa2014-05-13 11:19:17 -07004732 if (mUseAsyncWrite) {
4733 ALOG_ASSERT(mCallbackThread != 0);
4734 mCallbackThread->exit();
4735 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004736 PlaybackThread::threadLoop_exit();
4737}
4738
4739AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
4740 Vector< sp<Track> > *tracksToRemove
4741)
4742{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004743 size_t count = mActiveTracks.size();
4744
4745 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07004746 bool doHwPause = false;
4747 bool doHwResume = false;
4748
Eric Laurentede6c3b2013-09-19 14:37:46 -07004749 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
4750
Eric Laurentbfb1b832013-01-07 09:53:42 -08004751 // find out which tracks need to be processed
4752 for (size_t i = 0; i < count; i++) {
4753 sp<Track> t = mActiveTracks[i].promote();
4754 // The track died recently
4755 if (t == 0) {
4756 continue;
4757 }
4758 Track* const track = t.get();
4759 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004760 // Only consider last track started for volume and mixer state control.
4761 // In theory an older track could underrun and restart after the new one starts
4762 // but as we only care about the transition phase between two tracks on a
4763 // direct output, it is not a problem to ignore the underrun case.
4764 sp<Track> l = mLatestActiveTrack.promote();
4765 bool last = l.get() == track;
4766
Haynes Mathew George7844f672014-01-15 12:32:55 -08004767 if (track->isInvalid()) {
4768 ALOGW("An invalidated track shouldn't be in active list");
4769 tracksToRemove->add(track);
4770 continue;
4771 }
4772
4773 if (track->mState == TrackBase::IDLE) {
4774 ALOGW("An idle track shouldn't be in active list");
4775 continue;
4776 }
4777
Eric Laurentbfb1b832013-01-07 09:53:42 -08004778 if (track->isPausing()) {
4779 track->setPaused();
4780 if (last) {
4781 if (!mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07004782 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004783 mHwPaused = true;
4784 }
4785 // If we were part way through writing the mixbuffer to
4786 // the HAL we must save this until we resume
4787 // BUG - this will be wrong if a different track is made active,
4788 // in that case we want to discard the pending data in the
4789 // mixbuffer and tell the client to present it again when the
4790 // track is resumed
4791 mPausedWriteLength = mCurrentWriteLength;
4792 mPausedBytesRemaining = mBytesRemaining;
4793 mBytesRemaining = 0; // stop writing
4794 }
4795 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08004796 } else if (track->isFlushPending()) {
4797 track->flushAck();
4798 if (last) {
4799 mFlushPending = true;
4800 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08004801 } else if (track->isResumePending()){
4802 track->resumeAck();
4803 if (last) {
4804 if (mPausedBytesRemaining) {
4805 // Need to continue write that was interrupted
4806 mCurrentWriteLength = mPausedWriteLength;
4807 mBytesRemaining = mPausedBytesRemaining;
4808 mPausedBytesRemaining = 0;
4809 }
4810 if (mHwPaused) {
4811 doHwResume = true;
4812 mHwPaused = false;
4813 // threadLoop_mix() will handle the case that we need to
4814 // resume an interrupted write
4815 }
4816 // enable write to audio HAL
4817 sleepTime = 0;
4818
4819 // Do not handle new data in this iteration even if track->framesReady()
4820 mixerStatus = MIXER_TRACKS_ENABLED;
4821 }
4822 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07004823 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004824 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004825 if (track->mFillingUpStatus == Track::FS_FILLED) {
4826 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004827 // make sure processVolume_l() will apply new volume even if 0
4828 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004829 }
4830
4831 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08004832 sp<Track> previousTrack = mPreviousTrack.promote();
4833 if (previousTrack != 0) {
4834 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08004835 // Flush any data still being written from last track
4836 mBytesRemaining = 0;
4837 if (mPausedBytesRemaining) {
4838 // Last track was paused so we also need to flush saved
4839 // mixbuffer state and invalidate track so that it will
4840 // re-submit that unwritten data when it is next resumed
4841 mPausedBytesRemaining = 0;
4842 // Invalidate is a bit drastic - would be more efficient
4843 // to have a flag to tell client that some of the
4844 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08004845 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004846 }
4847 // flush data already sent to the DSP if changing audio session as audio
4848 // comes from a different source. Also invalidate previous track to force a
4849 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08004850 if (previousTrack->sessionId() != track->sessionId()) {
4851 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08004852 }
4853 }
4854 }
4855 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004856 // reset retry count
4857 track->mRetryCount = kMaxTrackRetriesOffload;
4858 mActiveTrack = t;
4859 mixerStatus = MIXER_TRACKS_READY;
4860 }
4861 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004862 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004863 if (track->isStopping_1()) {
4864 // Hardware buffer can hold a large amount of audio so we must
4865 // wait for all current track's data to drain before we say
4866 // that the track is stopped.
4867 if (mBytesRemaining == 0) {
4868 // Only start draining when all data in mixbuffer
4869 // has been written
4870 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
4871 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004872 // do not drain if no data was ever sent to HAL (mStandby == true)
4873 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004874 // do not modify drain sequence if we are already draining. This happens
4875 // when resuming from pause after drain.
4876 if ((mDrainSequence & 1) == 0) {
4877 sleepTime = 0;
4878 standbyTime = systemTime() + standbyDelay;
4879 mixerStatus = MIXER_DRAIN_TRACK;
4880 mDrainSequence += 2;
4881 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004882 if (mHwPaused) {
4883 // It is possible to move from PAUSED to STOPPING_1 without
4884 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08004885 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004886 mHwPaused = false;
4887 }
4888 }
4889 }
4890 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07004891 // Drain has completed or we are in standby, signal presentation complete
4892 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004893 track->mState = TrackBase::STOPPED;
4894 size_t audioHALFrames =
4895 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
4896 size_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08004897 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004898 track->presentationComplete(framesWritten, audioHALFrames);
4899 track->reset();
4900 tracksToRemove->add(track);
4901 }
4902 } else {
4903 // No buffers for this track. Give it a few chances to
4904 // fill a buffer, then remove it from active list.
4905 if (--(track->mRetryCount) <= 0) {
4906 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
4907 track->name());
4908 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004909 // indicate to client process that the track was disabled because of underrun;
4910 // it will then automatically call start() when data is available
4911 android_atomic_or(CBLK_DISABLED, &cblk->mFlags);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004912 } else if (last){
4913 mixerStatus = MIXER_TRACKS_ENABLED;
4914 }
4915 }
4916 }
4917 // compute volume for this track
4918 processVolume_l(track, last);
4919 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004920
Eric Laurentea0fade2013-10-04 16:23:48 -07004921 // make sure the pause/flush/resume sequence is executed in the right order.
4922 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4923 // before flush and then resume HW. This can happen in case of pause/flush/resume
4924 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07004925 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07004926 mOutput->stream->pause(mOutput->stream);
4927 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004928 if (mFlushPending) {
4929 flushHw_l();
4930 mFlushPending = false;
4931 }
Eric Laurentfd477972013-10-25 18:10:40 -07004932 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07004933 mOutput->stream->resume(mOutput->stream);
4934 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07004935
Eric Laurentbfb1b832013-01-07 09:53:42 -08004936 // remove all the tracks that need to be...
4937 removeTracks_l(*tracksToRemove);
4938
4939 return mixerStatus;
4940}
4941
Eric Laurentbfb1b832013-01-07 09:53:42 -08004942// must be called with thread mutex locked
4943bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
4944{
Eric Laurent3b4529e2013-09-05 18:09:19 -07004945 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
4946 mWriteAckSequence, mDrainSequence);
4947 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948 return true;
4949 }
4950 return false;
4951}
4952
Eric Laurentbfb1b832013-01-07 09:53:42 -08004953bool AudioFlinger::OffloadThread::waitingAsyncCallback()
4954{
4955 Mutex::Autolock _l(mLock);
4956 return waitingAsyncCallback_l();
4957}
4958
4959void AudioFlinger::OffloadThread::flushHw_l()
4960{
Eric Laurente659ef42014-09-29 13:06:46 -07004961 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004962 // Flush anything still waiting in the mixbuffer
4963 mCurrentWriteLength = 0;
4964 mBytesRemaining = 0;
4965 mPausedWriteLength = 0;
4966 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08004967
Eric Laurentbfb1b832013-01-07 09:53:42 -08004968 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004969 // discard any pending drain or write ack by incrementing sequence
4970 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4971 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004972 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004973 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4974 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004975 }
4976}
4977
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004978void AudioFlinger::OffloadThread::onAddNewTrack_l()
4979{
4980 sp<Track> previousTrack = mPreviousTrack.promote();
4981 sp<Track> latestTrack = mLatestActiveTrack.promote();
4982
4983 if (previousTrack != 0 && latestTrack != 0 &&
4984 (previousTrack->sessionId() != latestTrack->sessionId())) {
4985 mFlushPending = true;
4986 }
4987 PlaybackThread::onAddNewTrack_l();
4988}
4989
Eric Laurentbfb1b832013-01-07 09:53:42 -08004990// ----------------------------------------------------------------------------
4991
Eric Laurent81784c32012-11-19 14:55:58 -08004992AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
4993 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
4994 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4995 DUPLICATING),
4996 mWaitTimeMs(UINT_MAX)
4997{
4998 addOutputTrack(mainThread);
4999}
5000
5001AudioFlinger::DuplicatingThread::~DuplicatingThread()
5002{
5003 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5004 mOutputTracks[i]->destroy();
5005 }
5006}
5007
5008void AudioFlinger::DuplicatingThread::threadLoop_mix()
5009{
5010 // mix buffers...
5011 if (outputsReady(outputTracks)) {
5012 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
5013 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005014 if (mMixerBufferValid) {
5015 memset(mMixerBuffer, 0, mMixerBufferSize);
5016 } else {
5017 memset(mSinkBuffer, 0, mSinkBufferSize);
5018 }
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
5020 sleepTime = 0;
5021 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005022 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005023 standbyTime = systemTime() + standbyDelay;
5024}
5025
5026void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5027{
5028 if (sleepTime == 0) {
5029 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5030 sleepTime = activeSleepTime;
5031 } else {
5032 sleepTime = idleSleepTime;
5033 }
5034 } else if (mBytesWritten != 0) {
5035 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5036 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005037 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005038 } else {
5039 // flush remaining overflow buffers in output tracks
5040 writeFrames = 0;
5041 }
5042 sleepTime = 0;
5043 }
5044}
5045
Eric Laurentbfb1b832013-01-07 09:53:42 -08005046ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005047{
5048 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005049 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005050 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005051 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005052 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005053}
5054
5055void AudioFlinger::DuplicatingThread::threadLoop_standby()
5056{
5057 // DuplicatingThread implements standby by stopping all tracks
5058 for (size_t i = 0; i < outputTracks.size(); i++) {
5059 outputTracks[i]->stop();
5060 }
5061}
5062
5063void AudioFlinger::DuplicatingThread::saveOutputTracks()
5064{
5065 outputTracks = mOutputTracks;
5066}
5067
5068void AudioFlinger::DuplicatingThread::clearOutputTracks()
5069{
5070 outputTracks.clear();
5071}
5072
5073void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5074{
5075 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005076 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5077 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5078 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5079 const size_t frameCount =
5080 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5081 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5082 // from different OutputTracks and their associated MixerThreads (e.g. one may
5083 // nearly empty and the other may be dropping data).
5084
5085 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005086 this,
5087 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005088 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005089 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005090 frameCount,
5091 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005092 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005093 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005094 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005095 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005096 updateWaitTime_l();
5097 }
5098}
5099
5100void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5101{
5102 Mutex::Autolock _l(mLock);
5103 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5104 if (mOutputTracks[i]->thread() == thread) {
5105 mOutputTracks[i]->destroy();
5106 mOutputTracks.removeAt(i);
5107 updateWaitTime_l();
5108 return;
5109 }
5110 }
5111 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
5112}
5113
5114// caller must hold mLock
5115void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5116{
5117 mWaitTimeMs = UINT_MAX;
5118 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5119 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5120 if (strong != 0) {
5121 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5122 if (waitTimeMs < mWaitTimeMs) {
5123 mWaitTimeMs = waitTimeMs;
5124 }
5125 }
5126 }
5127}
5128
5129
5130bool AudioFlinger::DuplicatingThread::outputsReady(
5131 const SortedVector< sp<OutputTrack> > &outputTracks)
5132{
5133 for (size_t i = 0; i < outputTracks.size(); i++) {
5134 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5135 if (thread == 0) {
5136 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5137 outputTracks[i].get());
5138 return false;
5139 }
5140 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5141 // see note at standby() declaration
5142 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5143 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5144 thread.get());
5145 return false;
5146 }
5147 }
5148 return true;
5149}
5150
5151uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5152{
5153 return (mWaitTimeMs * 1000) / 2;
5154}
5155
5156void AudioFlinger::DuplicatingThread::cacheParameters_l()
5157{
5158 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5159 updateWaitTime_l();
5160
5161 MixerThread::cacheParameters_l();
5162}
5163
5164// ----------------------------------------------------------------------------
5165// Record
5166// ----------------------------------------------------------------------------
5167
5168AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5169 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005170 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005171 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -08005172 audio_devices_t inDevice
5173#ifdef TEE_SINK
5174 , const sp<NBAIO_Sink>& teeSink
5175#endif
5176 ) :
Eric Laurentd3922f72013-02-01 17:57:04 -08005177 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005178 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005179 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005180 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005181#ifdef TEE_SINK
5182 , mTeeSink(teeSink)
5183#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005184 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5185 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005186 // mFastCapture below
5187 , mFastCaptureFutex(0)
5188 // mInputSource
5189 // mPipeSink
5190 // mPipeSource
5191 , mPipeFramesP2(0)
5192 // mPipeMemory
5193 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005194 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005195{
Glenn Kastend7dca052015-03-05 16:05:54 -08005196 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5197 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005198
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005199 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005200
5201 // create an NBAIO source for the HAL input stream, and negotiate
5202 mInputSource = new AudioStreamInSource(input->stream);
5203 size_t numCounterOffers = 0;
5204 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5205 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5206 ALOG_ASSERT(index == 0);
5207
5208 // initialize fast capture depending on configuration
5209 bool initFastCapture;
5210 switch (kUseFastCapture) {
5211 case FastCapture_Never:
5212 initFastCapture = false;
5213 break;
5214 case FastCapture_Always:
5215 initFastCapture = true;
5216 break;
5217 case FastCapture_Static:
5218 uint32_t primaryOutputSampleRate;
5219 {
5220 AutoMutex _l(audioFlinger->mHardwareLock);
5221 primaryOutputSampleRate = audioFlinger->mPrimaryOutputSampleRate;
5222 }
5223 initFastCapture =
5224 // either capture sample rate is same as (a reasonable) primary output sample rate
5225 (((primaryOutputSampleRate == 44100 || primaryOutputSampleRate == 48000) &&
5226 (mSampleRate == primaryOutputSampleRate)) ||
5227 // or primary output sample rate is unknown, and capture sample rate is reasonable
5228 ((primaryOutputSampleRate == 0) &&
5229 ((mSampleRate == 44100 || mSampleRate == 48000)))) &&
Glenn Kasten9f81de32014-07-27 15:02:23 -07005230 // and the buffer size is < 12 ms
5231 (mFrameCount * 1000) / mSampleRate < 12;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005232 break;
5233 // case FastCapture_Dynamic:
5234 }
5235
5236 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005237 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005238 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005239 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005240 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5241 void *pipeBuffer;
5242 const sp<MemoryDealer> roHeap(readOnlyHeap());
5243 sp<IMemory> pipeMemory;
5244 if ((roHeap == 0) ||
5245 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5246 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5247 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5248 goto failed;
5249 }
5250 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5251 memset(pipeBuffer, 0, pipeSize);
5252 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5253 const NBAIO_Format offers[1] = {format};
5254 size_t numCounterOffers = 0;
5255 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5256 ALOG_ASSERT(index == 0);
5257 mPipeSink = pipe;
5258 PipeReader *pipeReader = new PipeReader(*pipe);
5259 numCounterOffers = 0;
5260 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5261 ALOG_ASSERT(index == 0);
5262 mPipeSource = pipeReader;
5263 mPipeFramesP2 = pipeFramesP2;
5264 mPipeMemory = pipeMemory;
5265
5266 // create fast capture
5267 mFastCapture = new FastCapture();
5268 FastCaptureStateQueue *sq = mFastCapture->sq();
5269#ifdef STATE_QUEUE_DUMP
5270 // FIXME
5271#endif
5272 FastCaptureState *state = sq->begin();
5273 state->mCblk = NULL;
5274 state->mInputSource = mInputSource.get();
5275 state->mInputSourceGen++;
5276 state->mPipeSink = pipe;
5277 state->mPipeSinkGen++;
5278 state->mFrameCount = mFrameCount;
5279 state->mCommand = FastCaptureState::COLD_IDLE;
5280 // already done in constructor initialization list
5281 //mFastCaptureFutex = 0;
5282 state->mColdFutexAddr = &mFastCaptureFutex;
5283 state->mColdGen++;
5284 state->mDumpState = &mFastCaptureDumpState;
5285#ifdef TEE_SINK
5286 // FIXME
5287#endif
5288 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5289 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5290 sq->end();
5291 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5292
5293 // start the fast capture
5294 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5295 pid_t tid = mFastCapture->getTid();
5296 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
5297 if (err != 0) {
5298 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
5299 kPriorityFastCapture, getpid_cached, tid, err);
5300 }
5301
5302#ifdef AUDIO_WATCHDOG
5303 // FIXME
5304#endif
5305
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005306 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005307 }
5308failed: ;
5309
5310 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005311}
5312
Eric Laurent81784c32012-11-19 14:55:58 -08005313AudioFlinger::RecordThread::~RecordThread()
5314{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005315 if (mFastCapture != 0) {
5316 FastCaptureStateQueue *sq = mFastCapture->sq();
5317 FastCaptureState *state = sq->begin();
5318 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5319 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5320 if (old == -1) {
5321 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5322 }
5323 }
5324 state->mCommand = FastCaptureState::EXIT;
5325 sq->end();
5326 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5327 mFastCapture->join();
5328 mFastCapture.clear();
5329 }
5330 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005331 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005332 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005333}
5334
5335void AudioFlinger::RecordThread::onFirstRef()
5336{
Glenn Kastend7dca052015-03-05 16:05:54 -08005337 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005338}
5339
Eric Laurent81784c32012-11-19 14:55:58 -08005340bool AudioFlinger::RecordThread::threadLoop()
5341{
Eric Laurent81784c32012-11-19 14:55:58 -08005342 nsecs_t lastWarning = 0;
5343
5344 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005345
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005346reacquire_wakelock:
5347 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005348 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005349 {
5350 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005351 size_t size = mActiveTracks.size();
5352 activeTracksGen = mActiveTracksGen;
5353 if (size > 0) {
5354 // FIXME an arbitrary choice
5355 activeTrack = mActiveTracks[0];
5356 acquireWakeLock_l(activeTrack->uid());
5357 if (size > 1) {
5358 SortedVector<int> tmp;
5359 for (size_t i = 0; i < size; i++) {
5360 tmp.add(mActiveTracks[i]->uid());
5361 }
5362 updateWakeLockUids_l(tmp);
5363 }
5364 } else {
5365 acquireWakeLock_l(-1);
5366 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005367 }
5368
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005369 // used to request a deferred sleep, to be executed later while mutex is unlocked
5370 uint32_t sleepUs = 0;
5371
5372 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005373 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005374 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005375
Glenn Kasten5edadd42013-08-14 16:30:49 -07005376 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005377 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005378 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005379 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005380 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005381 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005382 }
5383
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005384 // activeTracks accumulates a copy of a subset of mActiveTracks
5385 Vector< sp<RecordTrack> > activeTracks;
5386
Glenn Kasten735f45f2014-08-18 15:51:59 -07005387 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005388 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005389
Glenn Kasten735f45f2014-08-18 15:51:59 -07005390 // reference to a fast track which is about to be removed
5391 sp<RecordTrack> fastTrackToRemove;
5392
Eric Laurent81784c32012-11-19 14:55:58 -08005393 { // scope for mLock
5394 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005395
Eric Laurent021cf962014-05-13 10:18:14 -07005396 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005397
Eric Laurent000a4192014-01-29 15:17:32 -08005398 // check exitPending here because checkForNewParameters_l() and
5399 // checkForNewParameters_l() can temporarily release mLock
5400 if (exitPending()) {
5401 break;
5402 }
5403
Glenn Kasten2b806402013-11-20 16:37:38 -08005404 // if no active track(s), then standby and release wakelock
5405 size_t size = mActiveTracks.size();
5406 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005407 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005408 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005409 releaseWakeLock_l();
5410 ALOGV("RecordThread: loop stopping");
5411 // go to sleep
5412 mWaitWorkCV.wait(mLock);
5413 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005414 goto reacquire_wakelock;
5415 }
5416
Glenn Kasten2b806402013-11-20 16:37:38 -08005417 if (mActiveTracksGen != activeTracksGen) {
5418 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005419 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005420 for (size_t i = 0; i < size; i++) {
5421 tmp.add(mActiveTracks[i]->uid());
5422 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005423 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005424 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005425
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005426 bool doBroadcast = false;
5427 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005428
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005429 activeTrack = mActiveTracks[i];
5430 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005431 if (activeTrack->isFastTrack()) {
5432 ALOG_ASSERT(fastTrackToRemove == 0);
5433 fastTrackToRemove = activeTrack;
5434 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005435 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005436 mActiveTracks.remove(activeTrack);
5437 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005438 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005439 continue;
5440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005441
5442 TrackBase::track_state activeTrackState = activeTrack->mState;
5443 switch (activeTrackState) {
5444
5445 case TrackBase::PAUSING:
5446 mActiveTracks.remove(activeTrack);
5447 mActiveTracksGen++;
5448 doBroadcast = true;
5449 size--;
5450 continue;
5451
5452 case TrackBase::STARTING_1:
5453 sleepUs = 10000;
5454 i++;
5455 continue;
5456
5457 case TrackBase::STARTING_2:
5458 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005459 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005460 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005461 break;
5462
5463 case TrackBase::ACTIVE:
5464 break;
5465
5466 case TrackBase::IDLE:
5467 i++;
5468 continue;
5469
5470 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005471 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005472 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005473
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005474 activeTracks.add(activeTrack);
5475 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005476
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005477 if (activeTrack->isFastTrack()) {
5478 ALOG_ASSERT(!mFastTrackAvail);
5479 ALOG_ASSERT(fastTrack == 0);
5480 fastTrack = activeTrack;
5481 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005482 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005483 if (doBroadcast) {
5484 mStartStopCond.broadcast();
5485 }
5486
5487 // sleep if there are no active tracks to process
5488 if (activeTracks.size() == 0) {
5489 if (sleepUs == 0) {
5490 sleepUs = kRecordThreadSleepUs;
5491 }
5492 continue;
5493 }
5494 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005495
Eric Laurent81784c32012-11-19 14:55:58 -08005496 lockEffectChains_l(effectChains);
5497 }
5498
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005499 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07005500
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005501 size_t size = effectChains.size();
5502 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005503 // thread mutex is not locked, but effect chain is locked
5504 effectChains[i]->process_l();
5505 }
5506
Glenn Kasten735f45f2014-08-18 15:51:59 -07005507 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005508 if (mFastCapture != 0) {
5509 FastCaptureStateQueue *sq = mFastCapture->sq();
5510 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07005511 bool didModify = false;
5512 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005513 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
5514 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
5515 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5516 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5517 if (old == -1) {
5518 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5519 }
5520 }
5521 state->mCommand = FastCaptureState::READ_WRITE;
5522#if 0 // FIXME
5523 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005524 FastThreadDumpState::kSamplingNforLowRamDevice :
5525 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005526#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07005527 didModify = true;
5528 }
5529 audio_track_cblk_t *cblkOld = state->mCblk;
5530 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
5531 if (cblkNew != cblkOld) {
5532 state->mCblk = cblkNew;
5533 // block until acked if removing a fast track
5534 if (cblkOld != NULL) {
5535 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
5536 }
5537 didModify = true;
5538 }
5539 sq->end(didModify);
5540 if (didModify) {
5541 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005542#if 0
5543 if (kUseFastCapture == FastCapture_Dynamic) {
5544 mNormalSource = mPipeSource;
5545 }
5546#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005547 }
5548 }
5549
Glenn Kasten735f45f2014-08-18 15:51:59 -07005550 // now run the fast track destructor with thread mutex unlocked
5551 fastTrackToRemove.clear();
5552
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005553 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
5554 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
5555 // slow, then this RecordThread will overrun by not calling HAL read often enough.
5556 // If destination is non-contiguous, first read past the nominal end of buffer, then
5557 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005558
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005559 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005560 ssize_t framesRead;
5561
5562 // If an NBAIO source is present, use it to read the normal capture's data
5563 if (mPipeSource != 0) {
5564 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07005565 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005566 framesToRead, AudioBufferProvider::kInvalidPTS);
5567 if (framesRead == 0) {
5568 // since pipe is non-blocking, simulate blocking input
5569 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
5570 }
5571 // otherwise use the HAL / AudioStreamIn directly
5572 } else {
5573 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07005574 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005575 if (bytesRead < 0) {
5576 framesRead = bytesRead;
5577 } else {
5578 framesRead = bytesRead / mFrameSize;
5579 }
5580 }
5581
5582 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
5583 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005584 // Force input into standby so that it tries to recover at next read attempt
5585 inputStandBy();
5586 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005587 }
5588 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005589 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005590 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005591 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005592
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005593 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07005594 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005595 }
5596 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005597 {
5598 size_t part1 = mRsmpInFramesP2 - rear;
5599 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07005600 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005601 (framesRead - part1) * mFrameSize);
5602 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005603 }
5604 rear = mRsmpInRear += framesRead;
5605
5606 size = activeTracks.size();
5607 // loop over each active track
5608 for (size_t i = 0; i < size; i++) {
5609 activeTrack = activeTracks[i];
5610
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005611 // skip fast tracks, as those are handled directly by FastCapture
5612 if (activeTrack->isFastTrack()) {
5613 continue;
5614 }
5615
Andy Hung73c02e42015-03-29 01:13:58 -07005616 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07005617 // TODO: Update the activeTrack buffer converter in case of reconfigure.
5618
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005619 enum {
5620 OVERRUN_UNKNOWN,
5621 OVERRUN_TRUE,
5622 OVERRUN_FALSE
5623 } overrun = OVERRUN_UNKNOWN;
5624
5625 // loop over getNextBuffer to handle circular sink
5626 for (;;) {
5627
5628 activeTrack->mSink.frameCount = ~0;
5629 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
5630 size_t framesOut = activeTrack->mSink.frameCount;
5631 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
5632
Andy Hung73c02e42015-03-29 01:13:58 -07005633 // check available frames and handle overrun conditions
5634 // if the record track isn't draining fast enough.
5635 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005636 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07005637 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
5638 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005639 overrun = OVERRUN_TRUE;
5640 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005641 if (framesOut == 0 || framesIn == 0) {
5642 break;
5643 }
5644
Andy Hung6770c6f2015-04-07 13:43:36 -07005645 // Don't allow framesOut to be larger than what is possible with resampling
5646 // from framesIn.
5647 // This isn't strictly necessary but helps limit buffer resizing in
5648 // RecordBufferConverter. TODO: remove when no longer needed.
5649 framesOut = min(framesOut,
5650 destinationFramesPossible(
5651 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07005652 // process frames from the RecordThread buffer provider to the RecordTrack buffer
5653 framesOut = activeTrack->mRecordBufferConverter->convert(
5654 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005655
5656 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
5657 overrun = OVERRUN_FALSE;
5658 }
5659
5660 if (activeTrack->mFramesToDrop == 0) {
5661 if (framesOut > 0) {
5662 activeTrack->mSink.frameCount = framesOut;
5663 activeTrack->releaseBuffer(&activeTrack->mSink);
5664 }
5665 } else {
5666 // FIXME could do a partial drop of framesOut
5667 if (activeTrack->mFramesToDrop > 0) {
5668 activeTrack->mFramesToDrop -= framesOut;
5669 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005670 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005671 }
5672 } else {
5673 activeTrack->mFramesToDrop += framesOut;
5674 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
5675 activeTrack->mSyncStartEvent->isCancelled()) {
5676 ALOGW("Synced record %s, session %d, trigger session %d",
5677 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
5678 activeTrack->sessionId(),
5679 (activeTrack->mSyncStartEvent != 0) ?
5680 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005681 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005682 }
5683 }
5684 }
5685
5686 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005687 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005688 }
5689 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005690
5691 switch (overrun) {
5692 case OVERRUN_TRUE:
5693 // client isn't retrieving buffers fast enough
5694 if (!activeTrack->setOverflow()) {
5695 nsecs_t now = systemTime();
5696 // FIXME should lastWarning per track?
5697 if ((now - lastWarning) > kWarningThrottleNs) {
5698 ALOGW("RecordThread: buffer overflow");
5699 lastWarning = now;
5700 }
5701 }
5702 break;
5703 case OVERRUN_FALSE:
5704 activeTrack->clearOverflow();
5705 break;
5706 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005707 break;
5708 }
5709
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07005710 }
5711
Glenn Kasten3d61bc12014-06-16 10:25:20 -07005712unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08005713 // enable changes in effect chain
5714 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005715 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08005716 }
5717
Glenn Kasten93e471f2013-08-19 08:40:07 -07005718 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08005719
5720 {
5721 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07005722 for (size_t i = 0; i < mTracks.size(); i++) {
5723 sp<RecordTrack> track = mTracks[i];
5724 track->invalidate();
5725 }
Glenn Kasten2b806402013-11-20 16:37:38 -08005726 mActiveTracks.clear();
5727 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08005728 mStartStopCond.broadcast();
5729 }
5730
5731 releaseWakeLock();
5732
5733 ALOGV("RecordThread %p exiting", this);
5734 return false;
5735}
5736
Glenn Kasten93e471f2013-08-19 08:40:07 -07005737void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08005738{
5739 if (!mStandby) {
5740 inputStandBy();
5741 mStandby = true;
5742 }
5743}
5744
5745void AudioFlinger::RecordThread::inputStandBy()
5746{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005747 // Idle the fast capture if it's currently running
5748 if (mFastCapture != 0) {
5749 FastCaptureStateQueue *sq = mFastCapture->sq();
5750 FastCaptureState *state = sq->begin();
5751 if (!(state->mCommand & FastCaptureState::IDLE)) {
5752 state->mCommand = FastCaptureState::COLD_IDLE;
5753 state->mColdFutexAddr = &mFastCaptureFutex;
5754 state->mColdGen++;
5755 mFastCaptureFutex = 0;
5756 sq->end();
5757 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5758 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
5759#if 0
5760 if (kUseFastCapture == FastCapture_Dynamic) {
5761 // FIXME
5762 }
5763#endif
5764#ifdef AUDIO_WATCHDOG
5765 // FIXME
5766#endif
5767 } else {
5768 sq->end(false /*didModify*/);
5769 }
5770 }
Eric Laurent81784c32012-11-19 14:55:58 -08005771 mInput->stream->common.standby(&mInput->stream->common);
5772}
5773
Glenn Kasten05997e22014-03-13 15:08:33 -07005774// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07005775sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08005776 const sp<AudioFlinger::Client>& client,
5777 uint32_t sampleRate,
5778 audio_format_t format,
5779 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08005780 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08005781 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07005782 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005783 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07005784 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08005785 pid_t tid,
5786 status_t *status)
5787{
Glenn Kasten74935e42013-12-19 08:56:45 -08005788 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005789 sp<RecordTrack> track;
5790 status_t lStatus;
5791
Glenn Kasten90e58b12013-07-31 16:16:02 -07005792 // client expresses a preference for FAST, but we get the final say
5793 if (*flags & IAudioFlinger::TRACK_FAST) {
5794 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07005795 // we formerly checked for a callback handler (non-0 tid),
5796 // but that is no longer required for TRANSFER_OBTAIN mode
5797 //
Glenn Kasten74105912014-07-03 12:28:53 -07005798 // frame count is not specified, or is exactly the pipe depth
5799 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005800 // PCM data
5801 audio_is_linear_pcm(format) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005802 // native format
5803 (format == mFormat) &&
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005804 // native channel mask
5805 (channelMask == mChannelMask) &&
5806 // native hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07005807 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07005808 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005809 hasFastCapture() &&
5810 // there are sufficient fast track slots available
5811 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07005812 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07005813 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07005814 frameCount, mFrameCount);
5815 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07005816 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
5817 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005818 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07005819 frameCount, mFrameCount, mPipeFramesP2,
5820 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
5821 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005822 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07005823 }
5824 }
5825
5826 // compute track buffer size in frames, and suggest the notification frame count
5827 if (*flags & IAudioFlinger::TRACK_FAST) {
5828 // fast track: frame count is exactly the pipe depth
5829 frameCount = mPipeFramesP2;
5830 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
5831 *notificationFrames = mFrameCount;
5832 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005833 // not fast track: max notification period is resampled equivalent of one HAL buffer time
5834 // or 20 ms if there is a fast capture
5835 // TODO This could be a roundupRatio inline, and const
5836 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
5837 * sampleRate + mSampleRate - 1) / mSampleRate;
5838 // minimum number of notification periods is at least kMinNotifications,
5839 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
5840 static const size_t kMinNotifications = 3;
5841 static const uint32_t kMinMs = 30;
5842 // TODO This could be a roundupRatio inline
5843 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
5844 // TODO This could be a roundupRatio inline
5845 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
5846 maxNotificationFrames;
5847 const size_t minFrameCount = maxNotificationFrames *
5848 max(kMinNotifications, minNotificationsByMs);
5849 frameCount = max(frameCount, minFrameCount);
5850 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
5851 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07005852 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07005853 }
Glenn Kasten74935e42013-12-19 08:56:45 -08005854 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07005855
Glenn Kasten15e57982013-09-24 11:52:37 -07005856 lStatus = initCheck();
5857 if (lStatus != NO_ERROR) {
5858 ALOGE("createRecordTrack_l() audio driver not initialized");
5859 goto Exit;
5860 }
Eric Laurent81784c32012-11-19 14:55:58 -08005861
5862 { // scope for mLock
5863 Mutex::Autolock _l(mLock);
5864
5865 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07005866 format, channelMask, frameCount, NULL, sessionId, uid,
5867 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08005868
Glenn Kasten03003332013-08-06 15:40:54 -07005869 lStatus = track->initCheck();
5870 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07005871 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08005872 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08005873 goto Exit;
5874 }
5875 mTracks.add(track);
5876
5877 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5878 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
5879 mAudioFlinger->btNrecIsOff();
5880 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5881 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07005882
5883 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
5884 pid_t callingPid = IPCThreadState::self()->getCallingPid();
5885 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
5886 // so ask activity manager to do this on our behalf
5887 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
5888 }
Eric Laurent81784c32012-11-19 14:55:58 -08005889 }
Glenn Kasten05997e22014-03-13 15:08:33 -07005890
Eric Laurent81784c32012-11-19 14:55:58 -08005891 lStatus = NO_ERROR;
5892
5893Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07005894 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08005895 return track;
5896}
5897
5898status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
5899 AudioSystem::sync_event_t event,
5900 int triggerSession)
5901{
5902 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
5903 sp<ThreadBase> strongMe = this;
5904 status_t status = NO_ERROR;
5905
5906 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005907 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005908 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005909 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08005910 triggerSession,
5911 recordTrack->sessionId(),
5912 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005913 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08005914 // Sync event can be cancelled by the trigger session if the track is not in a
5915 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005916 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005917 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08005918 } else {
5919 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005920 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005921 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08005922 }
5923 }
5924
5925 {
Glenn Kasten47c20702013-08-13 15:37:35 -07005926 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08005927 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005928 if (mActiveTracks.indexOf(recordTrack) >= 0) {
5929 if (recordTrack->mState == TrackBase::PAUSING) {
5930 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005931 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005932 } else {
5933 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005934 }
5935 return status;
5936 }
5937
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005938 // TODO consider other ways of handling this, such as changing the state to :STARTING and
5939 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
5940 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005941 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08005942 mActiveTracks.add(recordTrack);
5943 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07005944 status_t status = NO_ERROR;
5945 if (recordTrack->isExternalTrack()) {
5946 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07005947 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005948 mLock.lock();
5949 // FIXME should verify that recordTrack is still in mActiveTracks
5950 if (status != NO_ERROR) {
5951 mActiveTracks.remove(recordTrack);
5952 mActiveTracksGen++;
5953 recordTrack->clearSyncStartEvent();
5954 ALOGV("RecordThread::start error %d", status);
5955 return status;
5956 }
Eric Laurent81784c32012-11-19 14:55:58 -08005957 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005958 // Catch up with current buffer indices if thread is already running.
5959 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
5960 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
5961 // see previously buffered data before it called start(), but with greater risk of overrun.
5962
Andy Hung73c02e42015-03-29 01:13:58 -07005963 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07005964 // clear any converter state as new data will be discontinuous
5965 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005966 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08005967 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08005968 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08005969 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005970 ALOGV("Record failed to start");
5971 status = BAD_VALUE;
5972 goto startError;
5973 }
Eric Laurent81784c32012-11-19 14:55:58 -08005974 return status;
5975 }
Glenn Kasten7c027242012-12-26 14:43:16 -08005976
Eric Laurent81784c32012-11-19 14:55:58 -08005977startError:
Eric Laurent83b88082014-06-20 18:31:16 -07005978 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07005979 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07005980 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08005981 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005982 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08005983 return status;
5984}
5985
Eric Laurent81784c32012-11-19 14:55:58 -08005986void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5987{
5988 sp<SyncEvent> strongEvent = event.promote();
5989
5990 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08005991 sp<RefBase> ptr = strongEvent->cookie().promote();
5992 if (ptr != 0) {
5993 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
5994 recordTrack->handleSyncStartEvent(strongEvent);
5995 }
Eric Laurent81784c32012-11-19 14:55:58 -08005996 }
5997}
5998
Glenn Kastena8356f62013-07-25 14:37:52 -07005999bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006000 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006001 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006002 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006003 return false;
6004 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006005 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006006 recordTrack->mState = TrackBase::PAUSING;
6007 // do not wait for mStartStopCond if exiting
6008 if (exitPending()) {
6009 return true;
6010 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006011 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006012 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006013 // if we have been restarted, recordTrack is in mActiveTracks here
6014 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006015 ALOGV("Record stopped OK");
6016 return true;
6017 }
6018 return false;
6019}
6020
Glenn Kasten0f11b512014-01-31 16:18:54 -08006021bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006022{
6023 return false;
6024}
6025
Glenn Kasten0f11b512014-01-31 16:18:54 -08006026status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006027{
6028#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6029 if (!isValidSyncEvent(event)) {
6030 return BAD_VALUE;
6031 }
6032
6033 int eventSession = event->triggerSession();
6034 status_t ret = NAME_NOT_FOUND;
6035
6036 Mutex::Autolock _l(mLock);
6037
6038 for (size_t i = 0; i < mTracks.size(); i++) {
6039 sp<RecordTrack> track = mTracks[i];
6040 if (eventSession == track->sessionId()) {
6041 (void) track->setSyncEvent(event);
6042 ret = NO_ERROR;
6043 }
6044 }
6045 return ret;
6046#else
6047 return BAD_VALUE;
6048#endif
6049}
6050
6051// destroyTrack_l() must be called with ThreadBase::mLock held
6052void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6053{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006054 track->terminate();
6055 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006056 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006057 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006058 removeTrack_l(track);
6059 }
6060}
6061
6062void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6063{
6064 mTracks.remove(track);
6065 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006066 if (track->isFastTrack()) {
6067 ALOG_ASSERT(!mFastTrackAvail);
6068 mFastTrackAvail = true;
6069 }
Eric Laurent81784c32012-11-19 14:55:58 -08006070}
6071
6072void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6073{
6074 dumpInternals(fd, args);
6075 dumpTracks(fd, args);
6076 dumpEffectChains(fd, args);
6077}
6078
6079void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6080{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006081 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006082
Glenn Kasten44182c22015-03-05 17:12:23 -08006083 dumpBase(fd, args);
6084
6085 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006086 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006087 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006088 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006089 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006090
6091 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6092 const FastCaptureDumpState copy(mFastCaptureDumpState);
6093 copy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006094}
6095
Glenn Kasten0f11b512014-01-31 16:18:54 -08006096void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006097{
6098 const size_t SIZE = 256;
6099 char buffer[SIZE];
6100 String8 result;
6101
Marco Nelissenb2208842014-02-07 14:00:50 -08006102 size_t numtracks = mTracks.size();
6103 size_t numactive = mActiveTracks.size();
6104 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006105 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006106 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006107 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006108 RecordTrack::appendDumpHeader(result);
6109 for (size_t i = 0; i < numtracks ; ++i) {
6110 sp<RecordTrack> track = mTracks[i];
6111 if (track != 0) {
6112 bool active = mActiveTracks.indexOf(track) >= 0;
6113 if (active) {
6114 numactiveseen++;
6115 }
6116 track->dump(buffer, SIZE, active);
6117 result.append(buffer);
6118 }
Eric Laurent81784c32012-11-19 14:55:58 -08006119 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006120 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006121 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006122 }
6123
Marco Nelissenb2208842014-02-07 14:00:50 -08006124 if (numactiveseen != numactive) {
6125 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6126 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006127 result.append(buffer);
6128 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006129 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006130 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006131 if (mTracks.indexOf(track) < 0) {
6132 track->dump(buffer, SIZE, true);
6133 result.append(buffer);
6134 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006135 }
Eric Laurent81784c32012-11-19 14:55:58 -08006136
6137 }
6138 write(fd, result.string(), result.size());
6139}
6140
Andy Hung73c02e42015-03-29 01:13:58 -07006141
6142void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6143{
6144 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6145 RecordThread *recordThread = (RecordThread *) threadBase.get();
6146 mRsmpInFront = recordThread->mRsmpInRear;
6147 mRsmpInUnrel = 0;
6148}
6149
6150void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6151 size_t *framesAvailable, bool *hasOverrun)
6152{
6153 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6154 RecordThread *recordThread = (RecordThread *) threadBase.get();
6155 const int32_t rear = recordThread->mRsmpInRear;
6156 const int32_t front = mRsmpInFront;
6157 const ssize_t filled = rear - front;
6158
6159 size_t framesIn;
6160 bool overrun = false;
6161 if (filled < 0) {
6162 // should not happen, but treat like a massive overrun and re-sync
6163 framesIn = 0;
6164 mRsmpInFront = rear;
6165 overrun = true;
6166 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6167 framesIn = (size_t) filled;
6168 } else {
6169 // client is not keeping up with server, but give it latest data
6170 framesIn = recordThread->mRsmpInFrames;
6171 mRsmpInFront = /* front = */ rear - framesIn;
6172 overrun = true;
6173 }
6174 if (framesAvailable != NULL) {
6175 *framesAvailable = framesIn;
6176 }
6177 if (hasOverrun != NULL) {
6178 *hasOverrun = overrun;
6179 }
6180}
6181
Eric Laurent81784c32012-11-19 14:55:58 -08006182// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006183status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
6184 AudioBufferProvider::Buffer* buffer, int64_t pts __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006185{
Andy Hung73c02e42015-03-29 01:13:58 -07006186 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006187 if (threadBase == 0) {
6188 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006189 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006190 return NOT_ENOUGH_DATA;
6191 }
6192 RecordThread *recordThread = (RecordThread *) threadBase.get();
6193 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006194 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006195 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006196 // FIXME should not be P2 (don't want to increase latency)
6197 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006198 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006199 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006200 front &= recordThread->mRsmpInFramesP2 - 1;
6201 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006202 if (part1 > (size_t) filled) {
6203 part1 = filled;
6204 }
6205 size_t ask = buffer->frameCount;
6206 ALOG_ASSERT(ask > 0);
6207 if (part1 > ask) {
6208 part1 = ask;
6209 }
6210 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006211 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006212 buffer->raw = NULL;
6213 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006214 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006215 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006216 }
6217
Andy Hung57446612015-04-19 23:56:46 -07006218 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006219 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006220 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006221 return NO_ERROR;
6222}
6223
6224// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006225void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6226 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006227{
Glenn Kasten85948432013-08-19 12:09:05 -07006228 size_t stepCount = buffer->frameCount;
6229 if (stepCount == 0) {
6230 return;
6231 }
Andy Hung73c02e42015-03-29 01:13:58 -07006232 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6233 mRsmpInUnrel -= stepCount;
6234 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006235 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006236 buffer->frameCount = 0;
6237}
6238
Andy Hung97a893e2015-03-29 01:03:07 -07006239AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6240 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6241 uint32_t srcSampleRate,
6242 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6243 uint32_t dstSampleRate) :
6244 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6245 // mSrcFormat
6246 // mSrcSampleRate
6247 // mDstChannelMask
6248 // mDstFormat
6249 // mDstSampleRate
6250 // mSrcChannelCount
6251 // mDstChannelCount
6252 // mDstFrameSize
6253 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006254 mResampler(NULL),
6255 mIsLegacyDownmix(false),
6256 mIsLegacyUpmix(false),
6257 mRequiresFloat(false),
6258 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006259{
6260 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6261 dstChannelMask, dstFormat, dstSampleRate);
6262}
6263
6264AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6265 free(mBuf);
6266 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006267 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006268}
6269
6270size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6271 AudioBufferProvider *provider, size_t frames)
6272{
Andy Hungd330ee42015-04-20 13:23:41 -07006273 if (mInputConverterProvider != NULL) {
6274 mInputConverterProvider->setBufferProvider(provider);
6275 provider = mInputConverterProvider;
6276 }
6277
6278 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006279 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6280 mSrcSampleRate, mSrcFormat, mDstFormat);
6281
6282 AudioBufferProvider::Buffer buffer;
6283 for (size_t i = frames; i > 0; ) {
6284 buffer.frameCount = i;
6285 status_t status = provider->getNextBuffer(&buffer, 0);
6286 if (status != OK || buffer.frameCount == 0) {
6287 frames -= i; // cannot fill request.
6288 break;
6289 }
Andy Hungd330ee42015-04-20 13:23:41 -07006290 // format convert to destination buffer
6291 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006292
6293 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6294 i -= buffer.frameCount;
6295 provider->releaseBuffer(&buffer);
6296 }
6297 } else {
6298 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6299 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6300
Andy Hungd330ee42015-04-20 13:23:41 -07006301 // reallocate buffer if needed
6302 if (mBufFrameSize != 0 && mBufFrames < frames) {
6303 free(mBuf);
6304 mBufFrames = frames;
6305 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6306 }
Andy Hung97a893e2015-03-29 01:03:07 -07006307 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006308 memset(mBuf, 0, frames * mBufFrameSize);
6309 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6310 // format convert to destination buffer
6311 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006312 }
6313 return frames;
6314}
6315
6316status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6317 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6318 uint32_t srcSampleRate,
6319 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6320 uint32_t dstSampleRate)
6321{
6322 // quick evaluation if there is any change.
6323 if (mSrcFormat == srcFormat
6324 && mSrcChannelMask == srcChannelMask
6325 && mSrcSampleRate == srcSampleRate
6326 && mDstFormat == dstFormat
6327 && mDstChannelMask == dstChannelMask
6328 && mDstSampleRate == dstSampleRate) {
6329 return NO_ERROR;
6330 }
6331
6332 const bool valid =
6333 audio_is_input_channel(srcChannelMask)
6334 && audio_is_input_channel(dstChannelMask)
6335 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6336 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6337 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6338 ; // no upsampling checks for now
6339 if (!valid) {
6340 return BAD_VALUE;
6341 }
6342
6343 mSrcFormat = srcFormat;
6344 mSrcChannelMask = srcChannelMask;
6345 mSrcSampleRate = srcSampleRate;
6346 mDstFormat = dstFormat;
6347 mDstChannelMask = dstChannelMask;
6348 mDstSampleRate = dstSampleRate;
6349
6350 // compute derived parameters
6351 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6352 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6353 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6354
Andy Hungd330ee42015-04-20 13:23:41 -07006355 // do we need to resample?
6356 delete mResampler;
6357 mResampler = NULL;
6358 if (mSrcSampleRate != mDstSampleRate) {
6359 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6360 mSrcChannelCount, mDstSampleRate);
6361 mResampler->setSampleRate(mSrcSampleRate);
6362 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6363 }
6364
6365 // are we running legacy channel conversion modes?
6366 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6367 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6368 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6369 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6370 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6371 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6372
6373 // do we need to process in float?
6374 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6375
6376 // do we need a staging buffer to convert for destination (we can still optimize this)?
6377 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6378 if (mResampler != NULL) {
6379 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6380 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6381 } else if ((mIsLegacyUpmix || mIsLegacyDownmix) && mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6382 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6383 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006384 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6385 } else {
6386 mBufFrameSize = 0;
6387 }
6388 mBufFrames = 0; // force the buffer to be resized.
6389
Andy Hungd330ee42015-04-20 13:23:41 -07006390 // do we need an input converter buffer provider to give us float?
6391 delete mInputConverterProvider;
6392 mInputConverterProvider = NULL;
6393 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6394 mInputConverterProvider = new ReformatBufferProvider(
6395 audio_channel_count_from_in_mask(mSrcChannelMask),
6396 mSrcFormat,
6397 AUDIO_FORMAT_PCM_FLOAT,
6398 256 /* provider buffer frame count */);
6399 }
6400
6401 // do we need a remixer to do channel mask conversion
6402 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6403 (void) memcpy_by_index_array_initialization_from_channel_mask(
6404 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006405 }
6406 return NO_ERROR;
6407}
6408
Andy Hungd330ee42015-04-20 13:23:41 -07006409void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6410 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006411{
Andy Hungd330ee42015-04-20 13:23:41 -07006412 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006413 if (mBufFrameSize != 0 && mBufFrames < frames) {
6414 free(mBuf);
6415 mBufFrames = frames;
6416 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6417 }
Andy Hungd330ee42015-04-20 13:23:41 -07006418 // do we need to do legacy upmix and downmix?
6419 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006420 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006421 if (mIsLegacyUpmix) {
6422 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6423 (const float *)src, frames);
6424 } else /*mIsLegacyDownmix */ {
6425 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6426 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006427 }
Andy Hungd330ee42015-04-20 13:23:41 -07006428 if (mBuf != NULL) {
6429 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6430 frames * mDstChannelCount);
6431 }
6432 return;
6433 }
6434 // do we need to do channel mask conversion?
6435 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006436 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006437 memcpy_by_index_array(dstBuf, mDstChannelCount,
6438 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6439 if (dstBuf == dst) {
6440 return; // format is the same
6441 }
6442 }
6443 // convert to destination buffer
6444 const void *convertBuf = mBuf != NULL ? mBuf : src;
6445 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6446 frames * mDstChannelCount);
6447}
6448
6449void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6450 void *dst, /*not-a-const*/ void *src, size_t frames)
6451{
6452 // src buffer format is ALWAYS float when entering this routine
6453 if (mIsLegacyUpmix) {
6454 ; // mono to stereo already handled by resampler
6455 } else if (mIsLegacyDownmix
6456 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6457 // the resampler outputs stereo for mono input channel (a feature?)
6458 // must convert to mono
6459 downmix_to_mono_float_from_stereo_float((float *)src,
6460 (const float *)src, frames);
6461 } else if (mSrcChannelMask != mDstChannelMask) {
6462 // convert to mono channel again for channel mask conversion (could be skipped
6463 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07006464 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07006465 downmix_to_mono_float_from_stereo_float((float *)src,
6466 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006467 }
Andy Hungd330ee42015-04-20 13:23:41 -07006468 // convert to destination format (in place, OK as float is larger than other types)
6469 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
6470 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6471 frames * mSrcChannelCount);
6472 }
6473 // channel convert and save to dst
6474 memcpy_by_index_array(dst, mDstChannelCount,
6475 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
6476 return;
Andy Hung97a893e2015-03-29 01:03:07 -07006477 }
Andy Hungd330ee42015-04-20 13:23:41 -07006478 // convert to destination format and save to dst
6479 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
6480 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006481}
6482
Eric Laurent10351942014-05-08 18:49:52 -07006483bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6484 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006485{
6486 bool reconfig = false;
6487
Eric Laurent10351942014-05-08 18:49:52 -07006488 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006489
Eric Laurent10351942014-05-08 18:49:52 -07006490 audio_format_t reqFormat = mFormat;
6491 uint32_t samplingRate = mSampleRate;
6492 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
Andy Hungd330ee42015-04-20 13:23:41 -07006493 // possible that we are > 2 channels, use channel index mask
6494 if (channelMask == AUDIO_CHANNEL_INVALID && mChannelCount <= FCC_8) {
6495 audio_channel_mask_for_index_assignment_from_count(mChannelCount);
6496 }
Eric Laurent10351942014-05-08 18:49:52 -07006497
6498 AudioParameter param = AudioParameter(keyValuePair);
6499 int value;
6500 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6501 // channel count change can be requested. Do we mandate the first client defines the
6502 // HAL sampling rate and channel count or do we allow changes on the fly?
6503 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6504 samplingRate = value;
6505 reconfig = true;
6506 }
6507 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006508 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006509 status = BAD_VALUE;
6510 } else {
6511 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006512 reconfig = true;
6513 }
Eric Laurent10351942014-05-08 18:49:52 -07006514 }
6515 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6516 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006517 if (!audio_is_input_channel(mask) ||
6518 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006519 status = BAD_VALUE;
6520 } else {
6521 channelMask = mask;
6522 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006523 }
Eric Laurent10351942014-05-08 18:49:52 -07006524 }
6525 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6526 // do not accept frame count changes if tracks are open as the track buffer
6527 // size depends on frame count and correct behavior would not be guaranteed
6528 // if frame count is changed after track creation
6529 if (mActiveTracks.size() > 0) {
6530 status = INVALID_OPERATION;
6531 } else {
6532 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006533 }
Eric Laurent10351942014-05-08 18:49:52 -07006534 }
6535 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6536 // forward device change to effects that have requested to be
6537 // aware of attached audio device.
6538 for (size_t i = 0; i < mEffectChains.size(); i++) {
6539 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006540 }
Eric Laurent81784c32012-11-19 14:55:58 -08006541
Eric Laurent10351942014-05-08 18:49:52 -07006542 // store input device and output device but do not forward output device to audio HAL.
6543 // Note that status is ignored by the caller for output device
6544 // (see AudioFlinger::setParameters()
6545 if (audio_is_output_devices(value)) {
6546 mOutDevice = value;
6547 status = BAD_VALUE;
6548 } else {
6549 mInDevice = value;
6550 // disable AEC and NS if the device is a BT SCO headset supporting those
6551 // pre processings
6552 if (mTracks.size() > 0) {
6553 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6554 mAudioFlinger->btNrecIsOff();
6555 for (size_t i = 0; i < mTracks.size(); i++) {
6556 sp<RecordTrack> track = mTracks[i];
6557 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6558 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006559 }
6560 }
6561 }
Eric Laurent10351942014-05-08 18:49:52 -07006562 }
6563 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6564 mAudioSource != (audio_source_t)value) {
6565 // forward device change to effects that have requested to be
6566 // aware of attached audio device.
6567 for (size_t i = 0; i < mEffectChains.size(); i++) {
6568 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08006569 }
Eric Laurent10351942014-05-08 18:49:52 -07006570 mAudioSource = (audio_source_t)value;
6571 }
Glenn Kastene198c362013-08-13 09:13:36 -07006572
Eric Laurent10351942014-05-08 18:49:52 -07006573 if (status == NO_ERROR) {
6574 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6575 keyValuePair.string());
6576 if (status == INVALID_OPERATION) {
6577 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006578 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6579 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07006580 }
6581 if (reconfig) {
6582 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07006583 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
6584 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07006585 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07006586 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07006587 audio_channel_count_from_in_mask(
6588 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
Eric Laurent10351942014-05-08 18:49:52 -07006589 (channelMask == AUDIO_CHANNEL_IN_MONO ||
6590 channelMask == AUDIO_CHANNEL_IN_STEREO)) {
6591 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006592 }
Eric Laurent10351942014-05-08 18:49:52 -07006593 if (status == NO_ERROR) {
6594 readInputParameters_l();
6595 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08006596 }
6597 }
Eric Laurent81784c32012-11-19 14:55:58 -08006598 }
Eric Laurent10351942014-05-08 18:49:52 -07006599
Eric Laurent81784c32012-11-19 14:55:58 -08006600 return reconfig;
6601}
6602
6603String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6604{
Eric Laurent81784c32012-11-19 14:55:58 -08006605 Mutex::Autolock _l(mLock);
6606 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07006607 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08006608 }
6609
Glenn Kastend8ea6992013-07-16 14:17:15 -07006610 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
6611 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08006612 free(s);
6613 return out_s8;
6614}
6615
Eric Laurent021cf962014-05-13 10:18:14 -07006616void AudioFlinger::RecordThread::audioConfigChanged(int event, int param __unused) {
Eric Laurent81784c32012-11-19 14:55:58 -08006617 AudioSystem::OutputDescriptor desc;
Glenn Kastenb2737d02013-08-19 12:03:11 -07006618 const void *param2 = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006619
6620 switch (event) {
6621 case AudioSystem::INPUT_OPENED:
6622 case AudioSystem::INPUT_CONFIG_CHANGED:
Glenn Kastenfad226a2013-07-16 17:19:58 -07006623 desc.channelMask = mChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08006624 desc.samplingRate = mSampleRate;
6625 desc.format = mFormat;
6626 desc.frameCount = mFrameCount;
6627 desc.latency = 0;
6628 param2 = &desc;
6629 break;
6630
6631 case AudioSystem::INPUT_CLOSED:
6632 default:
6633 break;
6634 }
Eric Laurent021cf962014-05-13 10:18:14 -07006635 mAudioFlinger->audioConfigChanged(event, mId, param2);
Eric Laurent81784c32012-11-19 14:55:58 -08006636}
6637
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006638void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006639{
Eric Laurent81784c32012-11-19 14:55:58 -08006640 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
6641 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07006642 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07006643 if (mChannelCount > FCC_8) {
6644 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
6645 }
Andy Hung463be252014-07-10 16:56:07 -07006646 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
6647 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07006648 if (!audio_is_linear_pcm(mFormat)) {
6649 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07006650 }
Eric Laurent665470b2014-07-03 16:37:08 -07006651 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08006652 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
6653 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006654 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08006655 // 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 -07006656 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08006657 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006658 // A larger value should allow more old data to be read after a track calls start(),
6659 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07006660 //
6661 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08006662 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07006663 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07006664 free(mRsmpInBuffer);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006665
6666 // TODO optimize audio capture buffer sizes ...
6667 // Here we calculate the size of the sliding buffer used as a source
6668 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
6669 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
6670 // be better to have it derived from the pipe depth in the long term.
6671 // The current value is higher than necessary. However it should not add to latency.
6672
Glenn Kasten85948432013-08-19 12:09:05 -07006673 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung57446612015-04-19 23:56:46 -07006674 (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006675
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006676 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
6677 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08006678}
6679
Glenn Kasten5f972c02014-01-13 09:59:31 -08006680uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08006681{
6682 Mutex::Autolock _l(mLock);
6683 if (initCheck() != NO_ERROR) {
6684 return 0;
6685 }
6686
6687 return mInput->stream->get_input_frames_lost(mInput->stream);
6688}
6689
6690uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
6691{
6692 Mutex::Autolock _l(mLock);
6693 uint32_t result = 0;
6694 if (getEffectChain_l(sessionId) != 0) {
6695 result = EFFECT_SESSION;
6696 }
6697
6698 for (size_t i = 0; i < mTracks.size(); ++i) {
6699 if (sessionId == mTracks[i]->sessionId()) {
6700 result |= TRACK_SESSION;
6701 break;
6702 }
6703 }
6704
6705 return result;
6706}
6707
6708KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
6709{
6710 KeyedVector<int, bool> ids;
6711 Mutex::Autolock _l(mLock);
6712 for (size_t j = 0; j < mTracks.size(); ++j) {
6713 sp<RecordThread::RecordTrack> track = mTracks[j];
6714 int sessionId = track->sessionId();
6715 if (ids.indexOfKey(sessionId) < 0) {
6716 ids.add(sessionId, true);
6717 }
6718 }
6719 return ids;
6720}
6721
6722AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6723{
6724 Mutex::Autolock _l(mLock);
6725 AudioStreamIn *input = mInput;
6726 mInput = NULL;
6727 return input;
6728}
6729
6730// this method must always be called either with ThreadBase mLock held or inside the thread loop
6731audio_stream_t* AudioFlinger::RecordThread::stream() const
6732{
6733 if (mInput == NULL) {
6734 return NULL;
6735 }
6736 return &mInput->stream->common;
6737}
6738
6739status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6740{
6741 // only one chain per input thread
6742 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07006743 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08006744 return INVALID_OPERATION;
6745 }
6746 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07006747 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08006748 chain->setInBuffer(NULL);
6749 chain->setOutBuffer(NULL);
6750
6751 checkSuspendOnAddEffectChain_l(chain);
6752
Eric Laurent1b928682014-10-02 19:41:47 -07006753 // make sure enabled pre processing effects state is communicated to the HAL as we
6754 // just moved them to a new input stream.
6755 chain->syncHalEffectsState();
6756
Eric Laurent81784c32012-11-19 14:55:58 -08006757 mEffectChains.add(chain);
6758
6759 return NO_ERROR;
6760}
6761
6762size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6763{
6764 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6765 ALOGW_IF(mEffectChains.size() != 1,
6766 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6767 chain.get(), mEffectChains.size(), this);
6768 if (mEffectChains.size() == 1) {
6769 mEffectChains.removeAt(0);
6770 }
6771 return 0;
6772}
6773
Eric Laurent1c333e22014-05-20 10:48:17 -07006774status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
6775 audio_patch_handle_t *handle)
6776{
6777 status_t status = NO_ERROR;
6778 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6779 // store new device and send to effects
6780 mInDevice = patch->sources[0].ext.device.type;
6781 for (size_t i = 0; i < mEffectChains.size(); i++) {
6782 mEffectChains[i]->setDevice_l(mInDevice);
6783 }
6784
6785 // disable AEC and NS if the device is a BT SCO headset supporting those
6786 // pre processings
6787 if (mTracks.size() > 0) {
6788 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6789 mAudioFlinger->btNrecIsOff();
6790 for (size_t i = 0; i < mTracks.size(); i++) {
6791 sp<RecordTrack> track = mTracks[i];
6792 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6793 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6794 }
6795 }
6796
6797 // store new source and send to effects
6798 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
6799 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
6800 for (size_t i = 0; i < mEffectChains.size(); i++) {
6801 mEffectChains[i]->setAudioSource_l(mAudioSource);
6802 }
6803 }
6804
6805 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6806 status = hwDevice->create_audio_patch(hwDevice,
6807 patch->num_sources,
6808 patch->sources,
6809 patch->num_sinks,
6810 patch->sinks,
6811 handle);
6812 } else {
6813 ALOG_ASSERT(false, "createAudioPatch_l() called on a pre 3.0 HAL");
6814 }
6815 return status;
6816}
6817
6818status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
6819{
6820 status_t status = NO_ERROR;
6821 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
6822 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
6823 status = hwDevice->release_audio_patch(hwDevice, handle);
6824 } else {
6825 ALOG_ASSERT(false, "releaseAudioPatch_l() called on a pre 3.0 HAL");
6826 }
6827 return status;
6828}
6829
Eric Laurent83b88082014-06-20 18:31:16 -07006830void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
6831{
6832 Mutex::Autolock _l(mLock);
6833 mTracks.add(record);
6834}
6835
6836void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
6837{
6838 Mutex::Autolock _l(mLock);
6839 destroyTrack_l(record);
6840}
6841
6842void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
6843{
6844 ThreadBase::getAudioPortConfig(config);
6845 config->role = AUDIO_PORT_ROLE_SINK;
6846 config->ext.mix.hw_module = mInput->audioHwDev->handle();
6847 config->ext.mix.usecase.source = mAudioSource;
6848}
Eric Laurent1c333e22014-05-20 10:48:17 -07006849
Glenn Kasten63238ef2015-03-02 15:50:29 -08006850} // namespace android