blob: f206e969d6b7268fe3524b86bc22dd79715ebda5 [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>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070045#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <media/nbaio/AudioStreamOutSink.h>
47#include <media/nbaio/MonoPipe.h>
48#include <media/nbaio/MonoPipeReader.h>
49#include <media/nbaio/Pipe.h>
50#include <media/nbaio/PipeReader.h>
51#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080052#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54#include <powermanager/PowerManager.h>
55
Eric Laurent81784c32012-11-19 14:55:58 -080056#include "AudioFlinger.h"
57#include "AudioMixer.h"
Andy Hungd330ee42015-04-20 13:23:41 -070058#include "BufferProviders.h"
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080061#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070062#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063
Eric Laurent81784c32012-11-19 14:55:58 -080064#ifdef ADD_BATTERY_DATA
65#include <media/IMediaPlayerService.h>
66#include <media/IMediaDeathNotifier.h>
67#endif
68
Eric Laurent81784c32012-11-19 14:55:58 -080069#ifdef DEBUG_CPU_USAGE
70#include <cpustats/CentralTendencyStatistics.h>
71#include <cpustats/ThreadCpuUsage.h>
72#endif
73
74// ----------------------------------------------------------------------------
75
76// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
88
Andy Hung6770c6f2015-04-07 13:43:36 -070089// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070090#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070091template <typename T>
92static inline T min(const T& a, const T& b)
93{
94 return a < b ? a : b;
95}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096
Andy Hungd330ee42015-04-20 13:23:41 -070097#ifndef ARRAY_SIZE
98#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
99#endif
100
Eric Laurent81784c32012-11-19 14:55:58 -0800101namespace android {
102
103// retry counts for buffer fill timeout
104// 50 * ~20msecs = 1 second
105static const int8_t kMaxTrackRetries = 50;
106static const int8_t kMaxTrackStartupRetries = 50;
107// allow less retry attempts on direct output thread.
108// direct outputs can be a scarce resource in audio hardware and should
109// be released as quickly as possible.
110static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurent51716182016-02-29 18:00:56 -0800111// retry count before removing active track in case of underrun on offloaded thread:
112// we need to make sure that AudioTrack client has enough time to send large buffers
113//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
114// for offloaded tracks
115static const int8_t kMaxTrackRetriesOffload = 10;
116static const int8_t kMaxTrackStartupRetriesOffload = 100;
117
Eric Laurent81784c32012-11-19 14:55:58 -0800118
119// don't warn about blocked writes or record buffer overflows more often than this
120static const nsecs_t kWarningThrottleNs = seconds(5);
121
122// RecordThread loop sleep time upon application overrun or audio HAL read error
123static const int kRecordThreadSleepUs = 5000;
124
Eric Laurent10351942014-05-08 18:49:52 -0700125// maximum time to wait in sendConfigEvent_l() for a status to be received
126static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800127
128// minimum sleep time for the mixer thread loop when tracks are active but in underrun
129static const uint32_t kMinThreadSleepTimeUs = 5000;
130// maximum divider applied to the active sleep time in the mixer thread loop
131static const uint32_t kMaxThreadSleepTimeShift = 2;
132
Andy Hung09a50072014-02-27 14:30:47 -0800133// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800135static const uint32_t kMinNormalSinkBufferSizeMs = 20;
136// maximum normal sink buffer size
137static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800138
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700139// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
140// FIXME This should be based on experimentally observed scheduling jitter
141static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
142
Eric Laurent972a1732013-09-04 09:42:59 -0700143// Offloaded output thread standby delay: allows track transition without going to standby
144static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
145
Eric Laurent51716182016-02-29 18:00:56 -0800146// Direct output thread minimum sleep time in idle or active(underrun) state
147static const nsecs_t kDirectMinSleepTimeUs = 10000;
148
149// Offloaded output bit rate in bits per second when unknown.
150// Used for sleep time calculation, so use a high default bitrate to be conservative on sleep time.
151static const uint32_t kOffloadDefaultBitRateBps = 1500000;
152
153
Eric Laurent81784c32012-11-19 14:55:58 -0800154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
160 // multiplier is calculated based on min & max normal mixer buffer size
161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700171// Whether to use fast capture
172static const enum {
173 FastCapture_Never, // never initialize or use: for debugging only
174 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
175 FastCapture_Static, // initialize if needed, then use all the time if initialized
176} kUseFastCapture = FastCapture_Static;
177
Eric Laurent81784c32012-11-19 14:55:58 -0800178// Priorities for requestPriority
179static const int kPriorityAudioApp = 2;
180static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
183// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
184// for the track. The client then sub-divides this into smaller buffers for its use.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800185// Currently the client uses N-buffering by default, but doesn't tell us about the value of N.
186// So for now we just assume that client is double-buffered for fast tracks.
187// FIXME It would be better for client to tell AudioFlinger the value of N,
188// so AudioFlinger could allocate the right amount of memory.
Eric Laurent81784c32012-11-19 14:55:58 -0800189// See the client's minBufCount and mNotificationFramesAct calculations for details.
Glenn Kasten03490092014-05-27 12:30:54 -0700190
191// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800192static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800193
Glenn Kasten03490092014-05-27 12:30:54 -0700194// The minimum and maximum allowed values
195static const int kFastTrackMultiplierMin = 1;
196static const int kFastTrackMultiplierMax = 2;
197
198// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
199static int sFastTrackMultiplier = kFastTrackMultiplier;
200
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201// See Thread::readOnlyHeap().
202// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
203// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
204// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700205static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700206
Eric Laurent81784c32012-11-19 14:55:58 -0800207// ----------------------------------------------------------------------------
208
Glenn Kasten03490092014-05-27 12:30:54 -0700209static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
210
211static void sFastTrackMultiplierInit()
212{
213 char value[PROPERTY_VALUE_MAX];
214 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
215 char *endptr;
216 unsigned long ul = strtoul(value, &endptr, 0);
217 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
218 sFastTrackMultiplier = (int) ul;
219 }
220 }
221}
222
223// ----------------------------------------------------------------------------
224
Eric Laurent81784c32012-11-19 14:55:58 -0800225#ifdef ADD_BATTERY_DATA
226// To collect the amplifier usage
227static void addBatteryData(uint32_t params) {
228 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
229 if (service == NULL) {
230 // it already logged
231 return;
232 }
233
234 service->addBatteryData(params);
235}
236#endif
237
Andy Hung3f0c9022016-01-15 17:49:46 -0800238// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
239struct {
240 // call when you acquire a partial wakelock
241 void acquire(const sp<IBinder> &wakeLockToken) {
242 pthread_mutex_lock(&mLock);
243 if (wakeLockToken.get() == nullptr) {
244 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
245 } else {
246 if (mCount == 0) {
247 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
248 }
249 ++mCount;
250 }
251 pthread_mutex_unlock(&mLock);
252 }
253
254 // call when you release a partial wakelock.
255 void release(const sp<IBinder> &wakeLockToken) {
256 if (wakeLockToken.get() == nullptr) {
257 return;
258 }
259 pthread_mutex_lock(&mLock);
260 if (--mCount < 0) {
261 ALOGE("negative wakelock count");
262 mCount = 0;
263 }
264 pthread_mutex_unlock(&mLock);
265 }
266
267 // retrieves the boottime timebase offset from monotonic.
268 int64_t getBoottimeOffset() {
269 pthread_mutex_lock(&mLock);
270 int64_t boottimeOffset = mBoottimeOffset;
271 pthread_mutex_unlock(&mLock);
272 return boottimeOffset;
273 }
274
275 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
276 // and the selected timebase.
277 // Currently only TIMEBASE_BOOTTIME is allowed.
278 //
279 // This only needs to be called upon acquiring the first partial wakelock
280 // after all other partial wakelocks are released.
281 //
282 // We do an empirical measurement of the offset rather than parsing
283 // /proc/timer_list since the latter is not a formal kernel ABI.
284 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
285 int clockbase;
286 switch (timebase) {
287 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
288 clockbase = SYSTEM_TIME_BOOTTIME;
289 break;
290 default:
291 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
292 break;
293 }
294 // try three times to get the clock offset, choose the one
295 // with the minimum gap in measurements.
296 const int tries = 3;
297 nsecs_t bestGap, measured;
298 for (int i = 0; i < tries; ++i) {
299 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t tbase = systemTime(clockbase);
301 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t gap = tmono2 - tmono;
303 if (i == 0 || gap < bestGap) {
304 bestGap = gap;
305 measured = tbase - ((tmono + tmono2) >> 1);
306 }
307 }
308
309 // to avoid micro-adjusting, we don't change the timebase
310 // unless it is significantly different.
311 //
312 // Assumption: It probably takes more than toleranceNs to
313 // suspend and resume the device.
314 static int64_t toleranceNs = 10000; // 10 us
315 if (llabs(*offset - measured) > toleranceNs) {
316 ALOGV("Adjusting timebase offset old: %lld new: %lld",
317 (long long)*offset, (long long)measured);
318 *offset = measured;
319 }
320 }
321
322 pthread_mutex_t mLock;
323 int32_t mCount;
324 int64_t mBoottimeOffset;
325} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800326
327// ----------------------------------------------------------------------------
328// CPU Stats
329// ----------------------------------------------------------------------------
330
331class CpuStats {
332public:
333 CpuStats();
334 void sample(const String8 &title);
335#ifdef DEBUG_CPU_USAGE
336private:
337 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
338 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
339
340 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
341
342 int mCpuNum; // thread's current CPU number
343 int mCpukHz; // frequency of thread's current CPU in kHz
344#endif
345};
346
347CpuStats::CpuStats()
348#ifdef DEBUG_CPU_USAGE
349 : mCpuNum(-1), mCpukHz(-1)
350#endif
351{
352}
353
Glenn Kasten0f11b512014-01-31 16:18:54 -0800354void CpuStats::sample(const String8 &title
355#ifndef DEBUG_CPU_USAGE
356 __unused
357#endif
358 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800359#ifdef DEBUG_CPU_USAGE
360 // get current thread's delta CPU time in wall clock ns
361 double wcNs;
362 bool valid = mCpuUsage.sampleAndEnable(wcNs);
363
364 // record sample for wall clock statistics
365 if (valid) {
366 mWcStats.sample(wcNs);
367 }
368
369 // get the current CPU number
370 int cpuNum = sched_getcpu();
371
372 // get the current CPU frequency in kHz
373 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
374
375 // check if either CPU number or frequency changed
376 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
377 mCpuNum = cpuNum;
378 mCpukHz = cpukHz;
379 // ignore sample for purposes of cycles
380 valid = false;
381 }
382
383 // if no change in CPU number or frequency, then record sample for cycle statistics
384 if (valid && mCpukHz > 0) {
385 double cycles = wcNs * cpukHz * 0.000001;
386 mHzStats.sample(cycles);
387 }
388
389 unsigned n = mWcStats.n();
390 // mCpuUsage.elapsed() is expensive, so don't call it every loop
391 if ((n & 127) == 1) {
392 long long elapsed = mCpuUsage.elapsed();
393 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
394 double perLoop = elapsed / (double) n;
395 double perLoop100 = perLoop * 0.01;
396 double perLoop1k = perLoop * 0.001;
397 double mean = mWcStats.mean();
398 double stddev = mWcStats.stddev();
399 double minimum = mWcStats.minimum();
400 double maximum = mWcStats.maximum();
401 double meanCycles = mHzStats.mean();
402 double stddevCycles = mHzStats.stddev();
403 double minCycles = mHzStats.minimum();
404 double maxCycles = mHzStats.maximum();
405 mCpuUsage.resetElapsed();
406 mWcStats.reset();
407 mHzStats.reset();
408 ALOGD("CPU usage for %s over past %.1f secs\n"
409 " (%u mixer loops at %.1f mean ms per loop):\n"
410 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
411 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
412 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
413 title.string(),
414 elapsed * .000000001, n, perLoop * .000001,
415 mean * .001,
416 stddev * .001,
417 minimum * .001,
418 maximum * .001,
419 mean / perLoop100,
420 stddev / perLoop100,
421 minimum / perLoop100,
422 maximum / perLoop100,
423 meanCycles / perLoop1k,
424 stddevCycles / perLoop1k,
425 minCycles / perLoop1k,
426 maxCycles / perLoop1k);
427
428 }
429 }
430#endif
431};
432
433// ----------------------------------------------------------------------------
434// ThreadBase
435// ----------------------------------------------------------------------------
436
Glenn Kasten97b7b752014-09-28 13:04:24 -0700437// static
438const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
439{
440 switch (type) {
441 case MIXER:
442 return "MIXER";
443 case DIRECT:
444 return "DIRECT";
445 case DUPLICATING:
446 return "DUPLICATING";
447 case RECORD:
448 return "RECORD";
449 case OFFLOAD:
450 return "OFFLOAD";
451 default:
452 return "unknown";
453 }
454}
455
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456String8 devicesToString(audio_devices_t devices)
457{
458 static const struct mapping {
459 audio_devices_t mDevices;
460 const char * mString;
461 } mappingsOut[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800462 {AUDIO_DEVICE_OUT_EARPIECE, "EARPIECE"},
463 {AUDIO_DEVICE_OUT_SPEAKER, "SPEAKER"},
464 {AUDIO_DEVICE_OUT_WIRED_HEADSET, "WIRED_HEADSET"},
465 {AUDIO_DEVICE_OUT_WIRED_HEADPHONE, "WIRED_HEADPHONE"},
466 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO, "BLUETOOTH_SCO"},
467 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
468 {AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, "BLUETOOTH_SCO_CARKIT"},
469 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
470 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,"BLUETOOTH_A2DP_HEADPHONES"},
471 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, "BLUETOOTH_A2DP_SPEAKER"},
472 {AUDIO_DEVICE_OUT_AUX_DIGITAL, "AUX_DIGITAL"},
473 {AUDIO_DEVICE_OUT_HDMI, "HDMI"},
474 {AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET,"ANLG_DOCK_HEADSET"},
475 {AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,"DGTL_DOCK_HEADSET"},
476 {AUDIO_DEVICE_OUT_USB_ACCESSORY, "USB_ACCESSORY"},
477 {AUDIO_DEVICE_OUT_USB_DEVICE, "USB_DEVICE"},
478 {AUDIO_DEVICE_OUT_TELEPHONY_TX, "TELEPHONY_TX"},
479 {AUDIO_DEVICE_OUT_LINE, "LINE"},
480 {AUDIO_DEVICE_OUT_HDMI_ARC, "HDMI_ARC"},
481 {AUDIO_DEVICE_OUT_SPDIF, "SPDIF"},
482 {AUDIO_DEVICE_OUT_FM, "FM"},
483 {AUDIO_DEVICE_OUT_AUX_LINE, "AUX_LINE"},
484 {AUDIO_DEVICE_OUT_SPEAKER_SAFE, "SPEAKER_SAFE"},
485 {AUDIO_DEVICE_OUT_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800486 {AUDIO_DEVICE_OUT_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800487 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800488 }, mappingsIn[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800489 {AUDIO_DEVICE_IN_COMMUNICATION, "COMMUNICATION"},
490 {AUDIO_DEVICE_IN_AMBIENT, "AMBIENT"},
491 {AUDIO_DEVICE_IN_BUILTIN_MIC, "BUILTIN_MIC"},
492 {AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, "BLUETOOTH_SCO_HEADSET"},
493 {AUDIO_DEVICE_IN_WIRED_HEADSET, "WIRED_HEADSET"},
494 {AUDIO_DEVICE_IN_AUX_DIGITAL, "AUX_DIGITAL"},
495 {AUDIO_DEVICE_IN_VOICE_CALL, "VOICE_CALL"},
496 {AUDIO_DEVICE_IN_TELEPHONY_RX, "TELEPHONY_RX"},
497 {AUDIO_DEVICE_IN_BACK_MIC, "BACK_MIC"},
498 {AUDIO_DEVICE_IN_REMOTE_SUBMIX, "REMOTE_SUBMIX"},
499 {AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, "ANLG_DOCK_HEADSET"},
500 {AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, "DGTL_DOCK_HEADSET"},
501 {AUDIO_DEVICE_IN_USB_ACCESSORY, "USB_ACCESSORY"},
502 {AUDIO_DEVICE_IN_USB_DEVICE, "USB_DEVICE"},
503 {AUDIO_DEVICE_IN_FM_TUNER, "FM_TUNER"},
504 {AUDIO_DEVICE_IN_TV_TUNER, "TV_TUNER"},
505 {AUDIO_DEVICE_IN_LINE, "LINE"},
506 {AUDIO_DEVICE_IN_SPDIF, "SPDIF"},
507 {AUDIO_DEVICE_IN_BLUETOOTH_A2DP, "BLUETOOTH_A2DP"},
508 {AUDIO_DEVICE_IN_LOOPBACK, "LOOPBACK"},
509 {AUDIO_DEVICE_IN_IP, "IP"},
Eric Laurent58545be2016-02-22 18:54:20 -0800510 {AUDIO_DEVICE_IN_BUS, "BUS"},
Glenn Kasten818da522015-12-02 13:53:26 -0800511 {AUDIO_DEVICE_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800512 };
513 String8 result;
514 audio_devices_t allDevices = AUDIO_DEVICE_NONE;
515 const mapping *entry;
516 if (devices & AUDIO_DEVICE_BIT_IN) {
517 devices &= ~AUDIO_DEVICE_BIT_IN;
518 entry = mappingsIn;
519 } else {
520 entry = mappingsOut;
521 }
522 for ( ; entry->mDevices != AUDIO_DEVICE_NONE; entry++) {
523 allDevices = (audio_devices_t) (allDevices | entry->mDevices);
524 if (devices & entry->mDevices) {
525 if (!result.isEmpty()) {
526 result.append("|");
527 }
528 result.append(entry->mString);
529 }
530 }
531 if (devices & ~allDevices) {
532 if (!result.isEmpty()) {
533 result.append("|");
534 }
535 result.appendFormat("0x%X", devices & ~allDevices);
536 }
537 if (result.isEmpty()) {
538 result.append(entry->mString);
539 }
540 return result;
541}
542
543String8 inputFlagsToString(audio_input_flags_t flags)
544{
545 static const struct mapping {
546 audio_input_flags_t mFlag;
547 const char * mString;
548 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800549 {AUDIO_INPUT_FLAG_FAST, "FAST"},
550 {AUDIO_INPUT_FLAG_HW_HOTWORD, "HW_HOTWORD"},
551 {AUDIO_INPUT_FLAG_RAW, "RAW"},
552 {AUDIO_INPUT_FLAG_SYNC, "SYNC"},
553 {AUDIO_INPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800554 };
555 String8 result;
556 audio_input_flags_t allFlags = AUDIO_INPUT_FLAG_NONE;
557 const mapping *entry;
558 for (entry = mappings; entry->mFlag != AUDIO_INPUT_FLAG_NONE; entry++) {
559 allFlags = (audio_input_flags_t) (allFlags | entry->mFlag);
560 if (flags & entry->mFlag) {
561 if (!result.isEmpty()) {
562 result.append("|");
563 }
564 result.append(entry->mString);
565 }
566 }
567 if (flags & ~allFlags) {
568 if (!result.isEmpty()) {
569 result.append("|");
570 }
571 result.appendFormat("0x%X", flags & ~allFlags);
572 }
573 if (result.isEmpty()) {
574 result.append(entry->mString);
575 }
576 return result;
577}
578
579String8 outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700580{
581 static const struct mapping {
582 audio_output_flags_t mFlag;
583 const char * mString;
584 } mappings[] = {
Glenn Kasten818da522015-12-02 13:53:26 -0800585 {AUDIO_OUTPUT_FLAG_DIRECT, "DIRECT"},
586 {AUDIO_OUTPUT_FLAG_PRIMARY, "PRIMARY"},
587 {AUDIO_OUTPUT_FLAG_FAST, "FAST"},
588 {AUDIO_OUTPUT_FLAG_DEEP_BUFFER, "DEEP_BUFFER"},
589 {AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,"COMPRESS_OFFLOAD"},
590 {AUDIO_OUTPUT_FLAG_NON_BLOCKING, "NON_BLOCKING"},
591 {AUDIO_OUTPUT_FLAG_HW_AV_SYNC, "HW_AV_SYNC"},
592 {AUDIO_OUTPUT_FLAG_RAW, "RAW"},
593 {AUDIO_OUTPUT_FLAG_SYNC, "SYNC"},
594 {AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO, "IEC958_NONAUDIO"},
595 {AUDIO_OUTPUT_FLAG_NONE, "NONE"}, // must be last
Glenn Kasten97b7b752014-09-28 13:04:24 -0700596 };
597 String8 result;
598 audio_output_flags_t allFlags = AUDIO_OUTPUT_FLAG_NONE;
599 const mapping *entry;
600 for (entry = mappings; entry->mFlag != AUDIO_OUTPUT_FLAG_NONE; entry++) {
601 allFlags = (audio_output_flags_t) (allFlags | entry->mFlag);
602 if (flags & entry->mFlag) {
603 if (!result.isEmpty()) {
604 result.append("|");
605 }
606 result.append(entry->mString);
607 }
608 }
609 if (flags & ~allFlags) {
610 if (!result.isEmpty()) {
611 result.append("|");
612 }
613 result.appendFormat("0x%X", flags & ~allFlags);
614 }
615 if (result.isEmpty()) {
616 result.append(entry->mString);
617 }
618 return result;
619}
620
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800621const char *sourceToString(audio_source_t source)
622{
623 switch (source) {
624 case AUDIO_SOURCE_DEFAULT: return "default";
625 case AUDIO_SOURCE_MIC: return "mic";
626 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
627 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
628 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
629 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
630 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
631 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
632 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800633 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800634 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
635 case AUDIO_SOURCE_HOTWORD: return "hotword";
636 default: return "unknown";
637 }
638}
639
Eric Laurent81784c32012-11-19 14:55:58 -0800640AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700641 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800642 : Thread(false /*canCallJava*/),
643 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700644 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700645 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800646 // are set by PlaybackThread::readOutputParameters_l() or
647 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700648 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800649 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700650 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
651 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800652 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700653 mDeathRecipient(new PMDeathRecipient(this)),
Wei Jia3f273d12015-11-24 09:06:49 -0800654 mSystemReady(systemReady),
655 mNotifiedBatteryStart(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800656{
Eric Laurent296fb132015-05-01 11:38:42 -0700657 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800658}
659
660AudioFlinger::ThreadBase::~ThreadBase()
661{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700662 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700663 mConfigEvents.clear();
664
Eric Laurent81784c32012-11-19 14:55:58 -0800665 // do not lock the mutex in destructor
666 releaseWakeLock_l();
667 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800668 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800669 binder->unlinkToDeath(mDeathRecipient);
670 }
671}
672
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700673status_t AudioFlinger::ThreadBase::readyToRun()
674{
675 status_t status = initCheck();
676 if (status == NO_ERROR) {
677 ALOGI("AudioFlinger's thread %p ready to run", this);
678 } else {
679 ALOGE("No working audio driver found.");
680 }
681 return status;
682}
683
Eric Laurent81784c32012-11-19 14:55:58 -0800684void AudioFlinger::ThreadBase::exit()
685{
686 ALOGV("ThreadBase::exit");
687 // do any cleanup required for exit to succeed
688 preExit();
689 {
690 // This lock prevents the following race in thread (uniprocessor for illustration):
691 // if (!exitPending()) {
692 // // context switch from here to exit()
693 // // exit() calls requestExit(), what exitPending() observes
694 // // exit() calls signal(), which is dropped since no waiters
695 // // context switch back from exit() to here
696 // mWaitWorkCV.wait(...);
697 // // now thread is hung
698 // }
699 AutoMutex lock(mLock);
700 requestExit();
701 mWaitWorkCV.broadcast();
702 }
703 // When Thread::requestExitAndWait is made virtual and this method is renamed to
704 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
705 requestExitAndWait();
706}
707
708status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
709{
710 status_t status;
711
712 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
713 Mutex::Autolock _l(mLock);
714
Eric Laurent10351942014-05-08 18:49:52 -0700715 return sendSetParameterConfigEvent_l(keyValuePairs);
716}
717
718// sendConfigEvent_l() must be called with ThreadBase::mLock held
719// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
720status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
721{
722 status_t status = NO_ERROR;
723
Eric Laurent72e3f392015-05-20 14:43:50 -0700724 if (event->mRequiresSystemReady && !mSystemReady) {
725 event->mWaitStatus = false;
726 mPendingConfigEvents.add(event);
727 return status;
728 }
Eric Laurent10351942014-05-08 18:49:52 -0700729 mConfigEvents.add(event);
730 ALOGV("sendConfigEvent_l() num events %d event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800731 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700732 mLock.unlock();
733 {
734 Mutex::Autolock _l(event->mLock);
735 while (event->mWaitStatus) {
736 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
737 event->mStatus = TIMED_OUT;
738 event->mWaitStatus = false;
739 }
740 }
741 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800742 }
Eric Laurent10351942014-05-08 18:49:52 -0700743 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800744 return status;
745}
746
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700747void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800748{
749 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700750 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800751}
752
753// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700754void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800755{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700756 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700757 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Eric Laurent72e3f392015-05-20 14:43:50 -0700760void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
761{
762 Mutex::Autolock _l(mLock);
763 sendPrioConfigEvent_l(pid, tid, prio);
764}
765
Eric Laurent81784c32012-11-19 14:55:58 -0800766// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
767void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
768{
Eric Laurent10351942014-05-08 18:49:52 -0700769 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
770 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800771}
772
Eric Laurent10351942014-05-08 18:49:52 -0700773// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
774status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800775{
Andy Hung2ddee192015-12-18 17:34:44 -0800776 sp<ConfigEvent> configEvent;
777 AudioParameter param(keyValuePair);
778 int value;
779 if (param.getInt(String8(AUDIO_PARAMETER_MONO_OUTPUT), value) == NO_ERROR) {
780 setMasterMono_l(value != 0);
781 if (param.size() == 1) {
782 return NO_ERROR; // should be a solo parameter - we don't pass down
783 }
784 param.remove(String8(AUDIO_PARAMETER_MONO_OUTPUT));
785 configEvent = new SetParameterConfigEvent(param.toString());
786 } else {
787 configEvent = new SetParameterConfigEvent(keyValuePair);
788 }
Eric Laurent10351942014-05-08 18:49:52 -0700789 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700790}
791
Eric Laurent1c333e22014-05-20 10:48:17 -0700792status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
793 const struct audio_patch *patch,
794 audio_patch_handle_t *handle)
795{
796 Mutex::Autolock _l(mLock);
797 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
798 status_t status = sendConfigEvent_l(configEvent);
799 if (status == NO_ERROR) {
800 CreateAudioPatchConfigEventData *data =
801 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
802 *handle = data->mHandle;
803 }
804 return status;
805}
806
807status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
808 const audio_patch_handle_t handle)
809{
810 Mutex::Autolock _l(mLock);
811 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
812 return sendConfigEvent_l(configEvent);
813}
814
815
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700816// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700817void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700818{
Eric Laurent10351942014-05-08 18:49:52 -0700819 bool configChanged = false;
820
Eric Laurent81784c32012-11-19 14:55:58 -0800821 while (!mConfigEvents.isEmpty()) {
Eric Laurent10351942014-05-08 18:49:52 -0700822 ALOGV("processConfigEvents_l() remaining events %d", mConfigEvents.size());
823 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800824 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700825 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700826 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700827 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
828 // FIXME Need to understand why this has to be done asynchronously
829 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700830 true /*asynchronous*/);
831 if (err != 0) {
832 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700833 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700834 }
835 } break;
836 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700837 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700838 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700839 } break;
840 case CFG_EVENT_SET_PARAMETER: {
841 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
842 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
843 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700844 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700845 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700846 case CFG_EVENT_CREATE_AUDIO_PATCH: {
847 CreateAudioPatchConfigEventData *data =
848 (CreateAudioPatchConfigEventData *)event->mData.get();
849 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
850 } break;
851 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
852 ReleaseAudioPatchConfigEventData *data =
853 (ReleaseAudioPatchConfigEventData *)event->mData.get();
854 event->mStatus = releaseAudioPatch_l(data->mHandle);
855 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700856 default:
Eric Laurent10351942014-05-08 18:49:52 -0700857 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700858 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Eric Laurent10351942014-05-08 18:49:52 -0700860 {
861 Mutex::Autolock _l(event->mLock);
862 if (event->mWaitStatus) {
863 event->mWaitStatus = false;
864 event->mCond.signal();
865 }
866 }
867 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
868 }
869
870 if (configChanged) {
871 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872 }
Eric Laurent81784c32012-11-19 14:55:58 -0800873}
874
Marco Nelissenb2208842014-02-07 14:00:50 -0800875String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
876 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700877 const audio_channel_representation_t representation =
878 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700879
880 switch (representation) {
881 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
882 if (output) {
883 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
888 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
889 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
890 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
891 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
892 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
893 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
895 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
899 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
900 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
901 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
902 } else {
903 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
904 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
905 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
906 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
907 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
908 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
909 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
910 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
911 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
912 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
913 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
914 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
915 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
916 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
917 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
918 }
919 const int len = s.length();
920 if (len > 2) {
921 char *str = s.lockBuffer(len); // needed?
922 s.unlockBuffer(len - 2); // remove trailing ", "
923 }
924 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800925 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700926 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
927 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
928 return s;
929 default:
930 s.appendFormat("unknown mask, representation:%d bits:%#x",
931 representation, audio_channel_mask_get_bits(mask));
932 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800933 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800934}
935
Glenn Kasten0f11b512014-01-31 16:18:54 -0800936void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800937{
938 const size_t SIZE = 256;
939 char buffer[SIZE];
940 String8 result;
941
942 bool locked = AudioFlinger::dumpTryLock(mLock);
943 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700944 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
946
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800947 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, " I/O handle: %d\n", mId);
949 dprintf(fd, " TID: %d\n", getTid());
950 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700951 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700953 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat));
Elliott Hughes87cebad2014-05-22 10:14:43 -0700954 dprintf(fd, " HAL buffer size: %u bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700955 dprintf(fd, " Channel count: %u\n", mChannelCount);
956 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800957 channelMaskToString(mChannelMask, mType != RECORD).string());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700958 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
959 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700960 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800961 size_t numConfig = mConfigEvents.size();
962 if (numConfig) {
963 for (size_t i = 0; i < numConfig; i++) {
964 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700965 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800966 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700967 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800968 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700969 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800970 }
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800971 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).string());
972 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).string());
973 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800974
975 if (locked) {
976 mLock.unlock();
977 }
978}
979
980void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
981{
982 const size_t SIZE = 256;
983 char buffer[SIZE];
984 String8 result;
985
Marco Nelissenb2208842014-02-07 14:00:50 -0800986 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000987 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800988 write(fd, buffer, strlen(buffer));
989
Marco Nelissenb2208842014-02-07 14:00:50 -0800990 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800991 sp<EffectChain> chain = mEffectChains[i];
992 if (chain != 0) {
993 chain->dump(fd, args);
994 }
995 }
996}
997
Marco Nelissene14a5d62013-10-03 08:51:24 -0700998void AudioFlinger::ThreadBase::acquireWakeLock(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -0800999{
1000 Mutex::Autolock _l(mLock);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001001 acquireWakeLock_l(uid);
Eric Laurent81784c32012-11-19 14:55:58 -08001002}
1003
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001004String16 AudioFlinger::ThreadBase::getWakeLockTag()
1005{
1006 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001007 case MIXER:
1008 return String16("AudioMix");
1009 case DIRECT:
1010 return String16("AudioDirectOut");
1011 case DUPLICATING:
1012 return String16("AudioDup");
1013 case RECORD:
1014 return String16("AudioIn");
1015 case OFFLOAD:
1016 return String16("AudioOffload");
1017 default:
1018 ALOG_ASSERT(false);
1019 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001020 }
1021}
1022
Marco Nelissene14a5d62013-10-03 08:51:24 -07001023void AudioFlinger::ThreadBase::acquireWakeLock_l(int uid)
Eric Laurent81784c32012-11-19 14:55:58 -08001024{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001025 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001026 if (mPowerManager != 0) {
1027 sp<IBinder> binder = new BBinder();
Marco Nelissene14a5d62013-10-03 08:51:24 -07001028 status_t status;
1029 if (uid >= 0) {
Eric Laurent547789d2013-10-04 11:46:55 -07001030 status = mPowerManager->acquireWakeLockWithUid(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001031 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001032 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001033 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001034 uid,
1035 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001036 } else {
Eric Laurent547789d2013-10-04 11:46:55 -07001037 status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -07001038 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001039 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001040 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001041 true /* FIXME force oneway contrary to .aidl */);
Marco Nelissene14a5d62013-10-03 08:51:24 -07001042 }
Eric Laurent81784c32012-11-19 14:55:58 -08001043 if (status == NO_ERROR) {
1044 mWakeLockToken = binder;
1045 }
Glenn Kastend7dca052015-03-05 16:05:54 -08001046 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -08001047 }
Wei Jia3f273d12015-11-24 09:06:49 -08001048
1049 if (!mNotifiedBatteryStart) {
1050 BatteryNotifier::getInstance().noteStartAudio();
1051 mNotifiedBatteryStart = true;
1052 }
Andy Hung3f0c9022016-01-15 17:49:46 -08001053 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001054 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1055 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001056}
1057
1058void AudioFlinger::ThreadBase::releaseWakeLock()
1059{
1060 Mutex::Autolock _l(mLock);
1061 releaseWakeLock_l();
1062}
1063
1064void AudioFlinger::ThreadBase::releaseWakeLock_l()
1065{
Andy Hung3f0c9022016-01-15 17:49:46 -08001066 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001067 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001068 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001069 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001070 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
1071 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -08001072 }
1073 mWakeLockToken.clear();
1074 }
Wei Jia3f273d12015-11-24 09:06:49 -08001075
1076 if (mNotifiedBatteryStart) {
1077 BatteryNotifier::getInstance().noteStopAudio();
1078 mNotifiedBatteryStart = false;
1079 }
Eric Laurent81784c32012-11-19 14:55:58 -08001080}
1081
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001082void AudioFlinger::ThreadBase::updateWakeLockUids(const SortedVector<int> &uids) {
1083 Mutex::Autolock _l(mLock);
1084 updateWakeLockUids_l(uids);
1085}
1086
1087void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001088 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 // use checkService() to avoid blocking if power service is not up yet
1090 sp<IBinder> binder =
1091 defaultServiceManager()->checkService(String16("power"));
1092 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001093 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001094 } else {
1095 mPowerManager = interface_cast<IPowerManager>(binder);
1096 binder->linkToDeath(mDeathRecipient);
1097 }
1098 }
1099}
1100
1101void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<int> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001102 getPowerManager_l();
Andy Hung438e7572015-12-14 15:51:17 -08001103 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1104 if (mSystemReady) {
1105 ALOGE("no wake lock to update, but system ready!");
1106 } else {
1107 ALOGW("no wake lock to update, system not ready yet");
1108 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001109 return;
1110 }
1111 if (mPowerManager != 0) {
1112 sp<IBinder> binder = new BBinder();
1113 status_t status;
Glenn Kasten3abc2de2014-09-05 16:45:52 -07001114 status = mPowerManager->updateWakeLockUids(mWakeLockToken, uids.size(), uids.array(),
1115 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001116 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001117 }
1118}
1119
Eric Laurent81784c32012-11-19 14:55:58 -08001120void AudioFlinger::ThreadBase::clearPowerManager()
1121{
1122 Mutex::Autolock _l(mLock);
1123 releaseWakeLock_l();
1124 mPowerManager.clear();
1125}
1126
Glenn Kasten0f11b512014-01-31 16:18:54 -08001127void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 sp<ThreadBase> thread = mThread.promote();
1130 if (thread != 0) {
1131 thread->clearPowerManager();
1132 }
1133 ALOGW("power manager service died !!!");
1134}
1135
1136void AudioFlinger::ThreadBase::setEffectSuspended(
1137 const effect_uuid_t *type, bool suspend, int sessionId)
1138{
1139 Mutex::Autolock _l(mLock);
1140 setEffectSuspended_l(type, suspend, sessionId);
1141}
1142
1143void AudioFlinger::ThreadBase::setEffectSuspended_l(
1144 const effect_uuid_t *type, bool suspend, int sessionId)
1145{
1146 sp<EffectChain> chain = getEffectChain_l(sessionId);
1147 if (chain != 0) {
1148 if (type != NULL) {
1149 chain->setEffectSuspended_l(type, suspend);
1150 } else {
1151 chain->setEffectSuspendedAll_l(suspend);
1152 }
1153 }
1154
1155 updateSuspendedSessions_l(type, suspend, sessionId);
1156}
1157
1158void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1159{
1160 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1161 if (index < 0) {
1162 return;
1163 }
1164
1165 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1166 mSuspendedSessions.valueAt(index);
1167
1168 for (size_t i = 0; i < sessionEffects.size(); i++) {
1169 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1170 for (int j = 0; j < desc->mRefCount; j++) {
1171 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1172 chain->setEffectSuspendedAll_l(true);
1173 } else {
1174 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1175 desc->mType.timeLow);
1176 chain->setEffectSuspended_l(&desc->mType, true);
1177 }
1178 }
1179 }
1180}
1181
1182void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1183 bool suspend,
1184 int sessionId)
1185{
1186 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1187
1188 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1189
1190 if (suspend) {
1191 if (index >= 0) {
1192 sessionEffects = mSuspendedSessions.valueAt(index);
1193 } else {
1194 mSuspendedSessions.add(sessionId, sessionEffects);
1195 }
1196 } else {
1197 if (index < 0) {
1198 return;
1199 }
1200 sessionEffects = mSuspendedSessions.valueAt(index);
1201 }
1202
1203
1204 int key = EffectChain::kKeyForSuspendAll;
1205 if (type != NULL) {
1206 key = type->timeLow;
1207 }
1208 index = sessionEffects.indexOfKey(key);
1209
1210 sp<SuspendedSessionDesc> desc;
1211 if (suspend) {
1212 if (index >= 0) {
1213 desc = sessionEffects.valueAt(index);
1214 } else {
1215 desc = new SuspendedSessionDesc();
1216 if (type != NULL) {
1217 desc->mType = *type;
1218 }
1219 sessionEffects.add(key, desc);
1220 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1221 }
1222 desc->mRefCount++;
1223 } else {
1224 if (index < 0) {
1225 return;
1226 }
1227 desc = sessionEffects.valueAt(index);
1228 if (--desc->mRefCount == 0) {
1229 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1230 sessionEffects.removeItemsAt(index);
1231 if (sessionEffects.isEmpty()) {
1232 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1233 sessionId);
1234 mSuspendedSessions.removeItem(sessionId);
1235 }
1236 }
1237 }
1238 if (!sessionEffects.isEmpty()) {
1239 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1240 }
1241}
1242
1243void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1244 bool enabled,
1245 int sessionId)
1246{
1247 Mutex::Autolock _l(mLock);
1248 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1249}
1250
1251void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1252 bool enabled,
1253 int sessionId)
1254{
1255 if (mType != RECORD) {
1256 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1257 // another session. This gives the priority to well behaved effect control panels
1258 // and applications not using global effects.
1259 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1260 // global effects
1261 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1262 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1263 }
1264 }
1265
1266 sp<EffectChain> chain = getEffectChain_l(sessionId);
1267 if (chain != 0) {
1268 chain->checkSuspendOnEffectEnabled(effect, enabled);
1269 }
1270}
1271
1272// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1273sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1274 const sp<AudioFlinger::Client>& client,
1275 const sp<IEffectClient>& effectClient,
1276 int32_t priority,
1277 int sessionId,
1278 effect_descriptor_t *desc,
1279 int *enabled,
Glenn Kasten9156ef32013-08-06 15:39:08 -07001280 status_t *status)
Eric Laurent81784c32012-11-19 14:55:58 -08001281{
1282 sp<EffectModule> effect;
1283 sp<EffectHandle> handle;
1284 status_t lStatus;
1285 sp<EffectChain> chain;
1286 bool chainCreated = false;
1287 bool effectCreated = false;
1288 bool effectRegistered = false;
1289
1290 lStatus = initCheck();
1291 if (lStatus != NO_ERROR) {
1292 ALOGW("createEffect_l() Audio driver not initialized.");
1293 goto Exit;
1294 }
1295
Andy Hung98ef9782014-03-04 14:46:50 -08001296 // Reject any effect on Direct output threads for now, since the format of
1297 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1298 if (mType == DIRECT) {
1299 ALOGW("createEffect_l() Cannot add effect %s on Direct output type thread %s",
Glenn Kastend7dca052015-03-05 16:05:54 -08001300 desc->name, mThreadName);
Andy Hung98ef9782014-03-04 14:46:50 -08001301 lStatus = BAD_VALUE;
1302 goto Exit;
1303 }
1304
Andy Hung389cfdb2014-08-07 17:49:53 -07001305 // Reject any effect on mixer or duplicating multichannel sinks.
Andy Hung9a592762014-07-21 21:56:01 -07001306 // TODO: fix both format and multichannel issues with effects.
Andy Hung389cfdb2014-08-07 17:49:53 -07001307 if ((mType == MIXER || mType == DUPLICATING) && mChannelCount != FCC_2) {
1308 ALOGW("createEffect_l() Cannot add effect %s for multichannel(%d) %s threads",
1309 desc->name, mChannelCount, mType == MIXER ? "MIXER" : "DUPLICATING");
Andy Hung9a592762014-07-21 21:56:01 -07001310 lStatus = BAD_VALUE;
1311 goto Exit;
1312 }
1313
Eric Laurent5baf2af2013-09-12 17:37:00 -07001314 // Allow global effects only on offloaded and mixer threads
1315 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1316 switch (mType) {
1317 case MIXER:
1318 case OFFLOAD:
1319 break;
1320 case DIRECT:
1321 case DUPLICATING:
1322 case RECORD:
1323 default:
Glenn Kastend7dca052015-03-05 16:05:54 -08001324 ALOGW("createEffect_l() Cannot add global effect %s on thread %s",
1325 desc->name, mThreadName);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001326 lStatus = BAD_VALUE;
1327 goto Exit;
1328 }
Eric Laurent81784c32012-11-19 14:55:58 -08001329 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001330
Eric Laurent81784c32012-11-19 14:55:58 -08001331 // Only Pre processor effects are allowed on input threads and only on input threads
1332 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
1333 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
1334 desc->name, desc->flags, mType);
1335 lStatus = BAD_VALUE;
1336 goto Exit;
1337 }
1338
1339 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1340
1341 { // scope for mLock
1342 Mutex::Autolock _l(mLock);
1343
1344 // check for existing effect chain with the requested audio session
1345 chain = getEffectChain_l(sessionId);
1346 if (chain == 0) {
1347 // create a new chain for this session
1348 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1349 chain = new EffectChain(this, sessionId);
1350 addEffectChain_l(chain);
1351 chain->setStrategy(getStrategyForSession_l(sessionId));
1352 chainCreated = true;
1353 } else {
1354 effect = chain->getEffectFromDesc_l(desc);
1355 }
1356
1357 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1358
1359 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001360 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001361 // Check CPU and memory usage
1362 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1363 if (lStatus != NO_ERROR) {
1364 goto Exit;
1365 }
1366 effectRegistered = true;
1367 // create a new effect module if none present in the chain
1368 effect = new EffectModule(this, chain, desc, id, sessionId);
1369 lStatus = effect->status();
1370 if (lStatus != NO_ERROR) {
1371 goto Exit;
1372 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07001373 effect->setOffloaded(mType == OFFLOAD, mId);
1374
Eric Laurent81784c32012-11-19 14:55:58 -08001375 lStatus = chain->addEffect_l(effect);
1376 if (lStatus != NO_ERROR) {
1377 goto Exit;
1378 }
1379 effectCreated = true;
1380
1381 effect->setDevice(mOutDevice);
1382 effect->setDevice(mInDevice);
1383 effect->setMode(mAudioFlinger->getMode());
1384 effect->setAudioSource(mAudioSource);
1385 }
1386 // create effect handle and connect it to effect module
1387 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001388 lStatus = handle->initCheck();
1389 if (lStatus == OK) {
1390 lStatus = effect->addHandle(handle.get());
1391 }
Eric Laurent81784c32012-11-19 14:55:58 -08001392 if (enabled != NULL) {
1393 *enabled = (int)effect->isEnabled();
1394 }
1395 }
1396
1397Exit:
1398 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1399 Mutex::Autolock _l(mLock);
1400 if (effectCreated) {
1401 chain->removeEffect_l(effect);
1402 }
1403 if (effectRegistered) {
1404 AudioSystem::unregisterEffect(effect->id());
1405 }
1406 if (chainCreated) {
1407 removeEffectChain_l(chain);
1408 }
1409 handle.clear();
1410 }
1411
Glenn Kasten9156ef32013-08-06 15:39:08 -07001412 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001413 return handle;
1414}
1415
1416sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
1417{
1418 Mutex::Autolock _l(mLock);
1419 return getEffect_l(sessionId, effectId);
1420}
1421
1422sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
1423{
1424 sp<EffectChain> chain = getEffectChain_l(sessionId);
1425 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1426}
1427
1428// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1429// PlaybackThread::mLock held
1430status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1431{
1432 // check for existing effect chain with the requested audio session
1433 int sessionId = effect->sessionId();
1434 sp<EffectChain> chain = getEffectChain_l(sessionId);
1435 bool chainCreated = false;
1436
Eric Laurent5baf2af2013-09-12 17:37:00 -07001437 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1438 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1439 this, effect->desc().name, effect->desc().flags);
1440
Eric Laurent81784c32012-11-19 14:55:58 -08001441 if (chain == 0) {
1442 // create a new chain for this session
1443 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1444 chain = new EffectChain(this, sessionId);
1445 addEffectChain_l(chain);
1446 chain->setStrategy(getStrategyForSession_l(sessionId));
1447 chainCreated = true;
1448 }
1449 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1450
1451 if (chain->getEffectFromId_l(effect->id()) != 0) {
1452 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1453 this, effect->desc().name, chain.get());
1454 return BAD_VALUE;
1455 }
1456
Eric Laurent5baf2af2013-09-12 17:37:00 -07001457 effect->setOffloaded(mType == OFFLOAD, mId);
1458
Eric Laurent81784c32012-11-19 14:55:58 -08001459 status_t status = chain->addEffect_l(effect);
1460 if (status != NO_ERROR) {
1461 if (chainCreated) {
1462 removeEffectChain_l(chain);
1463 }
1464 return status;
1465 }
1466
1467 effect->setDevice(mOutDevice);
1468 effect->setDevice(mInDevice);
1469 effect->setMode(mAudioFlinger->getMode());
1470 effect->setAudioSource(mAudioSource);
1471 return NO_ERROR;
1472}
1473
1474void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
1475
1476 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
1477 effect_descriptor_t desc = effect->desc();
1478 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1479 detachAuxEffect_l(effect->id());
1480 }
1481
1482 sp<EffectChain> chain = effect->chain().promote();
1483 if (chain != 0) {
1484 // remove effect chain if removing last effect
1485 if (chain->removeEffect_l(effect) == 0) {
1486 removeEffectChain_l(chain);
1487 }
1488 } else {
1489 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1490 }
1491}
1492
1493void AudioFlinger::ThreadBase::lockEffectChains_l(
1494 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1495{
1496 effectChains = mEffectChains;
1497 for (size_t i = 0; i < mEffectChains.size(); i++) {
1498 mEffectChains[i]->lock();
1499 }
1500}
1501
1502void AudioFlinger::ThreadBase::unlockEffectChains(
1503 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1504{
1505 for (size_t i = 0; i < effectChains.size(); i++) {
1506 effectChains[i]->unlock();
1507 }
1508}
1509
1510sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
1511{
1512 Mutex::Autolock _l(mLock);
1513 return getEffectChain_l(sessionId);
1514}
1515
1516sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
1517{
1518 size_t size = mEffectChains.size();
1519 for (size_t i = 0; i < size; i++) {
1520 if (mEffectChains[i]->sessionId() == sessionId) {
1521 return mEffectChains[i];
1522 }
1523 }
1524 return 0;
1525}
1526
1527void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1528{
1529 Mutex::Autolock _l(mLock);
1530 size_t size = mEffectChains.size();
1531 for (size_t i = 0; i < size; i++) {
1532 mEffectChains[i]->setMode_l(mode);
1533 }
1534}
1535
Eric Laurent83b88082014-06-20 18:31:16 -07001536void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1537{
1538 config->type = AUDIO_PORT_TYPE_MIX;
1539 config->ext.mix.handle = mId;
1540 config->sample_rate = mSampleRate;
1541 config->format = mFormat;
1542 config->channel_mask = mChannelMask;
1543 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1544 AUDIO_PORT_CONFIG_FORMAT;
1545}
1546
Eric Laurent72e3f392015-05-20 14:43:50 -07001547void AudioFlinger::ThreadBase::systemReady()
1548{
1549 Mutex::Autolock _l(mLock);
1550 if (mSystemReady) {
1551 return;
1552 }
1553 mSystemReady = true;
1554
1555 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1556 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1557 }
1558 mPendingConfigEvents.clear();
1559}
1560
Eric Laurent83b88082014-06-20 18:31:16 -07001561
Eric Laurent81784c32012-11-19 14:55:58 -08001562// ----------------------------------------------------------------------------
1563// Playback
1564// ----------------------------------------------------------------------------
1565
1566AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1567 AudioStreamOut* output,
1568 audio_io_handle_t id,
1569 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001570 type_t type,
Eric Laurent51716182016-02-29 18:00:56 -08001571 bool systemReady,
1572 uint32_t bitRate)
Eric Laurent72e3f392015-05-20 14:43:50 -07001573 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001574 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001575 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001576 mMixerBuffer(NULL),
1577 mMixerBufferSize(0),
1578 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1579 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001580 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001581 mEffectBuffer(NULL),
1582 mEffectBufferSize(0),
1583 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1584 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001585 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001586 mFramesWritten(0),
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001587 mActiveTracksGeneration(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001588 // mStreamTypes[] initialized in constructor body
1589 mOutput(output),
1590 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1591 mMixerStatus(MIXER_IDLE),
1592 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001593 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001594 mBytesRemaining(0),
1595 mCurrentWriteLength(0),
1596 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001597 mWriteAckSequence(0),
1598 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001599 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001600 mScreenState(AudioFlinger::mScreenState),
1601 // index 0 is reserved for normal mixer's submix
Glenn Kastenbd096fd2013-08-23 13:53:56 -07001602 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001603 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001604{
Glenn Kastend7dca052015-03-05 16:05:54 -08001605 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1606 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001607
1608 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1609 // it would be safer to explicitly pass initial masterVolume/masterMute as
1610 // parameter.
1611 //
1612 // If the HAL we are using has support for master volume or master mute,
1613 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1614 // and the mute set to false).
1615 mMasterVolume = audioFlinger->masterVolume_l();
1616 mMasterMute = audioFlinger->masterMute_l();
1617 if (mOutput && mOutput->audioHwDev) {
1618 if (mOutput->audioHwDev->canSetMasterVolume()) {
1619 mMasterVolume = 1.0;
1620 }
1621
1622 if (mOutput->audioHwDev->canSetMasterMute()) {
1623 mMasterMute = false;
1624 }
1625 }
1626
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001627 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001628
Eric Laurent223fd5c2014-11-11 13:43:36 -08001629 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001630 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001631 stream = (audio_stream_type_t) (stream + 1)) {
1632 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1633 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1634 }
Eric Laurent51716182016-02-29 18:00:56 -08001635
1636 if (audio_has_proportional_frames(mFormat)) {
1637 mBufferDurationUs = (uint32_t)((mNormalFrameCount * 1000000LL) / mSampleRate);
1638 } else {
1639 bitRate = bitRate != 0 ? bitRate : kOffloadDefaultBitRateBps;
1640 mBufferDurationUs = (uint32_t)((mBufferSize * 8 * 1000000LL) / bitRate);
1641 }
Eric Laurent81784c32012-11-19 14:55:58 -08001642}
1643
1644AudioFlinger::PlaybackThread::~PlaybackThread()
1645{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001646 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001647 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001648 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001649 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001650}
1651
1652void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1653{
1654 dumpInternals(fd, args);
1655 dumpTracks(fd, args);
1656 dumpEffectChains(fd, args);
1657}
1658
Glenn Kasten0f11b512014-01-31 16:18:54 -08001659void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001660{
1661 const size_t SIZE = 256;
1662 char buffer[SIZE];
1663 String8 result;
1664
Marco Nelissenb2208842014-02-07 14:00:50 -08001665 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001666 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1667 const stream_type_t *st = &mStreamTypes[i];
1668 if (i > 0) {
1669 result.appendFormat(", ");
1670 }
1671 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1672 if (st->mute) {
1673 result.append("M");
1674 }
1675 }
1676 result.append("\n");
1677 write(fd, result.string(), result.length());
1678 result.clear();
1679
Eric Laurent81784c32012-11-19 14:55:58 -08001680 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1681 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001682 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001683 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001684
1685 size_t numtracks = mTracks.size();
1686 size_t numactive = mActiveTracks.size();
Elliott Hughes87cebad2014-05-22 10:14:43 -07001687 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001688 size_t numactiveseen = 0;
1689 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001690 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001691 Track::appendDumpHeader(result);
1692 for (size_t i = 0; i < numtracks; ++i) {
1693 sp<Track> track = mTracks[i];
1694 if (track != 0) {
1695 bool active = mActiveTracks.indexOf(track) >= 0;
1696 if (active) {
1697 numactiveseen++;
1698 }
1699 track->dump(buffer, SIZE, active);
1700 result.append(buffer);
1701 }
1702 }
1703 } else {
1704 result.append("\n");
1705 }
1706 if (numactiveseen != numactive) {
1707 // some tracks in the active list were not in the tracks list
1708 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1709 " not in the track list\n");
1710 result.append(buffer);
1711 Track::appendDumpHeader(result);
1712 for (size_t i = 0; i < numactive; ++i) {
1713 sp<Track> track = mActiveTracks[i].promote();
1714 if (track != 0 && mTracks.indexOf(track) < 0) {
1715 track->dump(buffer, SIZE, true);
1716 result.append(buffer);
1717 }
1718 }
1719 }
1720
1721 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001722}
1723
1724void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1725{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001726 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001727
1728 dumpBase(fd, args);
1729
Elliott Hughes87cebad2014-05-22 10:14:43 -07001730 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
1731 dprintf(fd, " Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1732 dprintf(fd, " Total writes: %d\n", mNumWrites);
1733 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1734 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1735 dprintf(fd, " Suspend count: %d\n", mSuspended);
1736 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1737 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1738 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1739 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001740 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001741 AudioStreamOut *output = mOutput;
1742 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
1743 String8 flagsAsString = outputFlagsToString(flags);
1744 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n", output, flags, flagsAsString.string());
Eric Laurent81784c32012-11-19 14:55:58 -08001745}
1746
1747// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001748
1749void AudioFlinger::PlaybackThread::onFirstRef()
1750{
Glenn Kastend7dca052015-03-05 16:05:54 -08001751 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001752}
1753
1754// ThreadBase virtuals
1755void AudioFlinger::PlaybackThread::preExit()
1756{
1757 ALOGV(" preExit()");
1758 // FIXME this is using hard-coded strings but in the future, this functionality will be
1759 // converted to use audio HAL extensions required to support tunneling
1760 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1761}
1762
1763// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1764sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1765 const sp<AudioFlinger::Client>& client,
1766 audio_stream_type_t streamType,
1767 uint32_t sampleRate,
1768 audio_format_t format,
1769 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001770 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001771 const sp<IMemory>& sharedBuffer,
1772 int sessionId,
1773 IAudioFlinger::track_flags_t *flags,
1774 pid_t tid,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001775 int uid,
Eric Laurent81784c32012-11-19 14:55:58 -08001776 status_t *status)
1777{
Glenn Kasten74935e42013-12-19 08:56:45 -08001778 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001779 sp<Track> track;
1780 status_t lStatus;
1781
Eric Laurent81784c32012-11-19 14:55:58 -08001782 // client expresses a preference for FAST, but we get the final say
1783 if (*flags & IAudioFlinger::TRACK_FAST) {
1784 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001785 // either of these use cases:
1786 (
1787 // use case 1: shared buffer with any frame count
1788 (
1789 (sharedBuffer != 0)
1790 ) ||
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001791 // use case 2: frame count is default or at least as large as HAL
Eric Laurent81784c32012-11-19 14:55:58 -08001792 (
Glenn Kasten1dfe2f92015-03-09 12:03:14 -07001793 // we formerly checked for a callback handler (non-0 tid),
1794 // but that is no longer required for TRANSFER_OBTAIN mode
Eric Laurent81784c32012-11-19 14:55:58 -08001795 ((frameCount == 0) ||
Glenn Kastenb5fed682013-12-03 09:06:43 -08001796 (frameCount >= mFrameCount))
Eric Laurent81784c32012-11-19 14:55:58 -08001797 )
1798 ) &&
1799 // PCM data
1800 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001801 // TODO: extract as a data library function that checks that a computationally
1802 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001803 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001804 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1805 (channelMask == AUDIO_CHANNEL_OUT_MONO
1806 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001807 // hardware sample rate
1808 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001809 // normal mixer has an associated fast mixer
1810 hasFastMixer() &&
1811 // there are sufficient fast track slots available
1812 (mFastTrackAvailMask != 0)
1813 // FIXME test that MixerThread for this fast track has a capable output HAL
1814 // FIXME add a permission test also?
1815 ) {
1816 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1817 if (frameCount == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001818 // read the fast track multiplier property the first time it is needed
1819 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1820 if (ok != 0) {
1821 ALOGE("%s pthread_once failed: %d", __func__, ok);
1822 }
1823 frameCount = mFrameCount * sFastTrackMultiplier;
Eric Laurent81784c32012-11-19 14:55:58 -08001824 }
1825 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1826 frameCount, mFrameCount);
1827 } else {
Glenn Kastend79072e2016-01-06 08:41:20 -08001828 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%d "
Andy Hung6146c082014-03-18 11:56:15 -07001829 "mFrameCount=%d format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
1830 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001831 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001832 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001833 audio_is_linear_pcm(format),
1834 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
1835 *flags &= ~IAudioFlinger::TRACK_FAST;
Andy Hung0e48d252015-01-26 11:43:15 -08001836 }
1837 }
1838 // For normal PCM streaming tracks, update minimum frame count.
1839 // For compatibility with AudioTrack calculation, buffer depth is forced
1840 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1841 // This is probably too conservative, but legacy application code may depend on it.
1842 // If you change this calculation, also review the start threshold which is related.
1843 if (!(*flags & IAudioFlinger::TRACK_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001844 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001845 // this must match AudioTrack.cpp calculateMinFrameCount().
1846 // TODO: Move to a common library
Eric Laurent81784c32012-11-19 14:55:58 -08001847 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1848 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1849 if (minBufCount < 2) {
1850 minBufCount = 2;
1851 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001852 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1853 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001854 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001855 minBufCount * sourceFramesNeededWithTimestretch(
1856 sampleRate, mNormalFrameCount,
1857 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001858 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001859 frameCount = minFrameCount;
1860 }
Eric Laurent81784c32012-11-19 14:55:58 -08001861 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001862 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001863
Glenn Kastenc3df8382014-03-13 15:05:25 -07001864 switch (mType) {
1865
1866 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001867 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001868 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001869 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1870 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001871 sampleRate, format, channelMask, mOutput, mFormat);
1872 lStatus = BAD_VALUE;
1873 goto Exit;
1874 }
1875 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001876 break;
1877
1878 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001879 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001880 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1881 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001882 sampleRate, format, channelMask, mOutput, mFormat);
1883 lStatus = BAD_VALUE;
1884 goto Exit;
1885 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001886 break;
1887
1888 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001889 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001890 ALOGE("createTrack_l() Bad parameter: format %#x \""
1891 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001892 format, mOutput, mFormat);
1893 lStatus = BAD_VALUE;
1894 goto Exit;
1895 }
Andy Hungcd044842014-08-07 11:04:34 -07001896 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001897 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1898 lStatus = BAD_VALUE;
1899 goto Exit;
1900 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001901 break;
1902
Eric Laurent81784c32012-11-19 14:55:58 -08001903 }
1904
1905 lStatus = initCheck();
1906 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001907 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001908 goto Exit;
1909 }
1910
1911 { // scope for mLock
1912 Mutex::Autolock _l(mLock);
1913
1914 // all tracks in same audio session must share the same routing strategy otherwise
1915 // conflicts will happen when tracks are moved from one output to another by audio policy
1916 // manager
1917 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1918 for (size_t i = 0; i < mTracks.size(); ++i) {
1919 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001920 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001921 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1922 if (sessionId == t->sessionId() && strategy != actual) {
1923 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1924 strategy, actual);
1925 lStatus = BAD_VALUE;
1926 goto Exit;
1927 }
1928 }
1929 }
1930
Glenn Kastend79072e2016-01-06 08:41:20 -08001931 track = new Track(this, client, streamType, sampleRate, format,
1932 channelMask, frameCount, NULL, sharedBuffer,
1933 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT);
Glenn Kasten03003332013-08-06 15:40:54 -07001934
Glenn Kasten03003332013-08-06 15:40:54 -07001935 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1936 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001937 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001938 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001939 goto Exit;
1940 }
1941 mTracks.add(track);
1942
1943 sp<EffectChain> chain = getEffectChain_l(sessionId);
1944 if (chain != 0) {
1945 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1946 track->setMainBuffer(chain->inBuffer());
1947 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1948 chain->incTrackCnt();
1949 }
1950
1951 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1952 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1953 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1954 // so ask activity manager to do this on our behalf
1955 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
1956 }
1957 }
1958
1959 lStatus = NO_ERROR;
1960
1961Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001962 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001963 return track;
1964}
1965
1966uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
1967{
1968 return latency;
1969}
1970
1971uint32_t AudioFlinger::PlaybackThread::latency() const
1972{
1973 Mutex::Autolock _l(mLock);
1974 return latency_l();
1975}
1976uint32_t AudioFlinger::PlaybackThread::latency_l() const
1977{
1978 if (initCheck() == NO_ERROR) {
1979 return correctLatency_l(mOutput->stream->get_latency(mOutput->stream));
1980 } else {
1981 return 0;
1982 }
1983}
1984
1985void AudioFlinger::PlaybackThread::setMasterVolume(float value)
1986{
1987 Mutex::Autolock _l(mLock);
1988 // Don't apply master volume in SW if our HAL can do it for us.
1989 if (mOutput && mOutput->audioHwDev &&
1990 mOutput->audioHwDev->canSetMasterVolume()) {
1991 mMasterVolume = 1.0;
1992 } else {
1993 mMasterVolume = value;
1994 }
1995}
1996
1997void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1998{
1999 Mutex::Autolock _l(mLock);
2000 // Don't apply master mute in SW if our HAL can do it for us.
2001 if (mOutput && mOutput->audioHwDev &&
2002 mOutput->audioHwDev->canSetMasterMute()) {
2003 mMasterMute = false;
2004 } else {
2005 mMasterMute = muted;
2006 }
2007}
2008
2009void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2010{
2011 Mutex::Autolock _l(mLock);
2012 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002013 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002014}
2015
2016void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2017{
2018 Mutex::Autolock _l(mLock);
2019 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002020 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002021}
2022
2023float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2024{
2025 Mutex::Autolock _l(mLock);
2026 return mStreamTypes[stream].volume;
2027}
2028
2029// addTrack_l() must be called with ThreadBase::mLock held
2030status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2031{
2032 status_t status = ALREADY_EXISTS;
2033
Eric Laurent81784c32012-11-19 14:55:58 -08002034 if (mActiveTracks.indexOf(track) < 0) {
2035 // the track is newly added, make sure it fills up all its
2036 // buffers before playing. This is to ensure the client will
2037 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002038 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002039 TrackBase::track_state state = track->mState;
2040 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002041 status = AudioSystem::startOutput(mId, track->streamType(),
2042 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 mLock.lock();
2044 // abort track was stopped/paused while we released the lock
2045 if (state != track->mState) {
2046 if (status == NO_ERROR) {
2047 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002048 AudioSystem::stopOutput(mId, track->streamType(),
2049 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002050 mLock.lock();
2051 }
2052 return INVALID_OPERATION;
2053 }
2054 // abort if start is rejected by audio policy manager
2055 if (status != NO_ERROR) {
2056 return PERMISSION_DENIED;
2057 }
2058#ifdef ADD_BATTERY_DATA
2059 // to track the speaker usage
2060 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2061#endif
2062 }
2063
Eric Laurent51716182016-02-29 18:00:56 -08002064 // set retry count for buffer fill
2065 if (track->isOffloaded()) {
2066 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2067 } else {
2068 track->mRetryCount = kMaxTrackStartupRetries;
2069 }
2070
Glenn Kasten9f80dd22012-12-18 15:57:32 -08002071 track->mFillingUpStatus = track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent81784c32012-11-19 14:55:58 -08002072 track->mResetDone = false;
2073 track->mPresentationCompleteFrames = 0;
2074 mActiveTracks.add(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002075 mWakeLockUids.add(track->uid());
2076 mActiveTracksGeneration++;
Eric Laurentfd477972013-10-25 18:10:40 -07002077 mLatestActiveTrack = track;
Eric Laurentd0107bc2013-06-11 14:38:48 -07002078 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2079 if (chain != 0) {
2080 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2081 track->sessionId());
2082 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002083 }
2084
2085 status = NO_ERROR;
2086 }
2087
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002088 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002089 return status;
2090}
2091
Eric Laurentbfb1b832013-01-07 09:53:42 -08002092bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002093{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002094 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002095 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002096 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2097 track->mState = TrackBase::STOPPED;
2098 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002099 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002100 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002101 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002102 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002103
2104 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002105}
2106
2107void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2108{
2109 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
2110 mTracks.remove(track);
2111 deleteTrackName_l(track->name());
2112 // redundant as track is about to be destroyed, for dumpsys only
2113 track->mName = -1;
2114 if (track->isFastTrack()) {
2115 int index = track->mFastIndex;
2116 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
2117 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2118 mFastTrackAvailMask |= 1 << index;
2119 // redundant as track is about to be destroyed, for dumpsys only
2120 track->mFastIndex = -1;
2121 }
2122 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2123 if (chain != 0) {
2124 chain->decTrackCnt();
2125 }
2126}
2127
Eric Laurentede6c3b2013-09-19 14:37:46 -07002128void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002129{
2130 // Thread could be blocked waiting for async
2131 // so signal it to handle state changes immediately
2132 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2133 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2134 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002135 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002136}
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2139{
Eric Laurent81784c32012-11-19 14:55:58 -08002140 Mutex::Autolock _l(mLock);
2141 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07002142 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002143 }
2144
Glenn Kastend8ea6992013-07-16 14:17:15 -07002145 char *s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
2146 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08002147 free(s);
2148 return out_s8;
2149}
2150
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002151void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002152 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2153 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002154
Eric Laurent73e26b62015-04-27 16:55:58 -07002155 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002156
2157 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002158 case AUDIO_OUTPUT_OPENED:
2159 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002160 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002161 desc->mChannelMask = mChannelMask;
2162 desc->mSamplingRate = mSampleRate;
2163 desc->mFormat = mFormat;
2164 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002165 // AudioFlinger::frameCount(audio_io_handle_t)
Eric Laurent73e26b62015-04-27 16:55:58 -07002166 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002167 break;
2168
Eric Laurent73e26b62015-04-27 16:55:58 -07002169 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002170 default:
2171 break;
2172 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002173 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002174}
2175
Eric Laurentbfb1b832013-01-07 09:53:42 -08002176void AudioFlinger::PlaybackThread::writeCallback()
2177{
2178 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002179 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002180}
2181
2182void AudioFlinger::PlaybackThread::drainCallback()
2183{
2184 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002185 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186}
2187
Eric Laurent3b4529e2013-09-05 18:09:19 -07002188void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189{
2190 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002191 // reject out of sequence requests
2192 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2193 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002194 mWaitWorkCV.signal();
2195 }
2196}
2197
Eric Laurent3b4529e2013-09-05 18:09:19 -07002198void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002199{
2200 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002201 // reject out of sequence requests
2202 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2203 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 mWaitWorkCV.signal();
2205 }
2206}
2207
2208// static
2209int AudioFlinger::PlaybackThread::asyncCallback(stream_callback_event_t event,
Glenn Kasten0f11b512014-01-31 16:18:54 -08002210 void *param __unused,
Eric Laurentbfb1b832013-01-07 09:53:42 -08002211 void *cookie)
2212{
2213 AudioFlinger::PlaybackThread *me = (AudioFlinger::PlaybackThread *)cookie;
2214 ALOGV("asyncCallback() event %d", event);
2215 switch (event) {
2216 case STREAM_CBK_EVENT_WRITE_READY:
2217 me->writeCallback();
2218 break;
2219 case STREAM_CBK_EVENT_DRAIN_READY:
2220 me->drainCallback();
2221 break;
2222 default:
2223 ALOGW("asyncCallback() unknown event %d", event);
2224 break;
2225 }
2226 return 0;
2227}
2228
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002229void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002230{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002231 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002232 mSampleRate = mOutput->getSampleRate();
2233 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002234 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002235 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002236 }
Andy Hung9a592762014-07-21 21:56:01 -07002237 if ((mType == MIXER || mType == DUPLICATING)
2238 && !isValidPcmSinkChannelMask(mChannelMask)) {
2239 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2240 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002241 }
Andy Hunge5412692014-05-16 11:25:07 -07002242 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002243
2244 // Get actual HAL format.
Andy Hung463be252014-07-10 16:56:07 -07002245 mHALFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Phil Burkca5e6142015-07-14 09:42:29 -07002246 // Get format from the shim, which will be different than the HAL format
2247 // if playing compressed audio over HDMI passthrough.
2248 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002249 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002250 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002251 }
Andy Hung6146c082014-03-18 11:56:15 -07002252 if ((mType == MIXER || mType == DUPLICATING)
2253 && !isValidPcmSinkFormat(mFormat)) {
2254 LOG_FATAL("HAL format %#x not supported for mixed output",
2255 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002256 }
Phil Burk062e67a2015-02-11 13:40:50 -08002257 mFrameSize = mOutput->getFrameSize();
Glenn Kasten70949c42013-08-06 07:40:12 -07002258 mBufferSize = mOutput->stream->common.get_buffer_size(&mOutput->stream->common);
2259 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002260 if (mFrameCount & 15) {
2261 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2262 mFrameCount);
2263 }
2264
Eric Laurentbfb1b832013-01-07 09:53:42 -08002265 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) &&
2266 (mOutput->stream->set_callback != NULL)) {
2267 if (mOutput->stream->set_callback(mOutput->stream,
2268 AudioFlinger::PlaybackThread::asyncCallback, this) == 0) {
2269 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002270 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002271 }
2272 }
2273
Eric Laurentd1f69b02014-12-15 14:33:13 -08002274 mHwSupportsPause = false;
2275 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
2276 if (mOutput->stream->pause != NULL) {
2277 if (mOutput->stream->resume != NULL) {
2278 mHwSupportsPause = true;
2279 } else {
2280 ALOGW("direct output implements pause but not resume");
2281 }
2282 } else if (mOutput->stream->resume != NULL) {
2283 ALOGW("direct output implements resume but not pause");
2284 }
2285 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002286 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2287 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2288 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002289
Andy Hungfbfc3952015-01-15 13:33:51 -08002290 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2291 // For best precision, we use float instead of the associated output
2292 // device format (typically PCM 16 bit).
2293
2294 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2295 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2296 mBufferSize = mFrameSize * mFrameCount;
2297
2298 // TODO: We currently use the associated output device channel mask and sample rate.
2299 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2300 // (if a valid mask) to avoid premature downmix.
2301 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2302 // instead of the output device sample rate to avoid loss of high frequency information.
2303 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2304 }
2305
Andy Hung09a50072014-02-27 14:30:47 -08002306 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002307 double multiplier = 1.0;
2308 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2309 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002310 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2311 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Eric Laurent81784c32012-11-19 14:55:58 -08002312 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2313 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2314 maxNormalFrameCount = maxNormalFrameCount & ~15;
2315 if (maxNormalFrameCount < minNormalFrameCount) {
2316 maxNormalFrameCount = minNormalFrameCount;
2317 }
2318 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2319 if (multiplier <= 1.0) {
2320 multiplier = 1.0;
2321 } else if (multiplier <= 2.0) {
2322 if (2 * mFrameCount <= maxNormalFrameCount) {
2323 multiplier = 2.0;
2324 } else {
2325 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2326 }
2327 } else {
2328 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
Andy Hung09a50072014-02-27 14:30:47 -08002329 // 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 -08002330 // track, but we sometimes have to do this to satisfy the maximum frame count
2331 // constraint)
2332 // FIXME this rounding up should not be done if no HAL SRC
2333 uint32_t truncMult = (uint32_t) multiplier;
2334 if ((truncMult & 1)) {
2335 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2336 ++truncMult;
2337 }
2338 }
2339 multiplier = (double) truncMult;
2340 }
2341 }
2342 mNormalFrameCount = multiplier * mFrameCount;
2343 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002344 if (mType == MIXER || mType == DUPLICATING) {
2345 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2346 }
Andy Hung09a50072014-02-27 14:30:47 -08002347 ALOGI("HAL output buffer size %u frames, normal sink buffer size %u frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002348 mNormalFrameCount);
2349
Andy Hung08fb1742015-05-31 23:22:10 -07002350 // Check if we want to throttle the processing to no more than 2x normal rate
2351 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002352 mThreadThrottleTimeMs = 0;
2353 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002354 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2355
Andy Hung010a1a12014-03-13 13:57:33 -07002356 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2357 // Originally this was int16_t[] array, need to remove legacy implications.
2358 free(mSinkBuffer);
2359 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002360 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2361 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2362 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002363 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002364
Andy Hung69aed5f2014-02-25 17:24:40 -08002365 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2366 // drives the output.
2367 free(mMixerBuffer);
2368 mMixerBuffer = NULL;
2369 if (mMixerBufferEnabled) {
2370 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2371 mMixerBufferSize = mNormalFrameCount * mChannelCount
2372 * audio_bytes_per_sample(mMixerBufferFormat);
2373 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2374 }
Andy Hung98ef9782014-03-04 14:46:50 -08002375 free(mEffectBuffer);
2376 mEffectBuffer = NULL;
2377 if (mEffectBufferEnabled) {
2378 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2379 mEffectBufferSize = mNormalFrameCount * mChannelCount
2380 * audio_bytes_per_sample(mEffectBufferFormat);
2381 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2382 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002383
Eric Laurent81784c32012-11-19 14:55:58 -08002384 // force reconfiguration of effect chains and engines to take new buffer size and audio
2385 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002386 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002387 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2388 // matter.
2389 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2390 Vector< sp<EffectChain> > effectChains = mEffectChains;
2391 for (size_t i = 0; i < effectChains.size(); i ++) {
2392 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2393 }
2394}
2395
2396
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002397status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002398{
2399 if (halFrames == NULL || dspFrames == NULL) {
2400 return BAD_VALUE;
2401 }
2402 Mutex::Autolock _l(mLock);
2403 if (initCheck() != NO_ERROR) {
2404 return INVALID_OPERATION;
2405 }
Andy Hung818e7a32016-02-16 18:08:07 -08002406 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002407 *halFrames = framesWritten;
2408
2409 if (isSuspended()) {
2410 // return an estimation of rendered frames when the output is suspended
2411 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002412 *dspFrames = (uint32_t)
2413 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002414 return NO_ERROR;
2415 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002416 status_t status;
2417 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002418 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002419 *dspFrames = (size_t)frames;
2420 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002421 }
2422}
2423
2424uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
2425{
2426 Mutex::Autolock _l(mLock);
2427 uint32_t result = 0;
2428 if (getEffectChain_l(sessionId) != 0) {
2429 result = EFFECT_SESSION;
2430 }
2431
2432 for (size_t i = 0; i < mTracks.size(); ++i) {
2433 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002434 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002435 result |= TRACK_SESSION;
2436 break;
2437 }
2438 }
2439
2440 return result;
2441}
2442
2443uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2444{
2445 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2446 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2447 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2448 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2449 }
2450 for (size_t i = 0; i < mTracks.size(); i++) {
2451 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002452 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002453 return AudioSystem::getStrategyForStream(track->streamType());
2454 }
2455 }
2456 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2457}
2458
2459
Phil Burk062e67a2015-02-11 13:40:50 -08002460AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002461{
2462 Mutex::Autolock _l(mLock);
2463 return mOutput;
2464}
2465
Phil Burk062e67a2015-02-11 13:40:50 -08002466AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002467{
2468 Mutex::Autolock _l(mLock);
2469 AudioStreamOut *output = mOutput;
2470 mOutput = NULL;
2471 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2472 // must push a NULL and wait for ack
2473 mOutputSink.clear();
2474 mPipeSink.clear();
2475 mNormalSink.clear();
2476 return output;
2477}
2478
2479// this method must always be called either with ThreadBase mLock held or inside the thread loop
2480audio_stream_t* AudioFlinger::PlaybackThread::stream() const
2481{
2482 if (mOutput == NULL) {
2483 return NULL;
2484 }
2485 return &mOutput->stream->common;
2486}
2487
2488uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2489{
2490 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2491}
2492
2493status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2494{
2495 if (!isValidSyncEvent(event)) {
2496 return BAD_VALUE;
2497 }
2498
2499 Mutex::Autolock _l(mLock);
2500
2501 for (size_t i = 0; i < mTracks.size(); ++i) {
2502 sp<Track> track = mTracks[i];
2503 if (event->triggerSession() == track->sessionId()) {
2504 (void) track->setSyncEvent(event);
2505 return NO_ERROR;
2506 }
2507 }
2508
2509 return NAME_NOT_FOUND;
2510}
2511
2512bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2513{
2514 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2515}
2516
2517void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2518 const Vector< sp<Track> >& tracksToRemove)
2519{
2520 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002521 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002522 for (size_t i = 0 ; i < count ; i++) {
2523 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002524 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002525 AudioSystem::stopOutput(mId, track->streamType(),
2526 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002527#ifdef ADD_BATTERY_DATA
2528 // to track the speaker usage
2529 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2530#endif
2531 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002532 AudioSystem::releaseOutput(mId, track->streamType(),
2533 (audio_session_t)track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002534 }
Eric Laurent81784c32012-11-19 14:55:58 -08002535 }
2536 }
2537 }
Eric Laurent81784c32012-11-19 14:55:58 -08002538}
2539
2540void AudioFlinger::PlaybackThread::checkSilentMode_l()
2541{
2542 if (!mMasterMute) {
2543 char value[PROPERTY_VALUE_MAX];
2544 if (property_get("ro.audio.silent", value, "0") > 0) {
2545 char *endptr;
2546 unsigned long ul = strtoul(value, &endptr, 0);
2547 if (*endptr == '\0' && ul != 0) {
2548 ALOGD("Silence is golden");
2549 // The setprop command will not allow a property to be changed after
2550 // the first time it is set, so we don't have to worry about un-muting.
2551 setMasterMute_l(true);
2552 }
2553 }
2554 }
2555}
2556
2557// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002558ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002559{
2560 // FIXME rewrite to reduce number of system calls
2561 mLastWriteTime = systemTime();
2562 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002563 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002564 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002565
2566 // If an NBAIO sink is present, use it to write the normal mixer's submix
2567 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002568
Andy Hung010a1a12014-03-13 13:57:33 -07002569 const size_t count = mBytesRemaining / mFrameSize;
2570
Simon Wilson2d590962012-11-29 15:18:50 -08002571 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002572 // update the setpoint when AudioFlinger::mScreenState changes
2573 uint32_t screenState = AudioFlinger::mScreenState;
2574 if (screenState != mScreenState) {
2575 mScreenState = screenState;
2576 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2577 if (pipe != NULL) {
2578 pipe->setAvgFrames((mScreenState & 1) ?
2579 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2580 }
2581 }
Andy Hung010a1a12014-03-13 13:57:33 -07002582 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002583 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002584 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002585 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002586 } else {
2587 bytesWritten = framesWritten;
2588 }
2589 // otherwise use the HAL / AudioStreamOut directly
2590 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002591 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002592
Eric Laurentbfb1b832013-01-07 09:53:42 -08002593 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002594 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2595 mWriteAckSequence += 2;
2596 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002598 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002600 // FIXME We should have an implementation of timestamps for direct output threads.
2601 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002602 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002603
Eric Laurentbfb1b832013-01-07 09:53:42 -08002604 if (mUseAsyncWrite &&
2605 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2606 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002607 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002609 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002610 }
Eric Laurent81784c32012-11-19 14:55:58 -08002611 }
2612
Eric Laurent81784c32012-11-19 14:55:58 -08002613 mNumWrites++;
2614 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002615 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002616 return bytesWritten;
2617}
2618
2619void AudioFlinger::PlaybackThread::threadLoop_drain()
2620{
2621 if (mOutput->stream->drain) {
2622 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2623 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002624 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2625 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002626 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002627 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002628 }
2629 mOutput->stream->drain(mOutput->stream,
2630 (mMixerStatus == MIXER_DRAIN_TRACK) ? AUDIO_DRAIN_EARLY_NOTIFY
2631 : AUDIO_DRAIN_ALL);
2632 }
2633}
2634
2635void AudioFlinger::PlaybackThread::threadLoop_exit()
2636{
Eric Laurent275e8e92014-11-30 15:14:47 -08002637 {
2638 Mutex::Autolock _l(mLock);
2639 for (size_t i = 0; i < mTracks.size(); i++) {
2640 sp<Track> track = mTracks[i];
2641 track->invalidate();
2642 }
2643 }
Eric Laurent81784c32012-11-19 14:55:58 -08002644}
2645
2646/*
2647The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002648 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002649 - mActiveSleepTimeUs from activeSleepTimeUs()
2650 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002651 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2652 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002653 - maxPeriod from frame count and sample rate (MIXER only)
2654
2655The parameters that affect these derived values are:
2656 - frame count
2657 - frame size
2658 - sample rate
2659 - device type: A2DP or not
2660 - device latency
2661 - format: PCM or not
2662 - active sleep time
2663 - idle sleep time
2664*/
2665
2666void AudioFlinger::PlaybackThread::cacheParameters_l()
2667{
Andy Hung25c2dac2014-02-27 14:56:00 -08002668 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002669 mActiveSleepTimeUs = activeSleepTimeUs();
2670 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002671
2672 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2673 // truncating audio when going to standby.
2674 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2675 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2676 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2677 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2678 }
2679 }
Eric Laurent81784c32012-11-19 14:55:58 -08002680}
2681
2682void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2683{
Glenn Kasten7c027242012-12-26 14:43:16 -08002684 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurent81784c32012-11-19 14:55:58 -08002685 this, streamType, mTracks.size());
2686 Mutex::Autolock _l(mLock);
2687
2688 size_t size = mTracks.size();
2689 for (size_t i = 0; i < size; i++) {
2690 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002691 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002692 t->invalidate();
Eric Laurent81784c32012-11-19 14:55:58 -08002693 }
2694 }
2695}
2696
2697status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2698{
2699 int session = chain->sessionId();
Andy Hung010a1a12014-03-13 13:57:33 -07002700 int16_t* buffer = reinterpret_cast<int16_t*>(mEffectBufferEnabled
2701 ? mEffectBuffer : mSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002702 bool ownsBuffer = false;
2703
2704 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
2705 if (session > 0) {
2706 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002707 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002708 if (mType != DIRECT) {
2709 size_t numSamples = mNormalFrameCount * mChannelCount;
2710 buffer = new int16_t[numSamples];
2711 memset(buffer, 0, numSamples * sizeof(int16_t));
2712 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
2713 ownsBuffer = true;
2714 }
2715
2716 // Attach all tracks with same session ID to this chain.
2717 for (size_t i = 0; i < mTracks.size(); ++i) {
2718 sp<Track> track = mTracks[i];
2719 if (session == track->sessionId()) {
2720 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2721 buffer);
2722 track->setMainBuffer(buffer);
2723 chain->incTrackCnt();
2724 }
2725 }
2726
2727 // indicate all active tracks in the chain
2728 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2729 sp<Track> track = mActiveTracks[i].promote();
2730 if (track == 0) {
2731 continue;
2732 }
2733 if (session == track->sessionId()) {
2734 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2735 chain->incActiveTrackCnt();
2736 }
2737 }
2738 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002739 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08002740 chain->setInBuffer(buffer, ownsBuffer);
Andy Hung010a1a12014-03-13 13:57:33 -07002741 chain->setOutBuffer(reinterpret_cast<int16_t*>(mEffectBufferEnabled
2742 ? mEffectBuffer : mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002743 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
2744 // chains list in order to be processed last as it contains output stage effects
2745 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2746 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
2747 // after track specific effects and before output stage
2748 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
2749 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
2750 // Effect chain for other sessions are inserted at beginning of effect
2751 // chains list to be processed before output mix effects. Relative order between other
2752 // sessions is not important
2753 size_t size = mEffectChains.size();
2754 size_t i = 0;
2755 for (i = 0; i < size; i++) {
2756 if (mEffectChains[i]->sessionId() < session) {
2757 break;
2758 }
2759 }
2760 mEffectChains.insertAt(chain, i);
2761 checkSuspendOnAddEffectChain_l(chain);
2762
2763 return NO_ERROR;
2764}
2765
2766size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2767{
2768 int session = chain->sessionId();
2769
2770 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2771
2772 for (size_t i = 0; i < mEffectChains.size(); i++) {
2773 if (chain == mEffectChains[i]) {
2774 mEffectChains.removeAt(i);
2775 // detach all active tracks from the chain
2776 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
2777 sp<Track> track = mActiveTracks[i].promote();
2778 if (track == 0) {
2779 continue;
2780 }
2781 if (session == track->sessionId()) {
2782 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2783 chain.get(), session);
2784 chain->decActiveTrackCnt();
2785 }
2786 }
2787
2788 // detach all tracks with same session ID from this chain
2789 for (size_t i = 0; i < mTracks.size(); ++i) {
2790 sp<Track> track = mTracks[i];
2791 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002792 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002793 chain->decTrackCnt();
2794 }
2795 }
2796 break;
2797 }
2798 }
2799 return mEffectChains.size();
2800}
2801
2802status_t AudioFlinger::PlaybackThread::attachAuxEffect(
2803 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2804{
2805 Mutex::Autolock _l(mLock);
2806 return attachAuxEffect_l(track, EffectId);
2807}
2808
2809status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
2810 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
2811{
2812 status_t status = NO_ERROR;
2813
2814 if (EffectId == 0) {
2815 track->setAuxBuffer(0, NULL);
2816 } else {
2817 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2818 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2819 if (effect != 0) {
2820 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2821 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2822 } else {
2823 status = INVALID_OPERATION;
2824 }
2825 } else {
2826 status = BAD_VALUE;
2827 }
2828 }
2829 return status;
2830}
2831
2832void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2833{
2834 for (size_t i = 0; i < mTracks.size(); ++i) {
2835 sp<Track> track = mTracks[i];
2836 if (track->auxEffectId() == effectId) {
2837 attachAuxEffect_l(track, 0);
2838 }
2839 }
2840}
2841
2842bool AudioFlinger::PlaybackThread::threadLoop()
2843{
2844 Vector< sp<Track> > tracksToRemove;
2845
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002846 mStandbyTimeNs = systemTime();
Eric Laurent81784c32012-11-19 14:55:58 -08002847
2848 // MIXER
2849 nsecs_t lastWarning = 0;
2850
2851 // DUPLICATING
2852 // FIXME could this be made local to while loop?
2853 writeFrames = 0;
2854
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002855 int lastGeneration = 0;
2856
Eric Laurent81784c32012-11-19 14:55:58 -08002857 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002858 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002859
2860 if (mType == MIXER) {
2861 sleepTimeShift = 0;
2862 }
2863
2864 CpuStats cpuStats;
2865 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2866
2867 acquireWakeLock();
2868
Glenn Kasten9e58b552013-01-18 15:09:48 -08002869 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2870 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2871 // and then that string will be logged at the next convenient opportunity.
2872 const char *logString = NULL;
2873
Eric Laurent664539d2013-09-23 18:24:31 -07002874 checkSilentMode_l();
2875
Eric Laurent81784c32012-11-19 14:55:58 -08002876 while (!exitPending())
2877 {
2878 cpuStats.sample(myName);
2879
2880 Vector< sp<EffectChain> > effectChains;
2881
Eric Laurent81784c32012-11-19 14:55:58 -08002882 { // scope for mLock
2883
2884 Mutex::Autolock _l(mLock);
2885
Eric Laurent021cf962014-05-13 10:18:14 -07002886 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002887
Glenn Kasten9e58b552013-01-18 15:09:48 -08002888 if (logString != NULL) {
2889 mNBLogWriter->logTimestamp();
2890 mNBLogWriter->log(logString);
2891 logString = NULL;
2892 }
2893
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002894 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002895 // and associate with the sink frames written out. We need
2896 // this to convert the sink timestamp to the track timestamp.
2897 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002898 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002899 // We always fetch the timestamp here because often the downstream
2900 // sink will block whie writing.
2901 ExtendedTimestamp timestamp; // use private copy to fetch
2902 (void) mNormalSink->getTimestamp(timestamp);
2903 // copy over kernel info
2904 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
2905 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2906 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2907 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002908 }
2909 // mFramesWritten for non-offloaded tracks are contiguous
2910 // even after standby() is called. This is useful for the track frame
2911 // to sink frame mapping.
2912 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
2913 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
2914 const size_t size = mActiveTracks.size();
2915 for (size_t i = 0; i < size; ++i) {
2916 sp<Track> t = mActiveTracks[i].promote();
2917 if (t != 0 && !t->isFastTrack()) {
2918 t->updateTrackFrameInfo(
2919 t->mAudioTrackServerProxy->framesReleased(),
2920 mFramesWritten,
2921 mTimestamp);
Andy Hunge10393e2015-06-12 13:59:33 -07002922 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07002923 }
2924
Eric Laurent81784c32012-11-19 14:55:58 -08002925 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 if (mSignalPending) {
2927 // A signal was raised while we were unlocked
2928 mSignalPending = false;
2929 } else if (waitingAsyncCallback_l()) {
2930 if (exitPending()) {
2931 break;
2932 }
Marco Nelissen078538c2015-05-12 09:17:57 -07002933 bool released = false;
2934 // The following works around a bug in the offload driver. Ideally we would release
2935 // the wake lock every time, but that causes the last offload buffer(s) to be
2936 // dropped while the device is on battery, so we need to hold a wake lock during
2937 // the drain phase.
2938 if (mBytesRemaining && !(mDrainSequence & 1)) {
2939 releaseWakeLock_l();
2940 released = true;
2941 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002942 mWakeLockUids.clear();
2943 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002944 ALOGV("wait async completion");
2945 mWaitWorkCV.wait(mLock);
2946 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07002947 if (released) {
2948 acquireWakeLock_l();
2949 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002950 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2951 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002952
2953 continue;
2954 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002955 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 isSuspended()) {
2957 // put audio hardware into standby after short delay
2958 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002959
2960 threadLoop_standby();
2961
2962 mStandby = true;
2963 }
2964
2965 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2966 // we're about to wait, flush the binder command buffer
2967 IPCThreadState::self()->flushCommands();
2968
2969 clearOutputTracks();
2970
2971 if (exitPending()) {
2972 break;
2973 }
2974
2975 releaseWakeLock_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08002976 mWakeLockUids.clear();
2977 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08002978 // wait until we have something to do...
2979 ALOGV("%s going to sleep", myName.string());
2980 mWaitWorkCV.wait(mLock);
2981 ALOGV("%s waking up", myName.string());
2982 acquireWakeLock_l();
2983
2984 mMixerStatus = MIXER_IDLE;
2985 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
2986 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002987 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002988 checkSilentMode_l();
2989
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002990 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
2991 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002992 if (mType == MIXER) {
2993 sleepTimeShift = 0;
2994 }
2995
2996 continue;
2997 }
2998 }
Eric Laurent81784c32012-11-19 14:55:58 -08002999 // mMixerStatusIgnoringFastTracks is also updated internally
3000 mMixerStatus = prepareTracks_l(&tracksToRemove);
3001
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003002 // compare with previously applied list
3003 if (lastGeneration != mActiveTracksGeneration) {
3004 // update wakelock
3005 updateWakeLockUids_l(mWakeLockUids);
3006 lastGeneration = mActiveTracksGeneration;
3007 }
3008
Eric Laurent81784c32012-11-19 14:55:58 -08003009 // prevent any changes in effect chain list and in each effect chain
3010 // during mixing and effect process as the audio buffers could be deleted
3011 // or modified if an effect is created or deleted
3012 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003013 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003014
Eric Laurentbfb1b832013-01-07 09:53:42 -08003015 if (mBytesRemaining == 0) {
3016 mCurrentWriteLength = 0;
3017 if (mMixerStatus == MIXER_TRACKS_READY) {
3018 // threadLoop_mix() sets mCurrentWriteLength
3019 threadLoop_mix();
3020 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3021 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003022 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023 // must be written to HAL
3024 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003025 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003026 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003027 }
3028 }
Andy Hung98ef9782014-03-04 14:46:50 -08003029 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003030 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003031 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3032 // or mSinkBuffer (if there are no effects).
3033 //
3034 // This is done pre-effects computation; if effects change to
3035 // support higher precision, this needs to move.
3036 //
3037 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003038 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003039 if (mMixerBufferValid) {
3040 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3041 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3042
Andy Hung2ddee192015-12-18 17:34:44 -08003043 // mono blend occurs for mixer threads only (not direct or offloaded)
3044 // and is handled here if we're going directly to the sink.
3045 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003046 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3047 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003048 }
3049
Andy Hung98ef9782014-03-04 14:46:50 -08003050 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3051 mNormalFrameCount * mChannelCount);
3052 }
3053
Eric Laurentbfb1b832013-01-07 09:53:42 -08003054 mBytesRemaining = mCurrentWriteLength;
3055 if (isSuspended()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003056 mSleepTimeUs = suspendSleepTimeUs();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057 // simulate write to HAL when suspended
Andy Hung25c2dac2014-02-27 14:56:00 -08003058 mBytesWritten += mSinkBufferSize;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003059 mFramesWritten += mSinkBufferSize / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060 mBytesRemaining = 0;
3061 }
Eric Laurent81784c32012-11-19 14:55:58 -08003062
Eric Laurentbfb1b832013-01-07 09:53:42 -08003063 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003064 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003065 for (size_t i = 0; i < effectChains.size(); i ++) {
3066 effectChains[i]->process_l();
3067 }
Eric Laurent81784c32012-11-19 14:55:58 -08003068 }
3069 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003070 // Process effect chains for offloaded thread even if no audio
3071 // was read from audio track: process only updates effect state
3072 // and thus does have to be synchronized with audio writes but may have
3073 // to be called while waiting for async write callback
3074 if (mType == OFFLOAD) {
3075 for (size_t i = 0; i < effectChains.size(); i ++) {
3076 effectChains[i]->process_l();
3077 }
3078 }
Eric Laurent81784c32012-11-19 14:55:58 -08003079
Andy Hung98ef9782014-03-04 14:46:50 -08003080 // Only if the Effects buffer is enabled and there is data in the
3081 // Effects buffer (buffer valid), we need to
3082 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003083 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003084 if (mEffectBufferValid) {
3085 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003086
3087 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003088 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3089 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003090 }
3091
Andy Hung98ef9782014-03-04 14:46:50 -08003092 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3093 mNormalFrameCount * mChannelCount);
3094 }
3095
Eric Laurent81784c32012-11-19 14:55:58 -08003096 // enable changes in effect chain
3097 unlockEffectChains(effectChains);
3098
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003100 // mSleepTimeUs == 0 means we must write to audio hardware
3101 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003102 ssize_t ret = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003103 if (mBytesRemaining) {
Andy Hung08fb1742015-05-31 23:22:10 -07003104 ret = threadLoop_write();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 if (ret < 0) {
3106 mBytesRemaining = 0;
3107 } else {
3108 mBytesWritten += ret;
3109 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003110 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003111 }
3112 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3113 (mMixerStatus == MIXER_DRAIN_ALL)) {
3114 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003115 }
Andy Hung08fb1742015-05-31 23:22:10 -07003116 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003117 // write blocked detection
3118 nsecs_t now = systemTime();
3119 nsecs_t delta = now - mLastWriteTime;
Andy Hung08fb1742015-05-31 23:22:10 -07003120 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003121 mNumDelayedWrites++;
3122 if ((now - lastWarning) > kWarningThrottleNs) {
3123 ATRACE_NAME("underrun");
3124 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
3125 ns2ms(delta), mNumDelayedWrites, this);
3126 lastWarning = now;
3127 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003128 }
Andy Hung08fb1742015-05-31 23:22:10 -07003129
3130 if (mThreadThrottle
3131 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3132 && ret > 0) { // we wrote something
3133 // Limit MixerThread data processing to no more than twice the
3134 // expected processing rate.
3135 //
3136 // This helps prevent underruns with NuPlayer and other applications
3137 // which may set up buffers that are close to the minimum size, or use
3138 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3139 //
3140 // The throttle smooths out sudden large data drains from the device,
3141 // e.g. when it comes out of standby, which often causes problems with
3142 // (1) mixer threads without a fast mixer (which has its own warm-up)
3143 // (2) minimum buffer sized tracks (even if the track is full,
3144 // the app won't fill fast enough to handle the sudden draw).
3145
3146 const int32_t deltaMs = delta / 1000000;
3147 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3148 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3149 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003150 // notify of throttle start on verbose log
3151 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3152 "mixer(%p) throttle begin:"
3153 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003154 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003155 mThreadThrottleTimeMs += throttleMs;
3156 } else {
3157 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3158 if (diff > 0) {
3159 // notify of throttle end on debug log
3160 ALOGD("mixer(%p) throttle end: throttle time(%u)", this, diff);
3161 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3162 }
Andy Hung08fb1742015-05-31 23:22:10 -07003163 }
3164 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003165 }
Eric Laurent81784c32012-11-19 14:55:58 -08003166
Eric Laurentbfb1b832013-01-07 09:53:42 -08003167 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003168 ATRACE_BEGIN("sleep");
Eric Laurent51716182016-02-29 18:00:56 -08003169 if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
3170 Mutex::Autolock _l(mLock);
3171 if (!mSignalPending && !exitPending()) {
3172 // Do not sleep more than one buffer duration since last write and not
3173 // less than kDirectMinSleepTimeUs
3174 // Wake up if a command is received
3175 nsecs_t now = systemTime();
3176 uint32_t deltaUs = (uint32_t)((now - mLastWriteTime) / 1000);
3177 uint32_t timeoutUs = mSleepTimeUs;
3178 if (timeoutUs + deltaUs > mBufferDurationUs) {
3179 if (mBufferDurationUs > deltaUs) {
3180 timeoutUs = mBufferDurationUs - deltaUs;
3181 if (timeoutUs < kDirectMinSleepTimeUs) {
3182 timeoutUs = kDirectMinSleepTimeUs;
3183 }
3184 } else {
3185 timeoutUs = kDirectMinSleepTimeUs;
3186 }
3187 }
3188 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)timeoutUs));
3189 }
3190 } else {
3191 usleep(mSleepTimeUs);
3192 }
Glenn Kastene7754022014-10-31 12:11:26 -07003193 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003194 }
Eric Laurent81784c32012-11-19 14:55:58 -08003195 }
3196
3197 // Finally let go of removed track(s), without the lock held
3198 // since we can't guarantee the destructors won't acquire that
3199 // same lock. This will also mutate and push a new fast mixer state.
3200 threadLoop_removeTracks(tracksToRemove);
3201 tracksToRemove.clear();
3202
3203 // FIXME I don't understand the need for this here;
3204 // it was in the original code but maybe the
3205 // assignment in saveOutputTracks() makes this unnecessary?
3206 clearOutputTracks();
3207
3208 // Effect chains will be actually deleted here if they were removed from
3209 // mEffectChains list during mixing or effects processing
3210 effectChains.clear();
3211
3212 // FIXME Note that the above .clear() is no longer necessary since effectChains
3213 // is now local to this block, but will keep it for now (at least until merge done).
3214 }
3215
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 threadLoop_exit();
3217
Eric Laurentcf817a22014-08-04 20:36:31 -07003218 if (!mStandby) {
3219 threadLoop_standby();
3220 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003221 }
3222
3223 releaseWakeLock();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003224 mWakeLockUids.clear();
3225 mActiveTracksGeneration++;
Eric Laurent81784c32012-11-19 14:55:58 -08003226
3227 ALOGV("Thread %p type %d exiting", this, mType);
3228 return false;
3229}
3230
Eric Laurentbfb1b832013-01-07 09:53:42 -08003231// removeTracks_l() must be called with ThreadBase::mLock held
3232void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3233{
3234 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003235 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003236 for (size_t i=0 ; i<count ; i++) {
3237 const sp<Track>& track = tracksToRemove.itemAt(i);
3238 mActiveTracks.remove(track);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003239 mWakeLockUids.remove(track->uid());
3240 mActiveTracksGeneration++;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3242 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3243 if (chain != 0) {
3244 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3245 track->sessionId());
3246 chain->decActiveTrackCnt();
3247 }
3248 if (track->isTerminated()) {
3249 removeTrack_l(track);
3250 }
3251 }
3252 }
3253
3254}
Eric Laurent81784c32012-11-19 14:55:58 -08003255
Eric Laurentaccc1472013-09-20 09:36:34 -07003256status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3257{
3258 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003259 ExtendedTimestamp ets;
3260 status_t status = mNormalSink->getTimestamp(ets);
3261 if (status == NO_ERROR) {
3262 status = ets.getBestTimestamp(&timestamp);
3263 }
3264 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003265 }
Andy Hung9a1c8892014-12-03 11:37:42 -08003266 if ((mType == OFFLOAD || mType == DIRECT)
3267 && mOutput != NULL && mOutput->stream->get_presentation_position) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003268 uint64_t position64;
Phil Burk062e67a2015-02-11 13:40:50 -08003269 int ret = mOutput->getPresentationPosition(&position64, &timestamp.mTime);
Eric Laurentaccc1472013-09-20 09:36:34 -07003270 if (ret == 0) {
3271 timestamp.mPosition = (uint32_t)position64;
3272 return NO_ERROR;
3273 }
3274 }
3275 return INVALID_OPERATION;
3276}
Eric Laurent1c333e22014-05-20 10:48:17 -07003277
Eric Laurent054d9d32015-04-24 08:48:48 -07003278status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3279 audio_patch_handle_t *handle)
3280{
3281 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3282 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3283 if (mFastMixer != 0) {
3284 FastMixerStateQueue *sq = mFastMixer->sq();
3285 FastMixerState *state = sq->begin();
3286 if (!(state->mCommand & FastMixerState::IDLE)) {
3287 previousCommand = state->mCommand;
3288 state->mCommand = FastMixerState::HOT_IDLE;
3289 sq->end();
3290 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3291 } else {
3292 sq->end(false /*didModify*/);
3293 }
3294 }
3295 status_t status = PlaybackThread::createAudioPatch_l(patch, handle);
3296
3297 if (!(previousCommand & FastMixerState::IDLE)) {
3298 ALOG_ASSERT(mFastMixer != 0);
3299 FastMixerStateQueue *sq = mFastMixer->sq();
3300 FastMixerState *state = sq->begin();
3301 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3302 state->mCommand = previousCommand;
3303 sq->end();
3304 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3305 }
3306
3307 return status;
3308}
3309
Eric Laurent1c333e22014-05-20 10:48:17 -07003310status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3311 audio_patch_handle_t *handle)
3312{
3313 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003314
3315 // store new device and send to effects
3316 audio_devices_t type = AUDIO_DEVICE_NONE;
3317 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3318 type |= patch->sinks[i].ext.device.type;
3319 }
3320
3321#ifdef ADD_BATTERY_DATA
3322 // when changing the audio output device, call addBatteryData to notify
3323 // the change
3324 if (mOutDevice != type) {
3325 uint32_t params = 0;
3326 // check whether speaker is on
3327 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3328 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003329 }
3330
Eric Laurent054d9d32015-04-24 08:48:48 -07003331 audio_devices_t deviceWithoutSpeaker
3332 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3333 // check if any other device (except speaker) is on
3334 if (type & deviceWithoutSpeaker) {
3335 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3336 }
3337
3338 if (params != 0) {
3339 addBatteryData(params);
3340 }
3341 }
3342#endif
3343
3344 for (size_t i = 0; i < mEffectChains.size(); i++) {
3345 mEffectChains[i]->setDevice_l(type);
3346 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003347
3348 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3349 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3350 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003351 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003352 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003353
3354 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003355 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3356 status = hwDevice->create_audio_patch(hwDevice,
3357 patch->num_sources,
3358 patch->sources,
3359 patch->num_sinks,
3360 patch->sinks,
3361 handle);
3362 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003363 char *address;
3364 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3365 //FIXME: we only support address on first sink with HAL version < 3.0
3366 address = audio_device_address_to_parameter(
3367 patch->sinks[0].ext.device.type,
3368 patch->sinks[0].ext.device.address);
3369 } else {
3370 address = (char *)calloc(1, 1);
3371 }
3372 AudioParameter param = AudioParameter(String8(address));
3373 free(address);
3374 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), (int)type);
3375 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3376 param.toString().string());
3377 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003378 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003379 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003380 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003381 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3382 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003383 return status;
3384}
3385
Eric Laurent054d9d32015-04-24 08:48:48 -07003386status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3387{
3388 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3389 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
3390 if (mFastMixer != 0) {
3391 FastMixerStateQueue *sq = mFastMixer->sq();
3392 FastMixerState *state = sq->begin();
3393 if (!(state->mCommand & FastMixerState::IDLE)) {
3394 previousCommand = state->mCommand;
3395 state->mCommand = FastMixerState::HOT_IDLE;
3396 sq->end();
3397 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3398 } else {
3399 sq->end(false /*didModify*/);
3400 }
3401 }
3402
3403 status_t status = PlaybackThread::releaseAudioPatch_l(handle);
3404
3405 if (!(previousCommand & FastMixerState::IDLE)) {
3406 ALOG_ASSERT(mFastMixer != 0);
3407 FastMixerStateQueue *sq = mFastMixer->sq();
3408 FastMixerState *state = sq->begin();
3409 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3410 state->mCommand = previousCommand;
3411 sq->end();
3412 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3413 }
3414
3415 return status;
3416}
3417
Eric Laurent1c333e22014-05-20 10:48:17 -07003418status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3419{
3420 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003421
3422 mOutDevice = AUDIO_DEVICE_NONE;
3423
Eric Laurent1c333e22014-05-20 10:48:17 -07003424 if (mOutput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
3425 audio_hw_device_t *hwDevice = mOutput->audioHwDev->hwDevice();
3426 status = hwDevice->release_audio_patch(hwDevice, handle);
3427 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003428 AudioParameter param;
3429 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
3430 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
3431 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07003432 }
3433 return status;
3434}
3435
Eric Laurent83b88082014-06-20 18:31:16 -07003436void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3437{
3438 Mutex::Autolock _l(mLock);
3439 mTracks.add(track);
3440}
3441
3442void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3443{
3444 Mutex::Autolock _l(mLock);
3445 destroyTrack_l(track);
3446}
3447
3448void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3449{
3450 ThreadBase::getAudioPortConfig(config);
3451 config->role = AUDIO_PORT_ROLE_SOURCE;
3452 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3453 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3454}
3455
Eric Laurent81784c32012-11-19 14:55:58 -08003456// ----------------------------------------------------------------------------
3457
3458AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003459 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3460 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003461 // mAudioMixer below
3462 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003463 mFastMixerFutex(0),
3464 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003465 // mOutputSink below
3466 // mPipeSink below
3467 // mNormalSink below
3468{
3469 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenf6ed4232013-07-16 11:16:27 -07003470 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%u, "
Eric Laurent81784c32012-11-19 14:55:58 -08003471 "mFrameCount=%d, mNormalFrameCount=%d",
3472 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3473 mNormalFrameCount);
3474 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3475
Andy Hungfbfc3952015-01-15 13:33:51 -08003476 if (type == DUPLICATING) {
3477 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3478 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3479 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3480 return;
3481 }
Eric Laurent81784c32012-11-19 14:55:58 -08003482 // create an NBAIO sink for the HAL output stream, and negotiate
3483 mOutputSink = new AudioStreamOutSink(output->stream);
3484 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003485 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Eric Laurent81784c32012-11-19 14:55:58 -08003486 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
3487 ALOG_ASSERT(index == 0);
3488
3489 // initialize fast mixer depending on configuration
3490 bool initFastMixer;
3491 switch (kUseFastMixer) {
3492 case FastMixer_Never:
3493 initFastMixer = false;
3494 break;
3495 case FastMixer_Always:
3496 initFastMixer = true;
3497 break;
3498 case FastMixer_Static:
3499 case FastMixer_Dynamic:
3500 initFastMixer = mFrameCount < mNormalFrameCount;
3501 break;
3502 }
3503 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003504 audio_format_t fastMixerFormat;
3505 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3506 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3507 } else {
3508 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3509 }
3510 if (mFormat != fastMixerFormat) {
3511 // change our Sink format to accept our intermediate precision
3512 mFormat = fastMixerFormat;
3513 free(mSinkBuffer);
3514 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3515 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3516 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3517 }
Eric Laurent81784c32012-11-19 14:55:58 -08003518
3519 // create a MonoPipe to connect our submix to FastMixer
3520 NBAIO_Format format = mOutputSink->format();
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003521 NBAIO_Format origformat = format;
Andy Hung1258c1a2014-05-23 21:22:17 -07003522 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003523 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003524 format.mFormat = fastMixerFormat;
3525 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3526
Eric Laurent81784c32012-11-19 14:55:58 -08003527 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3528 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3529 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3530 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3531 const NBAIO_Format offers[1] = {format};
3532 size_t numCounterOffers = 0;
3533 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
3534 ALOG_ASSERT(index == 0);
3535 monoPipe->setAvgFrames((mScreenState & 1) ?
3536 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3537 mPipeSink = monoPipe;
3538
Glenn Kasten46909e72013-02-26 09:20:22 -08003539#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003540 if (mTeeSinkOutputEnabled) {
3541 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003542 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3543 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003544 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003545 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003546 ALOG_ASSERT(index == 0);
3547 mTeeSink = teeSink;
3548 PipeReader *teeSource = new PipeReader(*teeSink);
3549 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003550 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003551 ALOG_ASSERT(index == 0);
3552 mTeeSource = teeSource;
3553 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003554#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003555
3556 // create fast mixer and configure it initially with just one fast track for our submix
3557 mFastMixer = new FastMixer();
3558 FastMixerStateQueue *sq = mFastMixer->sq();
3559#ifdef STATE_QUEUE_DUMP
3560 sq->setObserverDump(&mStateQueueObserverDump);
3561 sq->setMutatorDump(&mStateQueueMutatorDump);
3562#endif
3563 FastMixerState *state = sq->begin();
3564 FastTrack *fastTrack = &state->mFastTracks[0];
3565 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3566 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3567 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003568 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3569 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003570 fastTrack->mGeneration++;
3571 state->mFastTracksGen++;
3572 state->mTrackMask = 1;
3573 // fast mixer will use the HAL output sink
3574 state->mOutputSink = mOutputSink.get();
3575 state->mOutputSinkGen++;
3576 state->mFrameCount = mFrameCount;
3577 state->mCommand = FastMixerState::COLD_IDLE;
3578 // already done in constructor initialization list
3579 //mFastMixerFutex = 0;
3580 state->mColdFutexAddr = &mFastMixerFutex;
3581 state->mColdGen++;
3582 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003583#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003584 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003585#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003586 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3587 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003588 sq->end();
3589 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3590
3591 // start the fast mixer
3592 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3593 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003594 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003595
3596#ifdef AUDIO_WATCHDOG
3597 // create and start the watchdog
3598 mAudioWatchdog = new AudioWatchdog();
3599 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3600 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3601 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003602 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003603#endif
3604
Eric Laurent81784c32012-11-19 14:55:58 -08003605 }
3606
3607 switch (kUseFastMixer) {
3608 case FastMixer_Never:
3609 case FastMixer_Dynamic:
3610 mNormalSink = mOutputSink;
3611 break;
3612 case FastMixer_Always:
3613 mNormalSink = mPipeSink;
3614 break;
3615 case FastMixer_Static:
3616 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3617 break;
3618 }
3619}
3620
3621AudioFlinger::MixerThread::~MixerThread()
3622{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003623 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003624 FastMixerStateQueue *sq = mFastMixer->sq();
3625 FastMixerState *state = sq->begin();
3626 if (state->mCommand == FastMixerState::COLD_IDLE) {
3627 int32_t old = android_atomic_inc(&mFastMixerFutex);
3628 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003629 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003630 }
3631 }
3632 state->mCommand = FastMixerState::EXIT;
3633 sq->end();
3634 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3635 mFastMixer->join();
3636 // Though the fast mixer thread has exited, it's state queue is still valid.
3637 // We'll use that extract the final state which contains one remaining fast track
3638 // corresponding to our sub-mix.
3639 state = sq->begin();
3640 ALOG_ASSERT(state->mTrackMask == 1);
3641 FastTrack *fastTrack = &state->mFastTracks[0];
3642 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3643 delete fastTrack->mBufferProvider;
3644 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003645 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003646#ifdef AUDIO_WATCHDOG
3647 if (mAudioWatchdog != 0) {
3648 mAudioWatchdog->requestExit();
3649 mAudioWatchdog->requestExitAndWait();
3650 mAudioWatchdog.clear();
3651 }
3652#endif
3653 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003654 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003655 delete mAudioMixer;
3656}
3657
3658
3659uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3660{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003661 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003662 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3663 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3664 }
3665 return latency;
3666}
3667
3668
3669void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3670{
3671 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3672}
3673
Eric Laurentbfb1b832013-01-07 09:53:42 -08003674ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003675{
3676 // FIXME we should only do one push per cycle; confirm this is true
3677 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003678 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003679 FastMixerStateQueue *sq = mFastMixer->sq();
3680 FastMixerState *state = sq->begin();
3681 if (state->mCommand != FastMixerState::MIX_WRITE &&
3682 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3683 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003684
3685 // FIXME workaround for first HAL write being CPU bound on some devices
3686 ATRACE_BEGIN("write");
3687 mOutput->write((char *)mSinkBuffer, 0);
3688 ATRACE_END();
3689
Eric Laurent81784c32012-11-19 14:55:58 -08003690 int32_t old = android_atomic_inc(&mFastMixerFutex);
3691 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003692 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003693 }
3694#ifdef AUDIO_WATCHDOG
3695 if (mAudioWatchdog != 0) {
3696 mAudioWatchdog->resume();
3697 }
3698#endif
3699 }
3700 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003701#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003702 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003703 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003704#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003705 sq->end();
3706 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3707 if (kUseFastMixer == FastMixer_Dynamic) {
3708 mNormalSink = mPipeSink;
3709 }
3710 } else {
3711 sq->end(false /*didModify*/);
3712 }
3713 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003714 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003715}
3716
3717void AudioFlinger::MixerThread::threadLoop_standby()
3718{
3719 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003720 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003721 FastMixerStateQueue *sq = mFastMixer->sq();
3722 FastMixerState *state = sq->begin();
3723 if (!(state->mCommand & FastMixerState::IDLE)) {
3724 state->mCommand = FastMixerState::COLD_IDLE;
3725 state->mColdFutexAddr = &mFastMixerFutex;
3726 state->mColdGen++;
3727 mFastMixerFutex = 0;
3728 sq->end();
3729 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3730 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3731 if (kUseFastMixer == FastMixer_Dynamic) {
3732 mNormalSink = mOutputSink;
3733 }
3734#ifdef AUDIO_WATCHDOG
3735 if (mAudioWatchdog != 0) {
3736 mAudioWatchdog->pause();
3737 }
3738#endif
3739 } else {
3740 sq->end(false /*didModify*/);
3741 }
3742 }
3743 PlaybackThread::threadLoop_standby();
3744}
3745
Eric Laurentbfb1b832013-01-07 09:53:42 -08003746bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3747{
3748 return false;
3749}
3750
3751bool AudioFlinger::PlaybackThread::shouldStandby_l()
3752{
3753 return !mStandby;
3754}
3755
3756bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3757{
3758 Mutex::Autolock _l(mLock);
3759 return waitingAsyncCallback_l();
3760}
3761
Eric Laurent81784c32012-11-19 14:55:58 -08003762// shared by MIXER and DIRECT, overridden by DUPLICATING
3763void AudioFlinger::PlaybackThread::threadLoop_standby()
3764{
3765 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003766 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003767 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003768 // discard any pending drain or write ack by incrementing sequence
3769 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3770 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003771 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003772 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3773 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003774 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003775 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003776}
3777
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003778void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3779{
3780 ALOGV("signal playback thread");
3781 broadcast_l();
3782}
3783
Eric Laurent81784c32012-11-19 14:55:58 -08003784void AudioFlinger::MixerThread::threadLoop_mix()
3785{
Eric Laurent81784c32012-11-19 14:55:58 -08003786 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003787 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003788 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003789 // increase sleep time progressively when application underrun condition clears.
3790 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3791 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3792 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003793 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003794 sleepTimeShift--;
3795 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003796 mSleepTimeUs = 0;
3797 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003798 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003799
Eric Laurent81784c32012-11-19 14:55:58 -08003800}
3801
3802void AudioFlinger::MixerThread::threadLoop_sleepTime()
3803{
3804 // If no tracks are ready, sleep once for the duration of an output
3805 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003806 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003807 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003808 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3809 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3810 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003811 }
3812 // reduce sleep time in case of consecutive application underruns to avoid
3813 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3814 // duration we would end up writing less data than needed by the audio HAL if
3815 // the condition persists.
3816 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3817 sleepTimeShift++;
3818 }
3819 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003820 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003821 }
3822 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003823 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3824 // before effects processing or output.
3825 if (mMixerBufferValid) {
3826 memset(mMixerBuffer, 0, mMixerBufferSize);
3827 } else {
3828 memset(mSinkBuffer, 0, mSinkBufferSize);
3829 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003830 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003831 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3832 "anticipated start");
3833 }
3834 // TODO add standby time extension fct of effect tail
3835}
3836
3837// prepareTracks_l() must be called with ThreadBase::mLock held
3838AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3839 Vector< sp<Track> > *tracksToRemove)
3840{
3841
3842 mixer_state mixerStatus = MIXER_IDLE;
3843 // find out which tracks need to be processed
3844 size_t count = mActiveTracks.size();
3845 size_t mixedTracks = 0;
3846 size_t tracksWithEffect = 0;
3847 // counts only _active_ fast tracks
3848 size_t fastTracks = 0;
3849 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3850
3851 float masterVolume = mMasterVolume;
3852 bool masterMute = mMasterMute;
3853
3854 if (masterMute) {
3855 masterVolume = 0;
3856 }
3857 // Delegate master volume control to effect in output mix effect chain if needed
3858 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3859 if (chain != 0) {
3860 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3861 chain->setVolume_l(&v, &v);
3862 masterVolume = (float)((v + (1 << 23)) >> 24);
3863 chain.clear();
3864 }
3865
3866 // prepare a new state to push
3867 FastMixerStateQueue *sq = NULL;
3868 FastMixerState *state = NULL;
3869 bool didModify = false;
3870 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003871 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003872 sq = mFastMixer->sq();
3873 state = sq->begin();
3874 }
3875
Andy Hung69aed5f2014-02-25 17:24:40 -08003876 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003877 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003878
Eric Laurent81784c32012-11-19 14:55:58 -08003879 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten9fdcb0a2013-06-26 16:11:36 -07003880 const sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08003881 if (t == 0) {
3882 continue;
3883 }
3884
3885 // this const just means the local variable doesn't change
3886 Track* const track = t.get();
3887
3888 // process fast tracks
3889 if (track->isFastTrack()) {
3890
3891 // It's theoretically possible (though unlikely) for a fast track to be created
3892 // and then removed within the same normal mix cycle. This is not a problem, as
3893 // the track never becomes active so it's fast mixer slot is never touched.
3894 // The converse, of removing an (active) track and then creating a new track
3895 // at the identical fast mixer slot within the same normal mix cycle,
3896 // is impossible because the slot isn't marked available until the end of each cycle.
3897 int j = track->mFastIndex;
3898 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
3899 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3900 FastTrack *fastTrack = &state->mFastTracks[j];
3901
3902 // Determine whether the track is currently in underrun condition,
3903 // and whether it had a recent underrun.
3904 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3905 FastTrackUnderruns underruns = ftDump->mUnderruns;
3906 uint32_t recentFull = (underruns.mBitFields.mFull -
3907 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3908 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3909 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3910 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3911 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3912 uint32_t recentUnderruns = recentPartial + recentEmpty;
3913 track->mObservedUnderruns = underruns;
3914 // don't count underruns that occur while stopping or pausing
3915 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003916 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3917 recentUnderruns > 0) {
3918 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3919 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003920 } else {
3921 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003922 }
3923
3924 // This is similar to the state machine for normal tracks,
3925 // with a few modifications for fast tracks.
3926 bool isActive = true;
3927 switch (track->mState) {
3928 case TrackBase::STOPPING_1:
3929 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08003930 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003931 track->mState = TrackBase::STOPPING_2;
3932 }
3933 break;
3934 case TrackBase::PAUSING:
3935 // ramp down is not yet implemented
3936 track->setPaused();
3937 break;
3938 case TrackBase::RESUMING:
3939 // ramp up is not yet implemented
3940 track->mState = TrackBase::ACTIVE;
3941 break;
3942 case TrackBase::ACTIVE:
3943 if (recentFull > 0 || recentPartial > 0) {
3944 // track has provided at least some frames recently: reset retry count
3945 track->mRetryCount = kMaxTrackRetries;
3946 }
3947 if (recentUnderruns == 0) {
3948 // no recent underruns: stay active
3949 break;
3950 }
3951 // there has recently been an underrun of some kind
3952 if (track->sharedBuffer() == 0) {
3953 // were any of the recent underruns "empty" (no frames available)?
3954 if (recentEmpty == 0) {
3955 // no, then ignore the partial underruns as they are allowed indefinitely
3956 break;
3957 }
3958 // there has recently been an "empty" underrun: decrement the retry counter
3959 if (--(track->mRetryCount) > 0) {
3960 break;
3961 }
3962 // indicate to client process that the track was disabled because of underrun;
3963 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08003964 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08003965 // remove from active list, but state remains ACTIVE [confusing but true]
3966 isActive = false;
3967 break;
3968 }
3969 // fall through
3970 case TrackBase::STOPPING_2:
3971 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003972 case TrackBase::STOPPED:
3973 case TrackBase::FLUSHED: // flush() while active
3974 // Check for presentation complete if track is inactive
3975 // We have consumed all the buffers of this track.
3976 // This would be incomplete if we auto-paused on underrun
3977 {
3978 size_t audioHALFrames =
3979 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003980 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003981 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
3982 // track stays in active list until presentation is complete
3983 break;
3984 }
3985 }
3986 if (track->isStopping_2()) {
3987 track->mState = TrackBase::STOPPED;
3988 }
3989 if (track->isStopped()) {
3990 // Can't reset directly, as fast mixer is still polling this track
3991 // track->reset();
3992 // So instead mark this track as needing to be reset after push with ack
3993 resetMask |= 1 << i;
3994 }
3995 isActive = false;
3996 break;
3997 case TrackBase::IDLE:
3998 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08003999 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004000 }
4001
4002 if (isActive) {
4003 // was it previously inactive?
4004 if (!(state->mTrackMask & (1 << j))) {
4005 ExtendedAudioBufferProvider *eabp = track;
4006 VolumeProvider *vp = track;
4007 fastTrack->mBufferProvider = eabp;
4008 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004009 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004010 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004011 fastTrack->mGeneration++;
4012 state->mTrackMask |= 1 << j;
4013 didModify = true;
4014 // no acknowledgement required for newly active tracks
4015 }
4016 // cache the combined master volume and stream type volume for fast mixer; this
4017 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004018 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004019 ++fastTracks;
4020 } else {
4021 // was it previously active?
4022 if (state->mTrackMask & (1 << j)) {
4023 fastTrack->mBufferProvider = NULL;
4024 fastTrack->mGeneration++;
4025 state->mTrackMask &= ~(1 << j);
4026 didModify = true;
4027 // If any fast tracks were removed, we must wait for acknowledgement
4028 // because we're about to decrement the last sp<> on those tracks.
4029 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4030 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004031 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4032 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4033 j, track->mState, state->mTrackMask, recentUnderruns,
4034 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004035 }
4036 tracksToRemove->add(track);
4037 // Avoids a misleading display in dumpsys
4038 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4039 }
4040 continue;
4041 }
4042
4043 { // local variable scope to avoid goto warning
4044
4045 audio_track_cblk_t* cblk = track->cblk();
4046
4047 // The first time a track is added we wait
4048 // for all its buffers to be filled before processing it
4049 int name = track->name();
4050 // make sure that we have enough frames to mix one full buffer.
4051 // enforce this condition only once to enable draining the buffer in case the client
4052 // app does not call stop() and relies on underrun to stop:
4053 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4054 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004055 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004056 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004057 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004058
4059 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004060 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004061 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4062 // add frames already consumed but not yet released by the resampler
4063 // because mAudioTrackServerProxy->framesReady() will include these frames
4064 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4065
Eric Laurent81784c32012-11-19 14:55:58 -08004066 uint32_t minFrames = 1;
4067 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4068 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004069 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004070 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004071
4072 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004073 if (ATRACE_ENABLED()) {
4074 // I wish we had formatted trace names
4075 char traceName[16];
4076 strcpy(traceName, "nRdy");
4077 int name = track->name();
4078 if (AudioMixer::TRACK0 <= name &&
4079 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4080 name -= AudioMixer::TRACK0;
4081 traceName[4] = (name / 10) + '0';
4082 traceName[5] = (name % 10) + '0';
4083 } else {
4084 traceName[4] = '?';
4085 traceName[5] = '?';
4086 }
4087 traceName[6] = '\0';
4088 ATRACE_INT(traceName, framesReady);
4089 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004090 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004091 !track->isPaused() && !track->isTerminated())
4092 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004093 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004094
4095 mixedTracks++;
4096
Andy Hung69aed5f2014-02-25 17:24:40 -08004097 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4098 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004099 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004100 if (track->mainBuffer() != mSinkBuffer &&
4101 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004102 if (mEffectBufferEnabled) {
4103 mEffectBufferValid = true; // Later can set directly.
4104 }
Eric Laurent81784c32012-11-19 14:55:58 -08004105 chain = getEffectChain_l(track->sessionId());
4106 // Delegate volume control to effect in track effect chain if needed
4107 if (chain != 0) {
4108 tracksWithEffect++;
4109 } else {
4110 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4111 "session %d",
4112 name, track->sessionId());
4113 }
4114 }
4115
4116
4117 int param = AudioMixer::VOLUME;
4118 if (track->mFillingUpStatus == Track::FS_FILLED) {
4119 // no ramp for the first volume setting
4120 track->mFillingUpStatus = Track::FS_ACTIVE;
4121 if (track->mState == TrackBase::RESUMING) {
4122 track->mState = TrackBase::ACTIVE;
4123 param = AudioMixer::RAMP_VOLUME;
4124 }
4125 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004126 // FIXME should not make a decision based on mServer
4127 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004128 // If the track is stopped before the first frame was mixed,
4129 // do not apply ramp
4130 param = AudioMixer::RAMP_VOLUME;
4131 }
4132
4133 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004134 uint32_t vl, vr; // in U8.24 integer format
4135 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004136 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004137 vl = vr = 0;
4138 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004139 if (track->isPausing()) {
4140 track->setPaused();
4141 }
4142 } else {
4143
4144 // read original volumes with volume control
4145 float typeVolume = mStreamTypes[track->streamType()].volume;
4146 float v = masterVolume * typeVolume;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004147 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004148 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004149 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4150 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004151 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004152 if (vlf > GAIN_FLOAT_UNITY) {
4153 ALOGV("Track left volume out of range: %.3g", vlf);
4154 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004155 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004156 if (vrf > GAIN_FLOAT_UNITY) {
4157 ALOGV("Track right volume out of range: %.3g", vrf);
4158 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004159 }
4160 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004161 vlf *= v;
4162 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004163 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004164 // then derive vl and vr as U8.24 versions for the effect chain
4165 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4166 vl = (uint32_t) (scaleto8_24 * vlf);
4167 vr = (uint32_t) (scaleto8_24 * vrf);
4168 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004169 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004170 // send level comes from shared memory and so may be corrupt
4171 if (sendLevel > MAX_GAIN_INT) {
4172 ALOGV("Track send level out of range: %04X", sendLevel);
4173 sendLevel = MAX_GAIN_INT;
4174 }
Andy Hung6be49402014-05-30 10:42:03 -07004175 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4176 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004177 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004178
Eric Laurent81784c32012-11-19 14:55:58 -08004179 // Delegate volume control to effect in track effect chain if needed
4180 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4181 // Do not ramp volume if volume is controlled by effect
4182 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004183 // Update remaining floating point volume levels
4184 vlf = (float)vl / (1 << 24);
4185 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004186 track->mHasVolumeController = true;
4187 } else {
4188 // force no volume ramp when volume controller was just disabled or removed
4189 // from effect chain to avoid volume spike
4190 if (track->mHasVolumeController) {
4191 param = AudioMixer::VOLUME;
4192 }
4193 track->mHasVolumeController = false;
4194 }
4195
Eric Laurent81784c32012-11-19 14:55:58 -08004196 // XXX: these things DON'T need to be done each time
4197 mAudioMixer->setBufferProvider(name, track);
4198 mAudioMixer->enable(name);
4199
Andy Hung6be49402014-05-30 10:42:03 -07004200 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4201 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4202 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004203 mAudioMixer->setParameter(
4204 name,
4205 AudioMixer::TRACK,
4206 AudioMixer::FORMAT, (void *)track->format());
4207 mAudioMixer->setParameter(
4208 name,
4209 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004210 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004211 mAudioMixer->setParameter(
4212 name,
4213 AudioMixer::TRACK,
4214 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004215 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004216 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004217 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004218 if (reqSampleRate == 0) {
4219 reqSampleRate = mSampleRate;
4220 } else if (reqSampleRate > maxSampleRate) {
4221 reqSampleRate = maxSampleRate;
4222 }
Eric Laurent81784c32012-11-19 14:55:58 -08004223 mAudioMixer->setParameter(
4224 name,
4225 AudioMixer::RESAMPLE,
4226 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004227 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004228
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004229 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004230 mAudioMixer->setParameter(
4231 name,
4232 AudioMixer::TIMESTRETCH,
4233 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004234 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004235
Andy Hung69aed5f2014-02-25 17:24:40 -08004236 /*
4237 * Select the appropriate output buffer for the track.
4238 *
Andy Hung98ef9782014-03-04 14:46:50 -08004239 * Tracks with effects go into their own effects chain buffer
4240 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004241 *
4242 * Other tracks can use mMixerBuffer for higher precision
4243 * channel accumulation. If this buffer is enabled
4244 * (mMixerBufferEnabled true), then selected tracks will accumulate
4245 * into it.
4246 *
4247 */
4248 if (mMixerBufferEnabled
4249 && (track->mainBuffer() == mSinkBuffer
4250 || track->mainBuffer() == mMixerBuffer)) {
4251 mAudioMixer->setParameter(
4252 name,
4253 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004254 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004255 mAudioMixer->setParameter(
4256 name,
4257 AudioMixer::TRACK,
4258 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4259 // TODO: override track->mainBuffer()?
4260 mMixerBufferValid = true;
4261 } else {
4262 mAudioMixer->setParameter(
4263 name,
4264 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004265 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004266 mAudioMixer->setParameter(
4267 name,
4268 AudioMixer::TRACK,
4269 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4270 }
Eric Laurent81784c32012-11-19 14:55:58 -08004271 mAudioMixer->setParameter(
4272 name,
4273 AudioMixer::TRACK,
4274 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4275
4276 // reset retry count
4277 track->mRetryCount = kMaxTrackRetries;
4278
4279 // If one track is ready, set the mixer ready if:
4280 // - the mixer was not ready during previous round OR
4281 // - no other track is not ready
4282 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4283 mixerStatus != MIXER_TRACKS_ENABLED) {
4284 mixerStatus = MIXER_TRACKS_READY;
4285 }
4286 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004287 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004288 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4289 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004290 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004291 } else {
4292 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004293 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004294
Eric Laurent81784c32012-11-19 14:55:58 -08004295 // clear effect chain input buffer if an active track underruns to avoid sending
4296 // previous audio buffer again to effects
4297 chain = getEffectChain_l(track->sessionId());
4298 if (chain != 0) {
4299 chain->clearInputBuffer();
4300 }
4301
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004302 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004303 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4304 track->isStopped() || track->isPaused()) {
4305 // We have consumed all the buffers of this track.
4306 // Remove it from the list of active tracks.
4307 // TODO: use actual buffer filling status instead of latency when available from
4308 // audio HAL
4309 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004310 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004311 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4312 if (track->isStopped()) {
4313 track->reset();
4314 }
4315 tracksToRemove->add(track);
4316 }
4317 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004318 // No buffers for this track. Give it a few chances to
4319 // fill a buffer, then remove it from active list.
4320 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004321 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004322 tracksToRemove->add(track);
4323 // indicate to client process that the track was disabled because of underrun;
4324 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004325 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004326 // If one track is not ready, mark the mixer also not ready if:
4327 // - the mixer was ready during previous round OR
4328 // - no other track is ready
4329 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4330 mixerStatus != MIXER_TRACKS_READY) {
4331 mixerStatus = MIXER_TRACKS_ENABLED;
4332 }
4333 }
4334 mAudioMixer->disable(name);
4335 }
4336
4337 } // local variable scope to avoid goto warning
4338track_is_ready: ;
4339
4340 }
4341
4342 // Push the new FastMixer state if necessary
4343 bool pauseAudioWatchdog = false;
4344 if (didModify) {
4345 state->mFastTracksGen++;
4346 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4347 if (kUseFastMixer == FastMixer_Dynamic &&
4348 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4349 state->mCommand = FastMixerState::COLD_IDLE;
4350 state->mColdFutexAddr = &mFastMixerFutex;
4351 state->mColdGen++;
4352 mFastMixerFutex = 0;
4353 if (kUseFastMixer == FastMixer_Dynamic) {
4354 mNormalSink = mOutputSink;
4355 }
4356 // If we go into cold idle, need to wait for acknowledgement
4357 // so that fast mixer stops doing I/O.
4358 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4359 pauseAudioWatchdog = true;
4360 }
Eric Laurent81784c32012-11-19 14:55:58 -08004361 }
4362 if (sq != NULL) {
4363 sq->end(didModify);
4364 sq->push(block);
4365 }
4366#ifdef AUDIO_WATCHDOG
4367 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4368 mAudioWatchdog->pause();
4369 }
4370#endif
4371
4372 // Now perform the deferred reset on fast tracks that have stopped
4373 while (resetMask != 0) {
4374 size_t i = __builtin_ctz(resetMask);
4375 ALOG_ASSERT(i < count);
4376 resetMask &= ~(1 << i);
4377 sp<Track> t = mActiveTracks[i].promote();
4378 if (t == 0) {
4379 continue;
4380 }
4381 Track* track = t.get();
4382 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4383 track->reset();
4384 }
4385
4386 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004387 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004388
Eric Laurent97d547d2014-09-02 14:45:53 -07004389 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4390 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004391 }
4392
4393 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004394 // as long as there are effects we should clear the effects buffer, to avoid
4395 // passing a non-clean buffer to the effect chain
4396 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004397 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004398 // sink or mix buffer must be cleared if all tracks are connected to an
4399 // effect chain as in this case the mixer will not write to the sink or mix buffer
4400 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004401 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4402 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004403 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004404 if (mMixerBufferValid) {
4405 memset(mMixerBuffer, 0, mMixerBufferSize);
4406 // TODO: In testing, mSinkBuffer below need not be cleared because
4407 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4408 // after mixing.
4409 //
4410 // To enforce this guarantee:
4411 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4412 // (mixedTracks == 0 && fastTracks > 0))
4413 // must imply MIXER_TRACKS_READY.
4414 // Later, we may clear buffers regardless, and skip much of this logic.
4415 }
Andy Hung98ef9782014-03-04 14:46:50 -08004416 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004417 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004418 }
4419
4420 // if any fast tracks, then status is ready
4421 mMixerStatusIgnoringFastTracks = mixerStatus;
4422 if (fastTracks > 0) {
4423 mixerStatus = MIXER_TRACKS_READY;
4424 }
4425 return mixerStatus;
4426}
4427
4428// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004429int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
4430 audio_format_t format, int sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08004431{
Andy Hunge8a1ced2014-05-09 15:02:21 -07004432 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004433}
4434
4435// deleteTrackName_l() must be called with ThreadBase::mLock held
4436void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4437{
4438 ALOGV("remove track (%d) and delete from mixer", name);
4439 mAudioMixer->deleteTrackName(name);
4440}
4441
Eric Laurent10351942014-05-08 18:49:52 -07004442// checkForNewParameter_l() must be called with ThreadBase::mLock held
4443bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4444 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004445{
Eric Laurent81784c32012-11-19 14:55:58 -08004446 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004447 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004448
Eric Laurent10351942014-05-08 18:49:52 -07004449 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004450
Eric Laurent10351942014-05-08 18:49:52 -07004451 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
4452 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004453 if (mFastMixer != 0) {
Eric Laurent10351942014-05-08 18:49:52 -07004454 FastMixerStateQueue *sq = mFastMixer->sq();
4455 FastMixerState *state = sq->begin();
4456 if (!(state->mCommand & FastMixerState::IDLE)) {
4457 previousCommand = state->mCommand;
4458 state->mCommand = FastMixerState::HOT_IDLE;
4459 sq->end();
4460 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4461 } else {
4462 sq->end(false /*didModify*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004463 }
Eric Laurent10351942014-05-08 18:49:52 -07004464 }
Eric Laurent81784c32012-11-19 14:55:58 -08004465
Eric Laurent10351942014-05-08 18:49:52 -07004466 AudioParameter param = AudioParameter(keyValuePair);
4467 int value;
4468 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4469 reconfig = true;
4470 }
4471 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004472 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004473 status = BAD_VALUE;
4474 } else {
4475 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004476 reconfig = true;
4477 }
Eric Laurent10351942014-05-08 18:49:52 -07004478 }
4479 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004480 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004481 status = BAD_VALUE;
4482 } else {
4483 // no need to save value, since it's constant
4484 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004485 }
Eric Laurent10351942014-05-08 18:49:52 -07004486 }
4487 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4488 // do not accept frame count changes if tracks are open as the track buffer
4489 // size depends on frame count and correct behavior would not be guaranteed
4490 // if frame count is changed after track creation
4491 if (!mTracks.isEmpty()) {
4492 status = INVALID_OPERATION;
4493 } else {
4494 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004495 }
Eric Laurent10351942014-05-08 18:49:52 -07004496 }
4497 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004498#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004499 // when changing the audio output device, call addBatteryData to notify
4500 // the change
4501 if (mOutDevice != value) {
4502 uint32_t params = 0;
4503 // check whether speaker is on
4504 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4505 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004506 }
Eric Laurent10351942014-05-08 18:49:52 -07004507
4508 audio_devices_t deviceWithoutSpeaker
4509 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4510 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004511 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004512 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4513 }
4514
4515 if (params != 0) {
4516 addBatteryData(params);
4517 }
4518 }
Eric Laurent81784c32012-11-19 14:55:58 -08004519#endif
4520
Eric Laurent10351942014-05-08 18:49:52 -07004521 // forward device change to effects that have requested to be
4522 // aware of attached audio device.
4523 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004524 a2dpDeviceChanged =
4525 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004526 mOutDevice = value;
4527 for (size_t i = 0; i < mEffectChains.size(); i++) {
4528 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004529 }
4530 }
Eric Laurent10351942014-05-08 18:49:52 -07004531 }
Eric Laurent81784c32012-11-19 14:55:58 -08004532
Eric Laurent10351942014-05-08 18:49:52 -07004533 if (status == NO_ERROR) {
4534 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
4535 keyValuePair.string());
4536 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004537 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004538 mStandby = true;
4539 mBytesWritten = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004540 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Eric Laurent10351942014-05-08 18:49:52 -07004541 keyValuePair.string());
Eric Laurent81784c32012-11-19 14:55:58 -08004542 }
Eric Laurent10351942014-05-08 18:49:52 -07004543 if (status == NO_ERROR && reconfig) {
4544 readOutputParameters_l();
4545 delete mAudioMixer;
4546 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4547 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004548 int name = getTrackName_l(mTracks[i]->mChannelMask,
4549 mTracks[i]->mFormat, mTracks[i]->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004550 if (name < 0) {
4551 break;
4552 }
4553 mTracks[i]->mName = name;
4554 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004555 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004556 }
Eric Laurent81784c32012-11-19 14:55:58 -08004557 }
4558
4559 if (!(previousCommand & FastMixerState::IDLE)) {
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004560 ALOG_ASSERT(mFastMixer != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004561 FastMixerStateQueue *sq = mFastMixer->sq();
4562 FastMixerState *state = sq->begin();
4563 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
4564 state->mCommand = previousCommand;
4565 sq->end();
4566 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4567 }
4568
Eric Laurent42537be2016-01-08 17:16:42 -08004569 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004570}
4571
4572
4573void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4574{
4575 const size_t SIZE = 256;
4576 char buffer[SIZE];
4577 String8 result;
4578
4579 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004580 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004581 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004582 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004583
4584 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004585 // while we are dumping it. It may be inconsistent, but it won't mutate!
4586 // This is a large object so we place it on the heap.
4587 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4588 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4589 copy->dump(fd);
4590 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004591
4592#ifdef STATE_QUEUE_DUMP
4593 // Similar for state queue
4594 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4595 observerCopy.dump(fd);
4596 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4597 mutatorCopy.dump(fd);
4598#endif
4599
Glenn Kasten46909e72013-02-26 09:20:22 -08004600#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004601 // Write the tee output to a .wav file
4602 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004603#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004604
4605#ifdef AUDIO_WATCHDOG
4606 if (mAudioWatchdog != 0) {
4607 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4608 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4609 wdCopy.dump(fd);
4610 }
4611#endif
4612}
4613
4614uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4615{
4616 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4617}
4618
4619uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4620{
4621 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4622}
4623
4624void AudioFlinger::MixerThread::cacheParameters_l()
4625{
4626 PlaybackThread::cacheParameters_l();
4627
4628 // FIXME: Relaxed timing because of a certain device that can't meet latency
4629 // Should be reduced to 2x after the vendor fixes the driver issue
4630 // increase threshold again due to low power audio mode. The way this warning
4631 // threshold is calculated and its usefulness should be reconsidered anyway.
4632 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4633}
4634
4635// ----------------------------------------------------------------------------
4636
4637AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08004638 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady,
4639 uint32_t bitRate)
4640 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady, bitRate)
Eric Laurent81784c32012-11-19 14:55:58 -08004641 // mLeftVolFloat, mRightVolFloat
4642{
4643}
4644
Eric Laurentbfb1b832013-01-07 09:53:42 -08004645AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4646 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurent51716182016-02-29 18:00:56 -08004647 ThreadBase::type_t type, bool systemReady, uint32_t bitRate)
4648 : PlaybackThread(audioFlinger, output, id, device, type, systemReady, bitRate)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 // mLeftVolFloat, mRightVolFloat
4650{
4651}
4652
Eric Laurent81784c32012-11-19 14:55:58 -08004653AudioFlinger::DirectOutputThread::~DirectOutputThread()
4654{
4655}
4656
Eric Laurentbfb1b832013-01-07 09:53:42 -08004657void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
4658{
4659 audio_track_cblk_t* cblk = track->cblk();
4660 float left, right;
4661
4662 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4663 left = right = 0;
4664 } else {
4665 float typeVolume = mStreamTypes[track->streamType()].volume;
4666 float v = mMasterVolume * typeVolume;
4667 AudioTrackServerProxy *proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004668 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4669 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4670 if (left > GAIN_FLOAT_UNITY) {
4671 left = GAIN_FLOAT_UNITY;
4672 }
4673 left *= v;
4674 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4675 if (right > GAIN_FLOAT_UNITY) {
4676 right = GAIN_FLOAT_UNITY;
4677 }
4678 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004679 }
4680
4681 if (lastTrack) {
4682 if (left != mLeftVolFloat || right != mRightVolFloat) {
4683 mLeftVolFloat = left;
4684 mRightVolFloat = right;
4685
4686 // Convert volumes from float to 8.24
4687 uint32_t vl = (uint32_t)(left * (1 << 24));
4688 uint32_t vr = (uint32_t)(right * (1 << 24));
4689
4690 // Delegate volume control to effect in track effect chain if needed
4691 // only one effect chain can be present on DirectOutputThread, so if
4692 // there is one, the track is connected to it
4693 if (!mEffectChains.isEmpty()) {
4694 mEffectChains[0]->setVolume_l(&vl, &vr);
4695 left = (float)vl / (1 << 24);
4696 right = (float)vr / (1 << 24);
4697 }
4698 if (mOutput->stream->set_volume) {
4699 mOutput->stream->set_volume(mOutput->stream, left, right);
4700 }
4701 }
4702 }
4703}
4704
Phil Burk43b4dcc2015-06-09 16:53:44 -07004705void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4706{
4707 sp<Track> previousTrack = mPreviousTrack.promote();
4708 sp<Track> latestTrack = mLatestActiveTrack.promote();
4709
Eric Laurent0f0631e2015-07-06 18:01:25 -07004710 if (previousTrack != 0 && latestTrack != 0) {
4711 if (mType == DIRECT) {
4712 if (previousTrack.get() != latestTrack.get()) {
4713 mFlushPending = true;
4714 }
4715 } else /* mType == OFFLOAD */ {
4716 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4717 mFlushPending = true;
4718 }
4719 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004720 }
4721 PlaybackThread::onAddNewTrack_l();
4722}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004723
Eric Laurent81784c32012-11-19 14:55:58 -08004724AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4725 Vector< sp<Track> > *tracksToRemove
4726)
4727{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004728 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004729 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004730 bool doHwPause = false;
4731 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004732
4733 // find out which tracks need to be processed
Eric Laurentd595b7c2013-04-03 17:27:56 -07004734 for (size_t i = 0; i < count; i++) {
4735 sp<Track> t = mActiveTracks[i].promote();
Eric Laurent81784c32012-11-19 14:55:58 -08004736 // The track died recently
4737 if (t == 0) {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004738 continue;
Eric Laurent81784c32012-11-19 14:55:58 -08004739 }
4740
Phil Burk43b4dcc2015-06-09 16:53:44 -07004741 if (t->isInvalid()) {
4742 ALOGW("An invalidated track shouldn't be in active list");
4743 tracksToRemove->add(t);
4744 continue;
4745 }
4746
Eric Laurent81784c32012-11-19 14:55:58 -08004747 Track* const track = t.get();
4748 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07004749 // Only consider last track started for volume and mixer state control.
4750 // In theory an older track could underrun and restart after the new one starts
4751 // but as we only care about the transition phase between two tracks on a
4752 // direct output, it is not a problem to ignore the underrun case.
4753 sp<Track> l = mLatestActiveTrack.promote();
4754 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004755
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004756 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004757 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004758 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004759 doHwPause = true;
4760 mHwPaused = true;
4761 }
4762 tracksToRemove->add(track);
4763 } else if (track->isFlushPending()) {
4764 track->flushAck();
4765 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004766 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004767 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004768 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004769 track->resumeAck();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004770 if (last && mHwPaused) {
4771 doHwResume = true;
4772 mHwPaused = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004773 }
4774 }
4775
Eric Laurent81784c32012-11-19 14:55:58 -08004776 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004777 // for all its buffers to be filled before processing it.
4778 // Allow draining the buffer in case the client
4779 // app does not call stop() and relies on underrun to stop:
4780 // hence the test on (track->mRetryCount > 1).
4781 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004782 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004783 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004784 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004785 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004786 minFrames = mNormalFrameCount;
4787 } else {
4788 minFrames = 1;
4789 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004790
Eric Laurentab5cdba2014-06-09 17:22:27 -07004791 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4792 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004793 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004794 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004795
4796 if (track->mFillingUpStatus == Track::FS_FILLED) {
4797 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07004798 // make sure processVolume_l() will apply new volume even if 0
4799 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004800 if (!mHwSupportsPause) {
4801 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004802 }
4803 }
4804
4805 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806 processVolume_l(track, last);
4807 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004808 sp<Track> previousTrack = mPreviousTrack.promote();
4809 if (previousTrack != 0) {
4810 if (track != previousTrack.get()) {
4811 // Flush any data still being written from last track
4812 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004813 // Invalidate previous track to force a seek when resuming.
4814 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004815 }
4816 }
4817 mPreviousTrack = track;
4818
Eric Laurentd595b7c2013-04-03 17:27:56 -07004819 // reset retry count
4820 track->mRetryCount = kMaxTrackRetriesDirect;
4821 mActiveTrack = t;
4822 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004823 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004824 doHwResume = true;
4825 mHwPaused = false;
4826 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004827 }
Eric Laurent81784c32012-11-19 14:55:58 -08004828 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004829 // clear effect chain input buffer if the last active track started underruns
4830 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004831 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004832 mEffectChains[0]->clearInputBuffer();
4833 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004834 if (track->isStopping_1()) {
4835 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004836 if (last && mHwPaused) {
4837 doHwResume = true;
4838 mHwPaused = false;
4839 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004840 }
4841 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4842 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004843 // We have consumed all the buffers of this track.
4844 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004845 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004846 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004847 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4848 } else {
4849 audioHALFrames = 0;
4850 }
4851
Andy Hung818e7a32016-02-16 18:08:07 -08004852 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004853 if (mStandby || !last ||
4854 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004855 if (track->isStopping_2()) {
4856 track->mState = TrackBase::STOPPED;
4857 }
Eric Laurent81784c32012-11-19 14:55:58 -08004858 if (track->isStopped()) {
4859 track->reset();
4860 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004861 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004862 }
4863 } else {
4864 // No buffers for this track. Give it a few chances to
4865 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004866 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004867 if (--(track->mRetryCount) <= 0) {
4868 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004869 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004870 // indicate to client process that the track was disabled because of underrun;
4871 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004872 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004873 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004874 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4875 "minFrames = %u, mFormat = %#x",
4876 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004877 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004878 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004879 doHwPause = true;
4880 mHwPaused = true;
4881 }
Eric Laurent81784c32012-11-19 14:55:58 -08004882 }
4883 }
4884 }
4885 }
4886
Eric Laurentd1f69b02014-12-15 14:33:13 -08004887 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004888 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004889 for (size_t i = 0; i < mTracks.size(); i++) {
4890 if (mTracks[i]->isFlushPending()) {
4891 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004892 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004893 }
4894 }
4895 }
4896
4897 // make sure the pause/flush/resume sequence is executed in the right order.
4898 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4899 // before flush and then resume HW. This can happen in case of pause/flush/resume
4900 // if resume is received before pause is executed.
4901 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004902 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004903 mOutput->stream->pause(mOutput->stream);
4904 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004905 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004906 flushHw_l();
4907 }
4908 if (mHwSupportsPause && !mStandby && doHwResume) {
4909 mOutput->stream->resume(mOutput->stream);
4910 }
Eric Laurent81784c32012-11-19 14:55:58 -08004911 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004912 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004913
4914 return mixerStatus;
4915}
4916
4917void AudioFlinger::DirectOutputThread::threadLoop_mix()
4918{
Eric Laurent81784c32012-11-19 14:55:58 -08004919 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004920 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004921 // output audio to hardware
4922 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004923 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004924 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004925 status_t status = mActiveTrack->getNextBuffer(&buffer);
4926 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004927 // no need to pad with 0 for compressed audio
4928 if (audio_has_proportional_frames(mFormat)) {
4929 memset(curBuf, 0, frameCount * mFrameSize);
4930 }
Eric Laurent81784c32012-11-19 14:55:58 -08004931 break;
4932 }
4933 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4934 frameCount -= buffer.frameCount;
4935 curBuf += buffer.frameCount * mFrameSize;
4936 mActiveTrack->releaseBuffer(&buffer);
4937 }
Andy Hung2098f272014-02-27 14:00:06 -08004938 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004939 mSleepTimeUs = 0;
4940 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004941 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004942}
4943
4944void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
4945{
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004947 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004948 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004949 return;
4950 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004951 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004952 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent51716182016-02-29 18:00:56 -08004953 // For compressed offload, use faster sleep time when underruning until more than an
4954 // entire buffer was written to the audio HAL
4955 if (!audio_has_proportional_frames(mFormat) &&
4956 (mType == OFFLOAD) && (mBytesWritten < mBufferSize)) {
4957 mSleepTimeUs = kDirectMinSleepTimeUs;
4958 } else {
4959 mSleepTimeUs = mActiveSleepTimeUs;
4960 }
Eric Laurent81784c32012-11-19 14:55:58 -08004961 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004962 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004963 }
Phil Burkfdb3c072016-02-09 10:47:02 -08004964 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08004965 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004966 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004967 }
4968}
4969
Eric Laurentd1f69b02014-12-15 14:33:13 -08004970void AudioFlinger::DirectOutputThread::threadLoop_exit()
4971{
4972 {
4973 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004974 for (size_t i = 0; i < mTracks.size(); i++) {
4975 if (mTracks[i]->isFlushPending()) {
4976 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004977 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004978 }
4979 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004980 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004981 flushHw_l();
4982 }
4983 }
4984 PlaybackThread::threadLoop_exit();
4985}
4986
4987// must be called with thread mutex locked
4988bool AudioFlinger::DirectOutputThread::shouldStandby_l()
4989{
4990 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07004991 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004992
4993 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
4994 // after a timeout and we will enter standby then.
4995 if (mTracks.size() > 0) {
4996 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07004997 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
4998 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004999 }
5000
Eric Laurent5cff4032015-05-26 13:49:58 -07005001 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005002}
5003
Eric Laurent81784c32012-11-19 14:55:58 -08005004// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005005int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Andy Hunge8a1ced2014-05-09 15:02:21 -07005006 audio_format_t format __unused, int sessionId __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005007{
5008 return 0;
5009}
5010
5011// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005012void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005013{
5014}
5015
Eric Laurent10351942014-05-08 18:49:52 -07005016// checkForNewParameter_l() must be called with ThreadBase::mLock held
5017bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5018 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005019{
5020 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005021 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005022
Eric Laurent10351942014-05-08 18:49:52 -07005023 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005024
Eric Laurent10351942014-05-08 18:49:52 -07005025 AudioParameter param = AudioParameter(keyValuePair);
5026 int value;
5027 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5028 // forward device change to effects that have requested to be
5029 // aware of attached audio device.
5030 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005031 a2dpDeviceChanged =
5032 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005033 mOutDevice = value;
5034 for (size_t i = 0; i < mEffectChains.size(); i++) {
5035 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005036 }
5037 }
Eric Laurent81784c32012-11-19 14:55:58 -08005038 }
Eric Laurent10351942014-05-08 18:49:52 -07005039 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5040 // do not accept frame count changes if tracks are open as the track buffer
5041 // size depends on frame count and correct behavior would not be garantied
5042 // if frame count is changed after track creation
5043 if (!mTracks.isEmpty()) {
5044 status = INVALID_OPERATION;
5045 } else {
5046 reconfig = true;
5047 }
5048 }
5049 if (status == NO_ERROR) {
5050 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5051 keyValuePair.string());
5052 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005053 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005054 mStandby = true;
5055 mBytesWritten = 0;
5056 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
5057 keyValuePair.string());
5058 }
5059 if (status == NO_ERROR && reconfig) {
5060 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005061 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005062 }
5063 }
5064
Eric Laurent42537be2016-01-08 17:16:42 -08005065 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005066}
5067
5068uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5069{
5070 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005071 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005072 time = PlaybackThread::activeSleepTimeUs();
5073 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005074 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005075 }
5076 return time;
5077}
5078
5079uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5080{
5081 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005082 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005083 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5084 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005085 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005086 }
5087 return time;
5088}
5089
5090uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5091{
5092 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005093 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005094 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5095 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005096 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005097 }
5098 return time;
5099}
5100
5101void AudioFlinger::DirectOutputThread::cacheParameters_l()
5102{
5103 PlaybackThread::cacheParameters_l();
5104
5105 // use shorter standby delay as on normal output to release
5106 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005107 // no delay on outputs with HW A/V sync
5108 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005109 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005110 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005111 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005112 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005113 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005114 }
Eric Laurent81784c32012-11-19 14:55:58 -08005115}
5116
Eric Laurente659ef42014-09-29 13:06:46 -07005117void AudioFlinger::DirectOutputThread::flushHw_l()
5118{
Phil Burk062e67a2015-02-11 13:40:50 -08005119 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005120 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005121 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005122}
5123
Eric Laurent81784c32012-11-19 14:55:58 -08005124// ----------------------------------------------------------------------------
5125
Eric Laurentbfb1b832013-01-07 09:53:42 -08005126AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005127 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005128 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005129 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005130 mWriteAckSequence(0),
5131 mDrainSequence(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005132{
5133}
5134
5135AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5136{
5137}
5138
5139void AudioFlinger::AsyncCallbackThread::onFirstRef()
5140{
5141 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5142}
5143
5144bool AudioFlinger::AsyncCallbackThread::threadLoop()
5145{
5146 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005147 uint32_t writeAckSequence;
5148 uint32_t drainSequence;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005149
5150 {
5151 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005152 while (!((mWriteAckSequence & 1) ||
5153 (mDrainSequence & 1) ||
5154 exitPending())) {
5155 mWaitWorkCV.wait(mLock);
5156 }
5157
Eric Laurentbfb1b832013-01-07 09:53:42 -08005158 if (exitPending()) {
5159 break;
5160 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005161 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5162 mWriteAckSequence, mDrainSequence);
5163 writeAckSequence = mWriteAckSequence;
5164 mWriteAckSequence &= ~1;
5165 drainSequence = mDrainSequence;
5166 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005167 }
5168 {
Eric Laurent4de95592013-09-26 15:28:21 -07005169 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5170 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005171 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005172 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005173 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005174 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005175 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005176 }
5177 }
5178 }
5179 }
5180 return false;
5181}
5182
5183void AudioFlinger::AsyncCallbackThread::exit()
5184{
5185 ALOGV("AsyncCallbackThread::exit");
5186 Mutex::Autolock _l(mLock);
5187 requestExit();
5188 mWaitWorkCV.broadcast();
5189}
5190
Eric Laurent3b4529e2013-09-05 18:09:19 -07005191void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005192{
5193 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005194 // bit 0 is cleared
5195 mWriteAckSequence = sequence << 1;
5196}
5197
5198void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5199{
5200 Mutex::Autolock _l(mLock);
5201 // ignore unexpected callbacks
5202 if (mWriteAckSequence & 2) {
5203 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204 mWaitWorkCV.signal();
5205 }
5206}
5207
Eric Laurent3b4529e2013-09-05 18:09:19 -07005208void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005209{
5210 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005211 // bit 0 is cleared
5212 mDrainSequence = sequence << 1;
5213}
5214
5215void AudioFlinger::AsyncCallbackThread::resetDraining()
5216{
5217 Mutex::Autolock _l(mLock);
5218 // ignore unexpected callbacks
5219 if (mDrainSequence & 2) {
5220 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221 mWaitWorkCV.signal();
5222 }
5223}
5224
5225
5226// ----------------------------------------------------------------------------
5227AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent51716182016-02-29 18:00:56 -08005228 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady,
5229 uint32_t bitRate)
5230 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady, bitRate),
Eric Laurentd7e59222013-11-15 12:02:28 -08005231 mPausedBytesRemaining(0)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005232{
Eric Laurentfd477972013-10-25 18:10:40 -07005233 //FIXME: mStandby should be set to true by ThreadBase constructor
5234 mStandby = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235}
5236
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237void AudioFlinger::OffloadThread::threadLoop_exit()
5238{
5239 if (mFlushPending || mHwPaused) {
5240 // If a flush is pending or track was paused, just discard buffered data
5241 flushHw_l();
5242 } else {
5243 mMixerStatus = MIXER_DRAIN_ALL;
5244 threadLoop_drain();
5245 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005246 if (mUseAsyncWrite) {
5247 ALOG_ASSERT(mCallbackThread != 0);
5248 mCallbackThread->exit();
5249 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005250 PlaybackThread::threadLoop_exit();
5251}
5252
5253AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5254 Vector< sp<Track> > *tracksToRemove
5255)
5256{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005257 size_t count = mActiveTracks.size();
5258
5259 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005260 bool doHwPause = false;
5261 bool doHwResume = false;
5262
Eric Laurentede6c3b2013-09-19 14:37:46 -07005263 ALOGV("OffloadThread::prepareTracks_l active tracks %d", count);
5264
Eric Laurentbfb1b832013-01-07 09:53:42 -08005265 // find out which tracks need to be processed
5266 for (size_t i = 0; i < count; i++) {
5267 sp<Track> t = mActiveTracks[i].promote();
5268 // The track died recently
5269 if (t == 0) {
5270 continue;
5271 }
5272 Track* const track = t.get();
5273 audio_track_cblk_t* cblk = track->cblk();
Eric Laurentfd477972013-10-25 18:10:40 -07005274 // Only consider last track started for volume and mixer state control.
5275 // In theory an older track could underrun and restart after the new one starts
5276 // but as we only care about the transition phase between two tracks on a
5277 // direct output, it is not a problem to ignore the underrun case.
5278 sp<Track> l = mLatestActiveTrack.promote();
5279 bool last = l.get() == track;
5280
Haynes Mathew George7844f672014-01-15 12:32:55 -08005281 if (track->isInvalid()) {
5282 ALOGW("An invalidated track shouldn't be in active list");
5283 tracksToRemove->add(track);
5284 continue;
5285 }
5286
5287 if (track->mState == TrackBase::IDLE) {
5288 ALOGW("An idle track shouldn't be in active list");
5289 continue;
5290 }
5291
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 if (track->isPausing()) {
5293 track->setPaused();
5294 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005295 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005296 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005297 mHwPaused = true;
5298 }
5299 // If we were part way through writing the mixbuffer to
5300 // the HAL we must save this until we resume
5301 // BUG - this will be wrong if a different track is made active,
5302 // in that case we want to discard the pending data in the
5303 // mixbuffer and tell the client to present it again when the
5304 // track is resumed
5305 mPausedWriteLength = mCurrentWriteLength;
5306 mPausedBytesRemaining = mBytesRemaining;
5307 mBytesRemaining = 0; // stop writing
5308 }
5309 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005310 } else if (track->isFlushPending()) {
Eric Laurent51716182016-02-29 18:00:56 -08005311 track->mRetryCount = kMaxTrackRetriesOffload;
Haynes Mathew George7844f672014-01-15 12:32:55 -08005312 track->flushAck();
5313 if (last) {
5314 mFlushPending = true;
5315 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005316 } else if (track->isResumePending()){
5317 track->resumeAck();
5318 if (last) {
5319 if (mPausedBytesRemaining) {
5320 // Need to continue write that was interrupted
5321 mCurrentWriteLength = mPausedWriteLength;
5322 mBytesRemaining = mPausedBytesRemaining;
5323 mPausedBytesRemaining = 0;
5324 }
5325 if (mHwPaused) {
5326 doHwResume = true;
5327 mHwPaused = false;
5328 // threadLoop_mix() will handle the case that we need to
5329 // resume an interrupted write
5330 }
5331 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005332 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005333
5334 // Do not handle new data in this iteration even if track->framesReady()
5335 mixerStatus = MIXER_TRACKS_ENABLED;
5336 }
5337 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005338 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005339 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340 if (track->mFillingUpStatus == Track::FS_FILLED) {
5341 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent1abbdb42013-09-13 17:00:08 -07005342 // make sure processVolume_l() will apply new volume even if 0
5343 mLeftVolFloat = mRightVolFloat = -1.0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 }
5345
5346 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005347 sp<Track> previousTrack = mPreviousTrack.promote();
5348 if (previousTrack != 0) {
5349 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005350 // Flush any data still being written from last track
5351 mBytesRemaining = 0;
5352 if (mPausedBytesRemaining) {
5353 // Last track was paused so we also need to flush saved
5354 // mixbuffer state and invalidate track so that it will
5355 // re-submit that unwritten data when it is next resumed
5356 mPausedBytesRemaining = 0;
5357 // Invalidate is a bit drastic - would be more efficient
5358 // to have a flag to tell client that some of the
5359 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005360 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005361 }
5362 // flush data already sent to the DSP if changing audio session as audio
5363 // comes from a different source. Also invalidate previous track to force a
5364 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005365 if (previousTrack->sessionId() != track->sessionId()) {
5366 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005367 }
5368 }
5369 }
5370 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005371 // reset retry count
5372 track->mRetryCount = kMaxTrackRetriesOffload;
5373 mActiveTrack = t;
5374 mixerStatus = MIXER_TRACKS_READY;
5375 }
5376 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005377 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005378 if (track->isStopping_1()) {
5379 // Hardware buffer can hold a large amount of audio so we must
5380 // wait for all current track's data to drain before we say
5381 // that the track is stopped.
5382 if (mBytesRemaining == 0) {
5383 // Only start draining when all data in mixbuffer
5384 // has been written
5385 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5386 track->mState = TrackBase::STOPPING_2; // so presentation completes after drain
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005387 // do not drain if no data was ever sent to HAL (mStandby == true)
5388 if (last && !mStandby) {
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005389 // do not modify drain sequence if we are already draining. This happens
5390 // when resuming from pause after drain.
5391 if ((mDrainSequence & 1) == 0) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005392 mSleepTimeUs = 0;
5393 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005394 mixerStatus = MIXER_DRAIN_TRACK;
5395 mDrainSequence += 2;
5396 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 if (mHwPaused) {
5398 // It is possible to move from PAUSED to STOPPING_1 without
5399 // a resume so we must ensure hardware is running
Eric Laurent1b9f9b12013-11-12 19:10:17 -08005400 doHwResume = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401 mHwPaused = false;
5402 }
5403 }
5404 }
5405 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005406 // Drain has completed or we are in standby, signal presentation complete
5407 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005408 track->mState = TrackBase::STOPPED;
5409 size_t audioHALFrames =
5410 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005411 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005412 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 track->presentationComplete(framesWritten, audioHALFrames);
5414 track->reset();
5415 tracksToRemove->add(track);
5416 }
5417 } else {
5418 // No buffers for this track. Give it a few chances to
5419 // fill a buffer, then remove it from active list.
5420 if (--(track->mRetryCount) <= 0) {
5421 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5422 track->name());
5423 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005424 // indicate to client process that the track was disabled because of underrun;
5425 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005426 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427 } else if (last){
5428 mixerStatus = MIXER_TRACKS_ENABLED;
5429 }
5430 }
5431 }
5432 // compute volume for this track
5433 processVolume_l(track, last);
5434 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005435
Eric Laurentea0fade2013-10-04 16:23:48 -07005436 // make sure the pause/flush/resume sequence is executed in the right order.
5437 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5438 // before flush and then resume HW. This can happen in case of pause/flush/resume
5439 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005440 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Eric Laurent972a1732013-09-04 09:42:59 -07005441 mOutput->stream->pause(mOutput->stream);
5442 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005443 if (mFlushPending) {
5444 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005445 }
Eric Laurentfd477972013-10-25 18:10:40 -07005446 if (!mStandby && doHwResume) {
Eric Laurent972a1732013-09-04 09:42:59 -07005447 mOutput->stream->resume(mOutput->stream);
5448 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005449
Eric Laurentbfb1b832013-01-07 09:53:42 -08005450 // remove all the tracks that need to be...
5451 removeTracks_l(*tracksToRemove);
5452
5453 return mixerStatus;
5454}
5455
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456// must be called with thread mutex locked
5457bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5458{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005459 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5460 mWriteAckSequence, mDrainSequence);
5461 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462 return true;
5463 }
5464 return false;
5465}
5466
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5468{
5469 Mutex::Autolock _l(mLock);
5470 return waitingAsyncCallback_l();
5471}
5472
5473void AudioFlinger::OffloadThread::flushHw_l()
5474{
Eric Laurente659ef42014-09-29 13:06:46 -07005475 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005476 // Flush anything still waiting in the mixbuffer
5477 mCurrentWriteLength = 0;
5478 mBytesRemaining = 0;
5479 mPausedWriteLength = 0;
5480 mPausedBytesRemaining = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005481
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005483 // discard any pending drain or write ack by incrementing sequence
5484 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5485 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005486 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005487 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5488 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005489 }
5490}
5491
Eric Laurent51716182016-02-29 18:00:56 -08005492uint32_t AudioFlinger::OffloadThread::activeSleepTimeUs() const
5493{
5494 uint32_t time;
5495 if (audio_has_proportional_frames(mFormat)) {
5496 time = PlaybackThread::activeSleepTimeUs();
5497 } else {
5498 // sleep time is half the duration of an audio HAL buffer.
5499 // Note: This can be problematic in case of underrun with variable bit rate and
5500 // current rate is much less than initial rate.
5501 time = (uint32_t)max(kDirectMinSleepTimeUs, mBufferDurationUs / 2);
5502 }
5503 return time;
5504}
5505
Eric Laurentbfb1b832013-01-07 09:53:42 -08005506// ----------------------------------------------------------------------------
5507
Eric Laurent81784c32012-11-19 14:55:58 -08005508AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005509 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005510 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005511 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005512 mWaitTimeMs(UINT_MAX)
5513{
5514 addOutputTrack(mainThread);
5515}
5516
5517AudioFlinger::DuplicatingThread::~DuplicatingThread()
5518{
5519 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5520 mOutputTracks[i]->destroy();
5521 }
5522}
5523
5524void AudioFlinger::DuplicatingThread::threadLoop_mix()
5525{
5526 // mix buffers...
5527 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005528 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005529 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005530 if (mMixerBufferValid) {
5531 memset(mMixerBuffer, 0, mMixerBufferSize);
5532 } else {
5533 memset(mSinkBuffer, 0, mSinkBufferSize);
5534 }
Eric Laurent81784c32012-11-19 14:55:58 -08005535 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005536 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005537 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005538 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005539 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005540}
5541
5542void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5543{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005544 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005545 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005546 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005547 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005548 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005549 }
5550 } else if (mBytesWritten != 0) {
5551 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5552 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005553 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005554 } else {
5555 // flush remaining overflow buffers in output tracks
5556 writeFrames = 0;
5557 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005558 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005559 }
5560}
5561
Eric Laurentbfb1b832013-01-07 09:53:42 -08005562ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005563{
5564 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005565 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005566 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005567 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005568 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005569}
5570
5571void AudioFlinger::DuplicatingThread::threadLoop_standby()
5572{
5573 // DuplicatingThread implements standby by stopping all tracks
5574 for (size_t i = 0; i < outputTracks.size(); i++) {
5575 outputTracks[i]->stop();
5576 }
5577}
5578
5579void AudioFlinger::DuplicatingThread::saveOutputTracks()
5580{
5581 outputTracks = mOutputTracks;
5582}
5583
5584void AudioFlinger::DuplicatingThread::clearOutputTracks()
5585{
5586 outputTracks.clear();
5587}
5588
5589void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5590{
5591 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005592 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5593 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5594 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5595 const size_t frameCount =
5596 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5597 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5598 // from different OutputTracks and their associated MixerThreads (e.g. one may
5599 // nearly empty and the other may be dropping data).
5600
5601 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005602 this,
5603 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005604 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005605 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005606 frameCount,
5607 IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08005608 if (outputTrack->cblk() != NULL) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005609 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurent81784c32012-11-19 14:55:58 -08005610 mOutputTracks.add(outputTrack);
Andy Hungc25b84a2015-01-14 19:04:10 -08005611 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005612 updateWaitTime_l();
5613 }
5614}
5615
5616void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5617{
5618 Mutex::Autolock _l(mLock);
5619 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5620 if (mOutputTracks[i]->thread() == thread) {
5621 mOutputTracks[i]->destroy();
5622 mOutputTracks.removeAt(i);
5623 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005624 if (thread->getOutput() == mOutput) {
5625 mOutput = NULL;
5626 }
Eric Laurent81784c32012-11-19 14:55:58 -08005627 return;
5628 }
5629 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005630 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005631}
5632
5633// caller must hold mLock
5634void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5635{
5636 mWaitTimeMs = UINT_MAX;
5637 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5638 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5639 if (strong != 0) {
5640 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5641 if (waitTimeMs < mWaitTimeMs) {
5642 mWaitTimeMs = waitTimeMs;
5643 }
5644 }
5645 }
5646}
5647
5648
5649bool AudioFlinger::DuplicatingThread::outputsReady(
5650 const SortedVector< sp<OutputTrack> > &outputTracks)
5651{
5652 for (size_t i = 0; i < outputTracks.size(); i++) {
5653 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5654 if (thread == 0) {
5655 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5656 outputTracks[i].get());
5657 return false;
5658 }
5659 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5660 // see note at standby() declaration
5661 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5662 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5663 thread.get());
5664 return false;
5665 }
5666 }
5667 return true;
5668}
5669
5670uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5671{
5672 return (mWaitTimeMs * 1000) / 2;
5673}
5674
5675void AudioFlinger::DuplicatingThread::cacheParameters_l()
5676{
5677 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5678 updateWaitTime_l();
5679
5680 MixerThread::cacheParameters_l();
5681}
5682
5683// ----------------------------------------------------------------------------
5684// Record
5685// ----------------------------------------------------------------------------
5686
5687AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5688 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005689 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005690 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005691 audio_devices_t inDevice,
5692 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005693#ifdef TEE_SINK
5694 , const sp<NBAIO_Sink>& teeSink
5695#endif
5696 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005697 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005698 mInput(input), mActiveTracksGen(0), mRsmpInBuffer(NULL),
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005699 // mRsmpInFrames and mRsmpInFramesP2 are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005700 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005701#ifdef TEE_SINK
5702 , mTeeSink(teeSink)
5703#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005704 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5705 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005706 // mFastCapture below
5707 , mFastCaptureFutex(0)
5708 // mInputSource
5709 // mPipeSink
5710 // mPipeSource
5711 , mPipeFramesP2(0)
5712 // mPipeMemory
5713 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005714 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005715{
Glenn Kastend7dca052015-03-05 16:05:54 -08005716 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5717 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005718
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005719 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005720
5721 // create an NBAIO source for the HAL input stream, and negotiate
5722 mInputSource = new AudioStreamInSource(input->stream);
5723 size_t numCounterOffers = 0;
5724 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
5725 ssize_t index = mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
5726 ALOG_ASSERT(index == 0);
5727
5728 // initialize fast capture depending on configuration
5729 bool initFastCapture;
5730 switch (kUseFastCapture) {
5731 case FastCapture_Never:
5732 initFastCapture = false;
5733 break;
5734 case FastCapture_Always:
5735 initFastCapture = true;
5736 break;
5737 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005738 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005739 break;
5740 // case FastCapture_Dynamic:
5741 }
5742
5743 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005744 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005745 NBAIO_Format format = mInputSource->format();
Glenn Kasten49d00ad2014-07-21 11:22:03 -07005746 size_t pipeFramesP2 = roundup(mSampleRate / 25); // double-buffering of 20 ms each
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005747 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5748 void *pipeBuffer;
5749 const sp<MemoryDealer> roHeap(readOnlyHeap());
5750 sp<IMemory> pipeMemory;
5751 if ((roHeap == 0) ||
5752 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5753 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5754 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5755 goto failed;
5756 }
5757 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5758 memset(pipeBuffer, 0, pipeSize);
5759 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5760 const NBAIO_Format offers[1] = {format};
5761 size_t numCounterOffers = 0;
5762 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5763 ALOG_ASSERT(index == 0);
5764 mPipeSink = pipe;
5765 PipeReader *pipeReader = new PipeReader(*pipe);
5766 numCounterOffers = 0;
5767 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5768 ALOG_ASSERT(index == 0);
5769 mPipeSource = pipeReader;
5770 mPipeFramesP2 = pipeFramesP2;
5771 mPipeMemory = pipeMemory;
5772
5773 // create fast capture
5774 mFastCapture = new FastCapture();
5775 FastCaptureStateQueue *sq = mFastCapture->sq();
5776#ifdef STATE_QUEUE_DUMP
5777 // FIXME
5778#endif
5779 FastCaptureState *state = sq->begin();
5780 state->mCblk = NULL;
5781 state->mInputSource = mInputSource.get();
5782 state->mInputSourceGen++;
5783 state->mPipeSink = pipe;
5784 state->mPipeSinkGen++;
5785 state->mFrameCount = mFrameCount;
5786 state->mCommand = FastCaptureState::COLD_IDLE;
5787 // already done in constructor initialization list
5788 //mFastCaptureFutex = 0;
5789 state->mColdFutexAddr = &mFastCaptureFutex;
5790 state->mColdGen++;
5791 state->mDumpState = &mFastCaptureDumpState;
5792#ifdef TEE_SINK
5793 // FIXME
5794#endif
5795 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5796 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5797 sq->end();
5798 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5799
5800 // start the fast capture
5801 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5802 pid_t tid = mFastCapture->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07005803 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005804#ifdef AUDIO_WATCHDOG
5805 // FIXME
5806#endif
5807
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005808 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005809 }
5810failed: ;
5811
5812 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005813}
5814
Eric Laurent81784c32012-11-19 14:55:58 -08005815AudioFlinger::RecordThread::~RecordThread()
5816{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005817 if (mFastCapture != 0) {
5818 FastCaptureStateQueue *sq = mFastCapture->sq();
5819 FastCaptureState *state = sq->begin();
5820 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5821 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5822 if (old == -1) {
5823 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5824 }
5825 }
5826 state->mCommand = FastCaptureState::EXIT;
5827 sq->end();
5828 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5829 mFastCapture->join();
5830 mFastCapture.clear();
5831 }
5832 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005833 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005834 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005835}
5836
5837void AudioFlinger::RecordThread::onFirstRef()
5838{
Glenn Kastend7dca052015-03-05 16:05:54 -08005839 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005840}
5841
Eric Laurent81784c32012-11-19 14:55:58 -08005842bool AudioFlinger::RecordThread::threadLoop()
5843{
Eric Laurent81784c32012-11-19 14:55:58 -08005844 nsecs_t lastWarning = 0;
5845
5846 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005847
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005848reacquire_wakelock:
5849 sp<RecordTrack> activeTrack;
Glenn Kasten2b806402013-11-20 16:37:38 -08005850 int activeTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005851 {
5852 Mutex::Autolock _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08005853 size_t size = mActiveTracks.size();
5854 activeTracksGen = mActiveTracksGen;
5855 if (size > 0) {
5856 // FIXME an arbitrary choice
5857 activeTrack = mActiveTracks[0];
5858 acquireWakeLock_l(activeTrack->uid());
5859 if (size > 1) {
5860 SortedVector<int> tmp;
5861 for (size_t i = 0; i < size; i++) {
5862 tmp.add(mActiveTracks[i]->uid());
5863 }
5864 updateWakeLockUids_l(tmp);
5865 }
5866 } else {
5867 acquireWakeLock_l(-1);
5868 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005869 }
5870
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005871 // used to request a deferred sleep, to be executed later while mutex is unlocked
5872 uint32_t sleepUs = 0;
5873
5874 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005875 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005876 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005877
Glenn Kasten5edadd42013-08-14 16:30:49 -07005878 // sleep with mutex unlocked
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005879 if (sleepUs > 0) {
Glenn Kastene7754022014-10-31 12:11:26 -07005880 ATRACE_BEGIN("sleep");
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005881 usleep(sleepUs);
Glenn Kastene7754022014-10-31 12:11:26 -07005882 ATRACE_END();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005883 sleepUs = 0;
Glenn Kasten5edadd42013-08-14 16:30:49 -07005884 }
5885
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005886 // activeTracks accumulates a copy of a subset of mActiveTracks
5887 Vector< sp<RecordTrack> > activeTracks;
5888
Glenn Kasten735f45f2014-08-18 15:51:59 -07005889 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005890 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005891
Glenn Kasten735f45f2014-08-18 15:51:59 -07005892 // reference to a fast track which is about to be removed
5893 sp<RecordTrack> fastTrackToRemove;
5894
Eric Laurent81784c32012-11-19 14:55:58 -08005895 { // scope for mLock
5896 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005897
Eric Laurent021cf962014-05-13 10:18:14 -07005898 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005899
Eric Laurent000a4192014-01-29 15:17:32 -08005900 // check exitPending here because checkForNewParameters_l() and
5901 // checkForNewParameters_l() can temporarily release mLock
5902 if (exitPending()) {
5903 break;
5904 }
5905
Glenn Kasten2b806402013-11-20 16:37:38 -08005906 // if no active track(s), then standby and release wakelock
5907 size_t size = mActiveTracks.size();
5908 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07005909 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005910 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08005911 releaseWakeLock_l();
5912 ALOGV("RecordThread: loop stopping");
5913 // go to sleep
5914 mWaitWorkCV.wait(mLock);
5915 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005916 goto reacquire_wakelock;
5917 }
5918
Glenn Kasten2b806402013-11-20 16:37:38 -08005919 if (mActiveTracksGen != activeTracksGen) {
5920 activeTracksGen = mActiveTracksGen;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005921 SortedVector<int> tmp;
Glenn Kasten2b806402013-11-20 16:37:38 -08005922 for (size_t i = 0; i < size; i++) {
5923 tmp.add(mActiveTracks[i]->uid());
5924 }
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005925 updateWakeLockUids_l(tmp);
Eric Laurent81784c32012-11-19 14:55:58 -08005926 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005927
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005928 bool doBroadcast = false;
5929 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07005930
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005931 activeTrack = mActiveTracks[i];
5932 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07005933 if (activeTrack->isFastTrack()) {
5934 ALOG_ASSERT(fastTrackToRemove == 0);
5935 fastTrackToRemove = activeTrack;
5936 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005937 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08005938 mActiveTracks.remove(activeTrack);
5939 mActiveTracksGen++;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005940 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07005941 continue;
5942 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005943
5944 TrackBase::track_state activeTrackState = activeTrack->mState;
5945 switch (activeTrackState) {
5946
5947 case TrackBase::PAUSING:
5948 mActiveTracks.remove(activeTrack);
5949 mActiveTracksGen++;
5950 doBroadcast = true;
5951 size--;
5952 continue;
5953
5954 case TrackBase::STARTING_1:
5955 sleepUs = 10000;
5956 i++;
5957 continue;
5958
5959 case TrackBase::STARTING_2:
5960 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005961 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07005962 activeTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005963 break;
5964
5965 case TrackBase::ACTIVE:
5966 break;
5967
5968 case TrackBase::IDLE:
5969 i++;
5970 continue;
5971
5972 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005973 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07005974 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005975
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005976 activeTracks.add(activeTrack);
5977 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07005978
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005979 if (activeTrack->isFastTrack()) {
5980 ALOG_ASSERT(!mFastTrackAvail);
5981 ALOG_ASSERT(fastTrack == 0);
5982 fastTrack = activeTrack;
5983 }
Glenn Kasten9e982352013-08-14 14:39:50 -07005984 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005985 if (doBroadcast) {
5986 mStartStopCond.broadcast();
5987 }
5988
5989 // sleep if there are no active tracks to process
5990 if (activeTracks.size() == 0) {
5991 if (sleepUs == 0) {
5992 sleepUs = kRecordThreadSleepUs;
5993 }
5994 continue;
5995 }
5996 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07005997
Eric Laurent81784c32012-11-19 14:55:58 -08005998 lockEffectChains_l(effectChains);
5999 }
6000
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006001 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006002
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006003 size_t size = effectChains.size();
6004 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006005 // thread mutex is not locked, but effect chain is locked
6006 effectChains[i]->process_l();
6007 }
6008
Glenn Kasten735f45f2014-08-18 15:51:59 -07006009 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006010 if (mFastCapture != 0) {
6011 FastCaptureStateQueue *sq = mFastCapture->sq();
6012 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006013 bool didModify = false;
6014 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006015 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6016 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6017 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6018 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6019 if (old == -1) {
6020 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6021 }
6022 }
6023 state->mCommand = FastCaptureState::READ_WRITE;
6024#if 0 // FIXME
6025 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006026 FastThreadDumpState::kSamplingNforLowRamDevice :
6027 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006028#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006029 didModify = true;
6030 }
6031 audio_track_cblk_t *cblkOld = state->mCblk;
6032 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6033 if (cblkNew != cblkOld) {
6034 state->mCblk = cblkNew;
6035 // block until acked if removing a fast track
6036 if (cblkOld != NULL) {
6037 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6038 }
6039 didModify = true;
6040 }
6041 sq->end(didModify);
6042 if (didModify) {
6043 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006044#if 0
6045 if (kUseFastCapture == FastCapture_Dynamic) {
6046 mNormalSource = mPipeSource;
6047 }
6048#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006049 }
6050 }
6051
Glenn Kasten735f45f2014-08-18 15:51:59 -07006052 // now run the fast track destructor with thread mutex unlocked
6053 fastTrackToRemove.clear();
6054
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006055 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6056 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6057 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6058 // If destination is non-contiguous, first read past the nominal end of buffer, then
6059 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006060
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006061 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006062 ssize_t framesRead;
6063
6064 // If an NBAIO source is present, use it to read the normal capture's data
6065 if (mPipeSource != 0) {
6066 size_t framesToRead = mBufferSize / mFrameSize;
Andy Hung57446612015-04-19 23:56:46 -07006067 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006068 framesToRead);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006069 if (framesRead == 0) {
6070 // since pipe is non-blocking, simulate blocking input
6071 sleepUs = (framesToRead * 1000000LL) / mSampleRate;
6072 }
6073 // otherwise use the HAL / AudioStreamIn directly
6074 } else {
6075 ssize_t bytesRead = mInput->stream->read(mInput->stream,
Andy Hung57446612015-04-19 23:56:46 -07006076 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006077 if (bytesRead < 0) {
6078 framesRead = bytesRead;
6079 } else {
6080 framesRead = bytesRead / mFrameSize;
6081 }
6082 }
6083
Andy Hung3f0c9022016-01-15 17:49:46 -08006084 // Update server timestamp with server stats
6085 // systemTime() is optional if the hardware supports timestamps.
6086 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6087 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6088
6089 // Update server timestamp with kernel stats
6090 if (mInput->stream->get_capture_position != nullptr) {
6091 int64_t position, time;
6092 int ret = mInput->stream->get_capture_position(mInput->stream, &position, &time);
6093 if (ret == NO_ERROR) {
6094 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6095 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6096 // Note: In general record buffers should tend to be empty in
6097 // a properly running pipeline.
6098 //
6099 // Also, it is not advantageous to call get_presentation_position during the read
6100 // as the read obtains a lock, preventing the timestamp call from executing.
6101 }
6102 }
6103 // Use this to track timestamp information
6104 // ALOGD("%s", mTimestamp.toString().c_str());
6105
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006106 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
6107 ALOGE("read failed: framesRead=%d", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006108 // Force input into standby so that it tries to recover at next read attempt
6109 inputStandBy();
6110 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006111 }
6112 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006113 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006114 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006115 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006116
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006118 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006119 }
6120 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006121 {
6122 size_t part1 = mRsmpInFramesP2 - rear;
6123 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006124 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006125 (framesRead - part1) * mFrameSize);
6126 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006127 }
6128 rear = mRsmpInRear += framesRead;
6129
6130 size = activeTracks.size();
6131 // loop over each active track
6132 for (size_t i = 0; i < size; i++) {
6133 activeTrack = activeTracks[i];
6134
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006135 // skip fast tracks, as those are handled directly by FastCapture
6136 if (activeTrack->isFastTrack()) {
6137 continue;
6138 }
6139
Andy Hung73c02e42015-03-29 01:13:58 -07006140 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006141 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6142
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006143 enum {
6144 OVERRUN_UNKNOWN,
6145 OVERRUN_TRUE,
6146 OVERRUN_FALSE
6147 } overrun = OVERRUN_UNKNOWN;
6148
6149 // loop over getNextBuffer to handle circular sink
6150 for (;;) {
6151
6152 activeTrack->mSink.frameCount = ~0;
6153 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6154 size_t framesOut = activeTrack->mSink.frameCount;
6155 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6156
Andy Hung73c02e42015-03-29 01:13:58 -07006157 // check available frames and handle overrun conditions
6158 // if the record track isn't draining fast enough.
6159 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006160 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006161 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6162 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006163 overrun = OVERRUN_TRUE;
6164 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006165 if (framesOut == 0 || framesIn == 0) {
6166 break;
6167 }
6168
Andy Hung6770c6f2015-04-07 13:43:36 -07006169 // Don't allow framesOut to be larger than what is possible with resampling
6170 // from framesIn.
6171 // This isn't strictly necessary but helps limit buffer resizing in
6172 // RecordBufferConverter. TODO: remove when no longer needed.
6173 framesOut = min(framesOut,
6174 destinationFramesPossible(
6175 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006176 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6177 framesOut = activeTrack->mRecordBufferConverter->convert(
6178 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006179
6180 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6181 overrun = OVERRUN_FALSE;
6182 }
6183
6184 if (activeTrack->mFramesToDrop == 0) {
6185 if (framesOut > 0) {
6186 activeTrack->mSink.frameCount = framesOut;
6187 activeTrack->releaseBuffer(&activeTrack->mSink);
6188 }
6189 } else {
6190 // FIXME could do a partial drop of framesOut
6191 if (activeTrack->mFramesToDrop > 0) {
6192 activeTrack->mFramesToDrop -= framesOut;
6193 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006194 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 }
6196 } else {
6197 activeTrack->mFramesToDrop += framesOut;
6198 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6199 activeTrack->mSyncStartEvent->isCancelled()) {
6200 ALOGW("Synced record %s, session %d, trigger session %d",
6201 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6202 activeTrack->sessionId(),
6203 (activeTrack->mSyncStartEvent != 0) ?
6204 activeTrack->mSyncStartEvent->triggerSession() : 0);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006205 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006206 }
6207 }
6208 }
6209
6210 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006211 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006212 }
6213 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006214
6215 switch (overrun) {
6216 case OVERRUN_TRUE:
6217 // client isn't retrieving buffers fast enough
6218 if (!activeTrack->setOverflow()) {
6219 nsecs_t now = systemTime();
6220 // FIXME should lastWarning per track?
6221 if ((now - lastWarning) > kWarningThrottleNs) {
6222 ALOGW("RecordThread: buffer overflow");
6223 lastWarning = now;
6224 }
6225 }
6226 break;
6227 case OVERRUN_FALSE:
6228 activeTrack->clearOverflow();
6229 break;
6230 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006231 break;
6232 }
6233
Andy Hung3f0c9022016-01-15 17:49:46 -08006234 // update frame information and push timestamp out
6235 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006236 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006237 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6238 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006239 }
6240
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006241unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006242 // enable changes in effect chain
6243 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006244 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006245 }
6246
Glenn Kasten93e471f2013-08-19 08:40:07 -07006247 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006248
6249 {
6250 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006251 for (size_t i = 0; i < mTracks.size(); i++) {
6252 sp<RecordTrack> track = mTracks[i];
6253 track->invalidate();
6254 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006255 mActiveTracks.clear();
6256 mActiveTracksGen++;
Eric Laurent81784c32012-11-19 14:55:58 -08006257 mStartStopCond.broadcast();
6258 }
6259
6260 releaseWakeLock();
6261
6262 ALOGV("RecordThread %p exiting", this);
6263 return false;
6264}
6265
Glenn Kasten93e471f2013-08-19 08:40:07 -07006266void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006267{
6268 if (!mStandby) {
6269 inputStandBy();
6270 mStandby = true;
6271 }
6272}
6273
6274void AudioFlinger::RecordThread::inputStandBy()
6275{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006276 // Idle the fast capture if it's currently running
6277 if (mFastCapture != 0) {
6278 FastCaptureStateQueue *sq = mFastCapture->sq();
6279 FastCaptureState *state = sq->begin();
6280 if (!(state->mCommand & FastCaptureState::IDLE)) {
6281 state->mCommand = FastCaptureState::COLD_IDLE;
6282 state->mColdFutexAddr = &mFastCaptureFutex;
6283 state->mColdGen++;
6284 mFastCaptureFutex = 0;
6285 sq->end();
6286 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6287 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6288#if 0
6289 if (kUseFastCapture == FastCapture_Dynamic) {
6290 // FIXME
6291 }
6292#endif
6293#ifdef AUDIO_WATCHDOG
6294 // FIXME
6295#endif
6296 } else {
6297 sq->end(false /*didModify*/);
6298 }
6299 }
Eric Laurent81784c32012-11-19 14:55:58 -08006300 mInput->stream->common.standby(&mInput->stream->common);
6301}
6302
Glenn Kasten05997e22014-03-13 15:08:33 -07006303// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006304sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006305 const sp<AudioFlinger::Client>& client,
6306 uint32_t sampleRate,
6307 audio_format_t format,
6308 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006309 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08006310 int sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006311 size_t *notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006312 int uid,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -07006313 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006314 pid_t tid,
6315 status_t *status)
6316{
Glenn Kasten74935e42013-12-19 08:56:45 -08006317 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006318 sp<RecordTrack> track;
6319 status_t lStatus;
6320
Glenn Kasten90e58b12013-07-31 16:16:02 -07006321 // client expresses a preference for FAST, but we get the final say
6322 if (*flags & IAudioFlinger::TRACK_FAST) {
6323 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006324 // we formerly checked for a callback handler (non-0 tid),
6325 // but that is no longer required for TRANSFER_OBTAIN mode
6326 //
Glenn Kasten74105912014-07-03 12:28:53 -07006327 // frame count is not specified, or is exactly the pipe depth
6328 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006329 // PCM data
6330 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006331 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006332 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006333 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006334 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006335 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006336 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006337 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006338 hasFastCapture() &&
6339 // there are sufficient fast track slots available
6340 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006341 ) {
Glenn Kasten74105912014-07-03 12:28:53 -07006342 ALOGV("AUDIO_INPUT_FLAG_FAST accepted: frameCount=%u mFrameCount=%u",
Glenn Kasten90e58b12013-07-31 16:16:02 -07006343 frameCount, mFrameCount);
6344 } else {
Glenn Kasten74105912014-07-03 12:28:53 -07006345 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%u mFrameCount=%u mPipeFramesP2=%u "
6346 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006347 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006348 frameCount, mFrameCount, mPipeFramesP2,
6349 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6350 hasFastCapture(), tid, mFastTrackAvail);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006351 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten74105912014-07-03 12:28:53 -07006352 }
6353 }
6354
6355 // compute track buffer size in frames, and suggest the notification frame count
6356 if (*flags & IAudioFlinger::TRACK_FAST) {
6357 // fast track: frame count is exactly the pipe depth
6358 frameCount = mPipeFramesP2;
6359 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6360 *notificationFrames = mFrameCount;
6361 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006362 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6363 // or 20 ms if there is a fast capture
6364 // TODO This could be a roundupRatio inline, and const
6365 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6366 * sampleRate + mSampleRate - 1) / mSampleRate;
6367 // minimum number of notification periods is at least kMinNotifications,
6368 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6369 static const size_t kMinNotifications = 3;
6370 static const uint32_t kMinMs = 30;
6371 // TODO This could be a roundupRatio inline
6372 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6373 // TODO This could be a roundupRatio inline
6374 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6375 maxNotificationFrames;
6376 const size_t minFrameCount = maxNotificationFrames *
6377 max(kMinNotifications, minNotificationsByMs);
6378 frameCount = max(frameCount, minFrameCount);
6379 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6380 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006381 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006382 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006383 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006384
Glenn Kasten15e57982013-09-24 11:52:37 -07006385 lStatus = initCheck();
6386 if (lStatus != NO_ERROR) {
6387 ALOGE("createRecordTrack_l() audio driver not initialized");
6388 goto Exit;
6389 }
Eric Laurent81784c32012-11-19 14:55:58 -08006390
6391 { // scope for mLock
6392 Mutex::Autolock _l(mLock);
6393
6394 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006395 format, channelMask, frameCount, NULL, sessionId, uid,
6396 *flags, TrackBase::TYPE_DEFAULT);
Eric Laurent81784c32012-11-19 14:55:58 -08006397
Glenn Kasten03003332013-08-06 15:40:54 -07006398 lStatus = track->initCheck();
6399 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006400 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006401 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006402 goto Exit;
6403 }
6404 mTracks.add(track);
6405
6406 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6407 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6408 mAudioFlinger->btNrecIsOff();
6409 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6410 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006411
6412 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
6413 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6414 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6415 // so ask activity manager to do this on our behalf
6416 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6417 }
Eric Laurent81784c32012-11-19 14:55:58 -08006418 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006419
Eric Laurent81784c32012-11-19 14:55:58 -08006420 lStatus = NO_ERROR;
6421
6422Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006423 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006424 return track;
6425}
6426
6427status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6428 AudioSystem::sync_event_t event,
6429 int triggerSession)
6430{
6431 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6432 sp<ThreadBase> strongMe = this;
6433 status_t status = NO_ERROR;
6434
6435 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006436 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006437 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006439 triggerSession,
6440 recordTrack->sessionId(),
6441 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006442 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006443 // Sync event can be cancelled by the trigger session if the track is not in a
6444 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006445 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006446 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006447 } else {
6448 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006450 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006451 }
6452 }
6453
6454 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006455 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006456 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006457 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6458 if (recordTrack->mState == TrackBase::PAUSING) {
6459 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006460 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006461 } else {
6462 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006463 }
6464 return status;
6465 }
6466
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006467 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6468 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6469 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006470 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006471 mActiveTracks.add(recordTrack);
6472 mActiveTracksGen++;
Eric Laurent83b88082014-06-20 18:31:16 -07006473 status_t status = NO_ERROR;
6474 if (recordTrack->isExternalTrack()) {
6475 mLock.unlock();
Eric Laurent4dc68062014-07-28 17:26:49 -07006476 status = AudioSystem::startInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006477 mLock.lock();
6478 // FIXME should verify that recordTrack is still in mActiveTracks
6479 if (status != NO_ERROR) {
6480 mActiveTracks.remove(recordTrack);
6481 mActiveTracksGen++;
6482 recordTrack->clearSyncStartEvent();
6483 ALOGV("RecordThread::start error %d", status);
6484 return status;
6485 }
Eric Laurent81784c32012-11-19 14:55:58 -08006486 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006487 // Catch up with current buffer indices if thread is already running.
6488 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6489 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6490 // see previously buffered data before it called start(), but with greater risk of overrun.
6491
Andy Hung73c02e42015-03-29 01:13:58 -07006492 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006493 // clear any converter state as new data will be discontinuous
6494 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006495 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006496 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006497 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006498 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006499 ALOGV("Record failed to start");
6500 status = BAD_VALUE;
6501 goto startError;
6502 }
Eric Laurent81784c32012-11-19 14:55:58 -08006503 return status;
6504 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006505
Eric Laurent81784c32012-11-19 14:55:58 -08006506startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006507 if (recordTrack->isExternalTrack()) {
Eric Laurent4dc68062014-07-28 17:26:49 -07006508 AudioSystem::stopInput(mId, (audio_session_t)recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006509 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006510 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006511 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006512 return status;
6513}
6514
Eric Laurent81784c32012-11-19 14:55:58 -08006515void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6516{
6517 sp<SyncEvent> strongEvent = event.promote();
6518
6519 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006520 sp<RefBase> ptr = strongEvent->cookie().promote();
6521 if (ptr != 0) {
6522 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6523 recordTrack->handleSyncStartEvent(strongEvent);
6524 }
Eric Laurent81784c32012-11-19 14:55:58 -08006525 }
6526}
6527
Glenn Kastena8356f62013-07-25 14:37:52 -07006528bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006529 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006530 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006531 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006532 return false;
6533 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006534 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006535 recordTrack->mState = TrackBase::PAUSING;
6536 // do not wait for mStartStopCond if exiting
6537 if (exitPending()) {
6538 return true;
6539 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006540 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006541 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006542 // if we have been restarted, recordTrack is in mActiveTracks here
6543 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006544 ALOGV("Record stopped OK");
6545 return true;
6546 }
6547 return false;
6548}
6549
Glenn Kasten0f11b512014-01-31 16:18:54 -08006550bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006551{
6552 return false;
6553}
6554
Glenn Kasten0f11b512014-01-31 16:18:54 -08006555status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006556{
6557#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6558 if (!isValidSyncEvent(event)) {
6559 return BAD_VALUE;
6560 }
6561
6562 int eventSession = event->triggerSession();
6563 status_t ret = NAME_NOT_FOUND;
6564
6565 Mutex::Autolock _l(mLock);
6566
6567 for (size_t i = 0; i < mTracks.size(); i++) {
6568 sp<RecordTrack> track = mTracks[i];
6569 if (eventSession == track->sessionId()) {
6570 (void) track->setSyncEvent(event);
6571 ret = NO_ERROR;
6572 }
6573 }
6574 return ret;
6575#else
6576 return BAD_VALUE;
6577#endif
6578}
6579
6580// destroyTrack_l() must be called with ThreadBase::mLock held
6581void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6582{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006583 track->terminate();
6584 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006585 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006586 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006587 removeTrack_l(track);
6588 }
6589}
6590
6591void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6592{
6593 mTracks.remove(track);
6594 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006595 if (track->isFastTrack()) {
6596 ALOG_ASSERT(!mFastTrackAvail);
6597 mFastTrackAvail = true;
6598 }
Eric Laurent81784c32012-11-19 14:55:58 -08006599}
6600
6601void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6602{
6603 dumpInternals(fd, args);
6604 dumpTracks(fd, args);
6605 dumpEffectChains(fd, args);
6606}
6607
6608void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6609{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006610 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006611
Glenn Kasten44182c22015-03-05 17:12:23 -08006612 dumpBase(fd, args);
6613
6614 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006615 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006616 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006617 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006618 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006619
Glenn Kasten2f90c512015-12-02 11:40:09 -08006620 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6621 // while we are dumping it. It may be inconsistent, but it won't mutate!
6622 // This is a large object so we place it on the heap.
6623 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6624 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6625 copy->dump(fd);
6626 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006627}
6628
Glenn Kasten0f11b512014-01-31 16:18:54 -08006629void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006630{
6631 const size_t SIZE = 256;
6632 char buffer[SIZE];
6633 String8 result;
6634
Marco Nelissenb2208842014-02-07 14:00:50 -08006635 size_t numtracks = mTracks.size();
6636 size_t numactive = mActiveTracks.size();
6637 size_t numactiveseen = 0;
Elliott Hughes87cebad2014-05-22 10:14:43 -07006638 dprintf(fd, " %d Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006639 if (numtracks) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006640 dprintf(fd, " of which %d are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006641 RecordTrack::appendDumpHeader(result);
6642 for (size_t i = 0; i < numtracks ; ++i) {
6643 sp<RecordTrack> track = mTracks[i];
6644 if (track != 0) {
6645 bool active = mActiveTracks.indexOf(track) >= 0;
6646 if (active) {
6647 numactiveseen++;
6648 }
6649 track->dump(buffer, SIZE, active);
6650 result.append(buffer);
6651 }
Eric Laurent81784c32012-11-19 14:55:58 -08006652 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006653 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006654 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006655 }
6656
Marco Nelissenb2208842014-02-07 14:00:50 -08006657 if (numactiveseen != numactive) {
6658 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6659 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006660 result.append(buffer);
6661 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006662 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006663 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006664 if (mTracks.indexOf(track) < 0) {
6665 track->dump(buffer, SIZE, true);
6666 result.append(buffer);
6667 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006668 }
Eric Laurent81784c32012-11-19 14:55:58 -08006669
6670 }
6671 write(fd, result.string(), result.size());
6672}
6673
Andy Hung73c02e42015-03-29 01:13:58 -07006674
6675void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6676{
6677 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6678 RecordThread *recordThread = (RecordThread *) threadBase.get();
6679 mRsmpInFront = recordThread->mRsmpInRear;
6680 mRsmpInUnrel = 0;
6681}
6682
6683void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6684 size_t *framesAvailable, bool *hasOverrun)
6685{
6686 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6687 RecordThread *recordThread = (RecordThread *) threadBase.get();
6688 const int32_t rear = recordThread->mRsmpInRear;
6689 const int32_t front = mRsmpInFront;
6690 const ssize_t filled = rear - front;
6691
6692 size_t framesIn;
6693 bool overrun = false;
6694 if (filled < 0) {
6695 // should not happen, but treat like a massive overrun and re-sync
6696 framesIn = 0;
6697 mRsmpInFront = rear;
6698 overrun = true;
6699 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6700 framesIn = (size_t) filled;
6701 } else {
6702 // client is not keeping up with server, but give it latest data
6703 framesIn = recordThread->mRsmpInFrames;
6704 mRsmpInFront = /* front = */ rear - framesIn;
6705 overrun = true;
6706 }
6707 if (framesAvailable != NULL) {
6708 *framesAvailable = framesIn;
6709 }
6710 if (hasOverrun != NULL) {
6711 *hasOverrun = overrun;
6712 }
6713}
6714
Eric Laurent81784c32012-11-19 14:55:58 -08006715// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006716status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006717 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006718{
Andy Hung73c02e42015-03-29 01:13:58 -07006719 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006720 if (threadBase == 0) {
6721 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006722 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006723 return NOT_ENOUGH_DATA;
6724 }
6725 RecordThread *recordThread = (RecordThread *) threadBase.get();
6726 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006727 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006728 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006729 // FIXME should not be P2 (don't want to increase latency)
6730 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006731 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006732 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006733 front &= recordThread->mRsmpInFramesP2 - 1;
6734 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006735 if (part1 > (size_t) filled) {
6736 part1 = filled;
6737 }
6738 size_t ask = buffer->frameCount;
6739 ALOG_ASSERT(ask > 0);
6740 if (part1 > ask) {
6741 part1 = ask;
6742 }
6743 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006744 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006745 buffer->raw = NULL;
6746 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006747 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006748 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006749 }
6750
Andy Hung57446612015-04-19 23:56:46 -07006751 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006752 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006753 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006754 return NO_ERROR;
6755}
6756
6757// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006758void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6759 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006760{
Glenn Kasten85948432013-08-19 12:09:05 -07006761 size_t stepCount = buffer->frameCount;
6762 if (stepCount == 0) {
6763 return;
6764 }
Andy Hung73c02e42015-03-29 01:13:58 -07006765 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6766 mRsmpInUnrel -= stepCount;
6767 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006768 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006769 buffer->frameCount = 0;
6770}
6771
Andy Hung97a893e2015-03-29 01:03:07 -07006772AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6773 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6774 uint32_t srcSampleRate,
6775 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6776 uint32_t dstSampleRate) :
6777 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6778 // mSrcFormat
6779 // mSrcSampleRate
6780 // mDstChannelMask
6781 // mDstFormat
6782 // mDstSampleRate
6783 // mSrcChannelCount
6784 // mDstChannelCount
6785 // mDstFrameSize
6786 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006787 mResampler(NULL),
6788 mIsLegacyDownmix(false),
6789 mIsLegacyUpmix(false),
6790 mRequiresFloat(false),
6791 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006792{
6793 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6794 dstChannelMask, dstFormat, dstSampleRate);
6795}
6796
6797AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6798 free(mBuf);
6799 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006800 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006801}
6802
6803size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6804 AudioBufferProvider *provider, size_t frames)
6805{
Andy Hungd330ee42015-04-20 13:23:41 -07006806 if (mInputConverterProvider != NULL) {
6807 mInputConverterProvider->setBufferProvider(provider);
6808 provider = mInputConverterProvider;
6809 }
6810
6811 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006812 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6813 mSrcSampleRate, mSrcFormat, mDstFormat);
6814
6815 AudioBufferProvider::Buffer buffer;
6816 for (size_t i = frames; i > 0; ) {
6817 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006818 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006819 if (status != OK || buffer.frameCount == 0) {
6820 frames -= i; // cannot fill request.
6821 break;
6822 }
Andy Hungd330ee42015-04-20 13:23:41 -07006823 // format convert to destination buffer
6824 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006825
6826 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6827 i -= buffer.frameCount;
6828 provider->releaseBuffer(&buffer);
6829 }
6830 } else {
6831 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6832 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
6833
Andy Hungd330ee42015-04-20 13:23:41 -07006834 // reallocate buffer if needed
6835 if (mBufFrameSize != 0 && mBufFrames < frames) {
6836 free(mBuf);
6837 mBufFrames = frames;
6838 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6839 }
Andy Hung97a893e2015-03-29 01:03:07 -07006840 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07006841 memset(mBuf, 0, frames * mBufFrameSize);
6842 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
6843 // format convert to destination buffer
6844 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006845 }
6846 return frames;
6847}
6848
6849status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
6850 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6851 uint32_t srcSampleRate,
6852 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6853 uint32_t dstSampleRate)
6854{
6855 // quick evaluation if there is any change.
6856 if (mSrcFormat == srcFormat
6857 && mSrcChannelMask == srcChannelMask
6858 && mSrcSampleRate == srcSampleRate
6859 && mDstFormat == dstFormat
6860 && mDstChannelMask == dstChannelMask
6861 && mDstSampleRate == dstSampleRate) {
6862 return NO_ERROR;
6863 }
6864
Andy Hungdb4c0312015-05-06 08:46:52 -07006865 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
6866 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
6867 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07006868 const bool valid =
6869 audio_is_input_channel(srcChannelMask)
6870 && audio_is_input_channel(dstChannelMask)
6871 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
6872 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
6873 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
6874 ; // no upsampling checks for now
6875 if (!valid) {
6876 return BAD_VALUE;
6877 }
6878
6879 mSrcFormat = srcFormat;
6880 mSrcChannelMask = srcChannelMask;
6881 mSrcSampleRate = srcSampleRate;
6882 mDstFormat = dstFormat;
6883 mDstChannelMask = dstChannelMask;
6884 mDstSampleRate = dstSampleRate;
6885
6886 // compute derived parameters
6887 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
6888 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
6889 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
6890
Andy Hungd330ee42015-04-20 13:23:41 -07006891 // do we need to resample?
6892 delete mResampler;
6893 mResampler = NULL;
6894 if (mSrcSampleRate != mDstSampleRate) {
6895 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
6896 mSrcChannelCount, mDstSampleRate);
6897 mResampler->setSampleRate(mSrcSampleRate);
6898 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
6899 }
6900
6901 // are we running legacy channel conversion modes?
6902 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
6903 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
6904 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
6905 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
6906 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
6907 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
6908
6909 // do we need to process in float?
6910 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
6911
6912 // do we need a staging buffer to convert for destination (we can still optimize this)?
6913 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
6914 if (mResampler != NULL) {
6915 mBufFrameSize = max(mSrcChannelCount, FCC_2)
6916 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07006917 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07006918 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
6919 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07006920 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
6921 } else {
6922 mBufFrameSize = 0;
6923 }
6924 mBufFrames = 0; // force the buffer to be resized.
6925
Andy Hungd330ee42015-04-20 13:23:41 -07006926 // do we need an input converter buffer provider to give us float?
6927 delete mInputConverterProvider;
6928 mInputConverterProvider = NULL;
6929 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
6930 mInputConverterProvider = new ReformatBufferProvider(
6931 audio_channel_count_from_in_mask(mSrcChannelMask),
6932 mSrcFormat,
6933 AUDIO_FORMAT_PCM_FLOAT,
6934 256 /* provider buffer frame count */);
6935 }
6936
6937 // do we need a remixer to do channel mask conversion
6938 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
6939 (void) memcpy_by_index_array_initialization_from_channel_mask(
6940 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07006941 }
6942 return NO_ERROR;
6943}
6944
Andy Hungd330ee42015-04-20 13:23:41 -07006945void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
6946 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07006947{
Andy Hungd330ee42015-04-20 13:23:41 -07006948 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07006949 if (mBufFrameSize != 0 && mBufFrames < frames) {
6950 free(mBuf);
6951 mBufFrames = frames;
6952 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
6953 }
Andy Hungd330ee42015-04-20 13:23:41 -07006954 // do we need to do legacy upmix and downmix?
6955 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07006956 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006957 if (mIsLegacyUpmix) {
6958 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
6959 (const float *)src, frames);
6960 } else /*mIsLegacyDownmix */ {
6961 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
6962 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07006963 }
Andy Hungd330ee42015-04-20 13:23:41 -07006964 if (mBuf != NULL) {
6965 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
6966 frames * mDstChannelCount);
6967 }
6968 return;
6969 }
6970 // do we need to do channel mask conversion?
6971 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07006972 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07006973 memcpy_by_index_array(dstBuf, mDstChannelCount,
6974 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
6975 if (dstBuf == dst) {
6976 return; // format is the same
6977 }
6978 }
6979 // convert to destination buffer
6980 const void *convertBuf = mBuf != NULL ? mBuf : src;
6981 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
6982 frames * mDstChannelCount);
6983}
6984
6985void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
6986 void *dst, /*not-a-const*/ void *src, size_t frames)
6987{
6988 // src buffer format is ALWAYS float when entering this routine
6989 if (mIsLegacyUpmix) {
6990 ; // mono to stereo already handled by resampler
6991 } else if (mIsLegacyDownmix
6992 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
6993 // the resampler outputs stereo for mono input channel (a feature?)
6994 // must convert to mono
6995 downmix_to_mono_float_from_stereo_float((float *)src,
6996 (const float *)src, frames);
6997 } else if (mSrcChannelMask != mDstChannelMask) {
6998 // convert to mono channel again for channel mask conversion (could be skipped
6999 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007000 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007001 downmix_to_mono_float_from_stereo_float((float *)src,
7002 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007003 }
Andy Hungd330ee42015-04-20 13:23:41 -07007004 // convert to destination format (in place, OK as float is larger than other types)
7005 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7006 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7007 frames * mSrcChannelCount);
7008 }
7009 // channel convert and save to dst
7010 memcpy_by_index_array(dst, mDstChannelCount,
7011 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7012 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007013 }
Andy Hungd330ee42015-04-20 13:23:41 -07007014 // convert to destination format and save to dst
7015 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7016 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007017}
7018
Eric Laurent10351942014-05-08 18:49:52 -07007019bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7020 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007021{
7022 bool reconfig = false;
7023
Eric Laurent10351942014-05-08 18:49:52 -07007024 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007025
Eric Laurent10351942014-05-08 18:49:52 -07007026 audio_format_t reqFormat = mFormat;
7027 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007028 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Eric Laurent10351942014-05-08 18:49:52 -07007029 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7030
7031 AudioParameter param = AudioParameter(keyValuePair);
7032 int value;
7033 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7034 // channel count change can be requested. Do we mandate the first client defines the
7035 // HAL sampling rate and channel count or do we allow changes on the fly?
7036 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7037 samplingRate = value;
7038 reconfig = true;
7039 }
7040 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007041 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007042 status = BAD_VALUE;
7043 } else {
7044 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007045 reconfig = true;
7046 }
Eric Laurent10351942014-05-08 18:49:52 -07007047 }
7048 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7049 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007050 if (!audio_is_input_channel(mask) ||
7051 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007052 status = BAD_VALUE;
7053 } else {
7054 channelMask = mask;
7055 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007056 }
Eric Laurent10351942014-05-08 18:49:52 -07007057 }
7058 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7059 // do not accept frame count changes if tracks are open as the track buffer
7060 // size depends on frame count and correct behavior would not be guaranteed
7061 // if frame count is changed after track creation
7062 if (mActiveTracks.size() > 0) {
7063 status = INVALID_OPERATION;
7064 } else {
7065 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007066 }
Eric Laurent10351942014-05-08 18:49:52 -07007067 }
7068 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7069 // forward device change to effects that have requested to be
7070 // aware of attached audio device.
7071 for (size_t i = 0; i < mEffectChains.size(); i++) {
7072 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007073 }
Eric Laurent81784c32012-11-19 14:55:58 -08007074
Eric Laurent10351942014-05-08 18:49:52 -07007075 // store input device and output device but do not forward output device to audio HAL.
7076 // Note that status is ignored by the caller for output device
7077 // (see AudioFlinger::setParameters()
7078 if (audio_is_output_devices(value)) {
7079 mOutDevice = value;
7080 status = BAD_VALUE;
7081 } else {
7082 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007083 if (value != AUDIO_DEVICE_NONE) {
7084 mPrevInDevice = value;
7085 }
Eric Laurent10351942014-05-08 18:49:52 -07007086 // disable AEC and NS if the device is a BT SCO headset supporting those
7087 // pre processings
7088 if (mTracks.size() > 0) {
7089 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7090 mAudioFlinger->btNrecIsOff();
7091 for (size_t i = 0; i < mTracks.size(); i++) {
7092 sp<RecordTrack> track = mTracks[i];
7093 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7094 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007095 }
7096 }
7097 }
Eric Laurent10351942014-05-08 18:49:52 -07007098 }
7099 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7100 mAudioSource != (audio_source_t)value) {
7101 // forward device change to effects that have requested to be
7102 // aware of attached audio device.
7103 for (size_t i = 0; i < mEffectChains.size(); i++) {
7104 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007105 }
Eric Laurent10351942014-05-08 18:49:52 -07007106 mAudioSource = (audio_source_t)value;
7107 }
Glenn Kastene198c362013-08-13 09:13:36 -07007108
Eric Laurent10351942014-05-08 18:49:52 -07007109 if (status == NO_ERROR) {
7110 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7111 keyValuePair.string());
7112 if (status == INVALID_OPERATION) {
7113 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007114 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7115 keyValuePair.string());
Eric Laurent10351942014-05-08 18:49:52 -07007116 }
7117 if (reconfig) {
7118 if (status == BAD_VALUE &&
Andy Hung97a893e2015-03-29 01:03:07 -07007119 audio_is_linear_pcm(mInput->stream->common.get_format(&mInput->stream->common)) &&
7120 audio_is_linear_pcm(reqFormat) &&
Eric Laurent10351942014-05-08 18:49:52 -07007121 (mInput->stream->common.get_sample_rate(&mInput->stream->common)
Andy Hung97a893e2015-03-29 01:03:07 -07007122 <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate)) &&
Andy Hunge5412692014-05-16 11:25:07 -07007123 audio_channel_count_from_in_mask(
Andy Hungd1abb8f2015-05-05 23:42:34 -07007124 mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007125 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007126 }
Eric Laurent10351942014-05-08 18:49:52 -07007127 if (status == NO_ERROR) {
7128 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007129 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007130 }
7131 }
Eric Laurent81784c32012-11-19 14:55:58 -08007132 }
Eric Laurent10351942014-05-08 18:49:52 -07007133
Eric Laurent81784c32012-11-19 14:55:58 -08007134 return reconfig;
7135}
7136
7137String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7138{
Eric Laurent81784c32012-11-19 14:55:58 -08007139 Mutex::Autolock _l(mLock);
7140 if (initCheck() != NO_ERROR) {
Glenn Kastend8ea6992013-07-16 14:17:15 -07007141 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007142 }
7143
Glenn Kastend8ea6992013-07-16 14:17:15 -07007144 char *s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
7145 const String8 out_s8(s);
Eric Laurent81784c32012-11-19 14:55:58 -08007146 free(s);
7147 return out_s8;
7148}
7149
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007150void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007151 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7152
7153 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007154
7155 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007156 case AUDIO_INPUT_OPENED:
7157 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007158 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007159 desc->mChannelMask = mChannelMask;
7160 desc->mSamplingRate = mSampleRate;
7161 desc->mFormat = mFormat;
7162 desc->mFrameCount = mFrameCount;
7163 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007164 break;
7165
Eric Laurent73e26b62015-04-27 16:55:58 -07007166 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007167 default:
7168 break;
7169 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007170 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007171}
7172
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007173void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007174{
Eric Laurent81784c32012-11-19 14:55:58 -08007175 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
7176 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
Andy Hunge5412692014-05-16 11:25:07 -07007177 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Andy Hungd330ee42015-04-20 13:23:41 -07007178 if (mChannelCount > FCC_8) {
7179 ALOGE("HAL channel count %d > %d", mChannelCount, FCC_8);
7180 }
Andy Hung463be252014-07-10 16:56:07 -07007181 mHALFormat = mInput->stream->common.get_format(&mInput->stream->common);
7182 mFormat = mHALFormat;
Andy Hungd330ee42015-04-20 13:23:41 -07007183 if (!audio_is_linear_pcm(mFormat)) {
7184 ALOGE("HAL format %#x is not linear pcm", mFormat);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07007185 }
Eric Laurent665470b2014-07-03 16:37:08 -07007186 mFrameSize = audio_stream_in_frame_size(mInput->stream);
Glenn Kasten548efc92012-11-29 08:48:51 -08007187 mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
7188 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007189 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007190 // 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 -07007191 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007192 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007193 // A larger value should allow more old data to be read after a track calls start(),
7194 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007195 //
7196 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007197 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007198 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007199 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007200 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007201
7202 // TODO optimize audio capture buffer sizes ...
7203 // Here we calculate the size of the sliding buffer used as a source
7204 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7205 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7206 // be better to have it derived from the pipe depth in the long term.
7207 // The current value is higher than necessary. However it should not add to latency.
7208
Glenn Kasten85948432013-08-19 12:09:05 -07007209 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Andy Hung0a01c2f2015-09-21 12:44:54 -07007210 size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
7211 (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
7212 memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007213
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007214 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7215 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007216}
7217
Glenn Kasten5f972c02014-01-13 09:59:31 -08007218uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007219{
7220 Mutex::Autolock _l(mLock);
7221 if (initCheck() != NO_ERROR) {
7222 return 0;
7223 }
7224
7225 return mInput->stream->get_input_frames_lost(mInput->stream);
7226}
7227
7228uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
7229{
7230 Mutex::Autolock _l(mLock);
7231 uint32_t result = 0;
7232 if (getEffectChain_l(sessionId) != 0) {
7233 result = EFFECT_SESSION;
7234 }
7235
7236 for (size_t i = 0; i < mTracks.size(); ++i) {
7237 if (sessionId == mTracks[i]->sessionId()) {
7238 result |= TRACK_SESSION;
7239 break;
7240 }
7241 }
7242
7243 return result;
7244}
7245
7246KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
7247{
7248 KeyedVector<int, bool> ids;
7249 Mutex::Autolock _l(mLock);
7250 for (size_t j = 0; j < mTracks.size(); ++j) {
7251 sp<RecordThread::RecordTrack> track = mTracks[j];
7252 int sessionId = track->sessionId();
7253 if (ids.indexOfKey(sessionId) < 0) {
7254 ids.add(sessionId, true);
7255 }
7256 }
7257 return ids;
7258}
7259
7260AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7261{
7262 Mutex::Autolock _l(mLock);
7263 AudioStreamIn *input = mInput;
7264 mInput = NULL;
7265 return input;
7266}
7267
7268// this method must always be called either with ThreadBase mLock held or inside the thread loop
7269audio_stream_t* AudioFlinger::RecordThread::stream() const
7270{
7271 if (mInput == NULL) {
7272 return NULL;
7273 }
7274 return &mInput->stream->common;
7275}
7276
7277status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7278{
7279 // only one chain per input thread
7280 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007281 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007282 return INVALID_OPERATION;
7283 }
7284 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007285 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007286 chain->setInBuffer(NULL);
7287 chain->setOutBuffer(NULL);
7288
7289 checkSuspendOnAddEffectChain_l(chain);
7290
Eric Laurent1b928682014-10-02 19:41:47 -07007291 // make sure enabled pre processing effects state is communicated to the HAL as we
7292 // just moved them to a new input stream.
7293 chain->syncHalEffectsState();
7294
Eric Laurent81784c32012-11-19 14:55:58 -08007295 mEffectChains.add(chain);
7296
7297 return NO_ERROR;
7298}
7299
7300size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7301{
7302 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7303 ALOGW_IF(mEffectChains.size() != 1,
7304 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7305 chain.get(), mEffectChains.size(), this);
7306 if (mEffectChains.size() == 1) {
7307 mEffectChains.removeAt(0);
7308 }
7309 return 0;
7310}
7311
Eric Laurent1c333e22014-05-20 10:48:17 -07007312status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7313 audio_patch_handle_t *handle)
7314{
7315 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007316
7317 // store new device and send to effects
7318 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007319 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007320 for (size_t i = 0; i < mEffectChains.size(); i++) {
7321 mEffectChains[i]->setDevice_l(mInDevice);
7322 }
7323
7324 // disable AEC and NS if the device is a BT SCO headset supporting those
7325 // pre processings
7326 if (mTracks.size() > 0) {
7327 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7328 mAudioFlinger->btNrecIsOff();
7329 for (size_t i = 0; i < mTracks.size(); i++) {
7330 sp<RecordTrack> track = mTracks[i];
7331 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7332 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7333 }
7334 }
7335
7336 // store new source and send to effects
7337 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7338 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007339 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007340 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007341 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007342 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007343
Eric Laurent054d9d32015-04-24 08:48:48 -07007344 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007345 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7346 status = hwDevice->create_audio_patch(hwDevice,
7347 patch->num_sources,
7348 patch->sources,
7349 patch->num_sinks,
7350 patch->sinks,
7351 handle);
7352 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007353 char *address;
7354 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7355 address = audio_device_address_to_parameter(
7356 patch->sources[0].ext.device.type,
7357 patch->sources[0].ext.device.address);
7358 } else {
7359 address = (char *)calloc(1, 1);
7360 }
7361 AudioParameter param = AudioParameter(String8(address));
7362 free(address);
7363 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING),
7364 (int)patch->sources[0].ext.device.type);
7365 param.addInt(String8(AUDIO_PARAMETER_STREAM_INPUT_SOURCE),
7366 (int)patch->sinks[0].ext.mix.usecase.source);
7367 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7368 param.toString().string());
7369 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007370 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007371
Eric Laurente8726fe2015-06-26 09:39:24 -07007372 if (mInDevice != mPrevInDevice) {
7373 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7374 mPrevInDevice = mInDevice;
7375 }
Eric Laurent296fb132015-05-01 11:38:42 -07007376
Eric Laurent1c333e22014-05-20 10:48:17 -07007377 return status;
7378}
7379
7380status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7381{
7382 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007383
7384 mInDevice = AUDIO_DEVICE_NONE;
7385
Eric Laurent1c333e22014-05-20 10:48:17 -07007386 if (mInput->audioHwDev->version() >= AUDIO_DEVICE_API_VERSION_3_0) {
7387 audio_hw_device_t *hwDevice = mInput->audioHwDev->hwDevice();
7388 status = hwDevice->release_audio_patch(hwDevice, handle);
7389 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007390 AudioParameter param;
7391 param.addInt(String8(AUDIO_PARAMETER_STREAM_ROUTING), 0);
7392 status = mInput->stream->common.set_parameters(&mInput->stream->common,
7393 param.toString().string());
Eric Laurent1c333e22014-05-20 10:48:17 -07007394 }
7395 return status;
7396}
7397
Eric Laurent83b88082014-06-20 18:31:16 -07007398void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7399{
7400 Mutex::Autolock _l(mLock);
7401 mTracks.add(record);
7402}
7403
7404void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7405{
7406 Mutex::Autolock _l(mLock);
7407 destroyTrack_l(record);
7408}
7409
7410void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7411{
7412 ThreadBase::getAudioPortConfig(config);
7413 config->role = AUDIO_PORT_ROLE_SINK;
7414 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7415 config->ext.mix.usecase.source = mAudioSource;
7416}
Eric Laurent1c333e22014-05-20 10:48:17 -07007417
Glenn Kasten63238ef2015-03-02 15:50:29 -08007418} // namespace android