blob: b5e7856aaa70d7c34ccfe1ee7f98bf35b4edb7d2 [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>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
27#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080030#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070032#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070033#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080034#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070035#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080037#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038
39#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070040#include <private/android_filesystem_config.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080041#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080043#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070044#include <audio_utils/minifloat.h>
Eric Tan1882f162018-08-02 18:05:39 -070045#include <json/json.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070046#include <system/audio_effects/effect_ns.h>
47#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049
50// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070051#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052#include <media/nbaio/AudioStreamOutSink.h>
53#include <media/nbaio/MonoPipe.h>
54#include <media/nbaio/MonoPipeReader.h>
55#include <media/nbaio/Pipe.h>
56#include <media/nbaio/PipeReader.h>
57#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080058#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080059
60#include <powermanager/PowerManager.h>
61
Kevin Rocard7588ff42018-01-08 11:11:30 -080062#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070063#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080066#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070067#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070068#include <mediautils/SchedulingPolicyService.h>
69#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070
Eric Laurent81784c32012-11-19 14:55:58 -080071#ifdef ADD_BATTERY_DATA
72#include <media/IMediaPlayerService.h>
73#include <media/IMediaDeathNotifier.h>
74#endif
75
Eric Laurent81784c32012-11-19 14:55:58 -080076#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070077#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080078#include <cpustats/ThreadCpuUsage.h>
79#endif
80
Glenn Kastenc05b8d72016-03-24 09:48:17 -070081#include "AutoPark.h"
82
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080083#include <pthread.h>
84#include "TypedLogger.h"
85
Eric Laurent81784c32012-11-19 14:55:58 -080086// ----------------------------------------------------------------------------
87
88// Note: the following macro is used for extremely verbose logging message. In
89// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
90// 0; but one side effect of this is to turn all LOGV's as well. Some messages
91// are so verbose that we want to suppress them even when we have ALOG_ASSERT
92// turned on. Do not uncomment the #def below unless you really know what you
93// are doing and want to see all of the extremely verbose messages.
94//#define VERY_VERY_VERBOSE_LOGGING
95#ifdef VERY_VERY_VERBOSE_LOGGING
96#define ALOGVV ALOGV
97#else
98#define ALOGVV(a...) do { } while(0)
99#endif
100
Andy Hung6770c6f2015-04-07 13:43:36 -0700101// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700103template <typename T>
104static inline T min(const T& a, const T& b)
105{
106 return a < b ? a : b;
107}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700108
Eric Laurent81784c32012-11-19 14:55:58 -0800109namespace android {
110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700119
Eric Laurent51716182016-02-29 18:00:56 -0800120
Eric Laurent81784c32012-11-19 14:55:58 -0800121
122// don't warn about blocked writes or record buffer overflows more often than this
123static const nsecs_t kWarningThrottleNs = seconds(5);
124
125// RecordThread loop sleep time upon application overrun or audio HAL read error
126static const int kRecordThreadSleepUs = 5000;
127
Eric Laurent10351942014-05-08 18:49:52 -0700128// maximum time to wait in sendConfigEvent_l() for a status to be received
129static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800130
131// minimum sleep time for the mixer thread loop when tracks are active but in underrun
132static const uint32_t kMinThreadSleepTimeUs = 5000;
133// maximum divider applied to the active sleep time in the mixer thread loop
134static const uint32_t kMaxThreadSleepTimeShift = 2;
135
Andy Hung09a50072014-02-27 14:30:47 -0800136// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700137// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800138static const uint32_t kMinNormalSinkBufferSizeMs = 20;
139// maximum normal sink buffer size
140static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800141
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700142// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
143// FIXME This should be based on experimentally observed scheduling jitter
144static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
145
Eric Laurent972a1732013-09-04 09:42:59 -0700146// Offloaded output thread standby delay: allows track transition without going to standby
147static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
148
Eric Laurent51716182016-02-29 18:00:56 -0800149// Direct output thread minimum sleep time in idle or active(underrun) state
150static const nsecs_t kDirectMinSleepTimeUs = 10000;
151
Glenn Kasten1b291842016-07-18 14:55:21 -0700152// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
153// balance between power consumption and latency, and allows threads to be scheduled reliably
154// by the CFS scheduler.
155// FIXME Express other hardcoded references to 20ms with references to this constant and move
156// it appropriately.
157#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800158
Eric Laurent81784c32012-11-19 14:55:58 -0800159// Whether to use fast mixer
160static const enum {
161 FastMixer_Never, // never initialize or use: for debugging only
162 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
163 // normal mixer multiplier is 1
164 FastMixer_Static, // initialize if needed, then use all the time if initialized,
165 // multiplier is calculated based on min & max normal mixer buffer size
166 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
167 // multiplier is calculated based on min & max normal mixer buffer size
168 // FIXME for FastMixer_Dynamic:
169 // Supporting this option will require fixing HALs that can't handle large writes.
170 // For example, one HAL implementation returns an error from a large write,
171 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
172 // We could either fix the HAL implementations, or provide a wrapper that breaks
173 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
174} kUseFastMixer = FastMixer_Static;
175
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700176// Whether to use fast capture
177static const enum {
178 FastCapture_Never, // never initialize or use: for debugging only
179 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
180 FastCapture_Static, // initialize if needed, then use all the time if initialized
181} kUseFastCapture = FastCapture_Static;
182
Eric Laurent81784c32012-11-19 14:55:58 -0800183// Priorities for requestPriority
184static const int kPriorityAudioApp = 2;
185static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700186static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800187
Glenn Kastenea38ee72016-04-18 11:08:01 -0700188// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
189// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
190// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700191
192// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800193static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800194
Glenn Kasten03490092014-05-27 12:30:54 -0700195// The minimum and maximum allowed values
196static const int kFastTrackMultiplierMin = 1;
197static const int kFastTrackMultiplierMax = 2;
198
199// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
200static int sFastTrackMultiplier = kFastTrackMultiplier;
201
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700202// See Thread::readOnlyHeap().
203// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
204// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
205// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700206static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700207
Eric Laurent81784c32012-11-19 14:55:58 -0800208// ----------------------------------------------------------------------------
209
Glenn Kasten03490092014-05-27 12:30:54 -0700210static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
211
212static void sFastTrackMultiplierInit()
213{
214 char value[PROPERTY_VALUE_MAX];
215 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
216 char *endptr;
217 unsigned long ul = strtoul(value, &endptr, 0);
218 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
219 sFastTrackMultiplier = (int) ul;
220 }
221 }
222}
223
224// ----------------------------------------------------------------------------
225
Eric Laurent81784c32012-11-19 14:55:58 -0800226#ifdef ADD_BATTERY_DATA
227// To collect the amplifier usage
228static void addBatteryData(uint32_t params) {
229 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
230 if (service == NULL) {
231 // it already logged
232 return;
233 }
234
235 service->addBatteryData(params);
236}
237#endif
238
Andy Hung3f0c9022016-01-15 17:49:46 -0800239// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
240struct {
241 // call when you acquire a partial wakelock
242 void acquire(const sp<IBinder> &wakeLockToken) {
243 pthread_mutex_lock(&mLock);
244 if (wakeLockToken.get() == nullptr) {
245 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
246 } else {
247 if (mCount == 0) {
248 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
249 }
250 ++mCount;
251 }
252 pthread_mutex_unlock(&mLock);
253 }
254
255 // call when you release a partial wakelock.
256 void release(const sp<IBinder> &wakeLockToken) {
257 if (wakeLockToken.get() == nullptr) {
258 return;
259 }
260 pthread_mutex_lock(&mLock);
261 if (--mCount < 0) {
262 ALOGE("negative wakelock count");
263 mCount = 0;
264 }
265 pthread_mutex_unlock(&mLock);
266 }
267
268 // retrieves the boottime timebase offset from monotonic.
269 int64_t getBoottimeOffset() {
270 pthread_mutex_lock(&mLock);
271 int64_t boottimeOffset = mBoottimeOffset;
272 pthread_mutex_unlock(&mLock);
273 return boottimeOffset;
274 }
275
276 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
277 // and the selected timebase.
278 // Currently only TIMEBASE_BOOTTIME is allowed.
279 //
280 // This only needs to be called upon acquiring the first partial wakelock
281 // after all other partial wakelocks are released.
282 //
283 // We do an empirical measurement of the offset rather than parsing
284 // /proc/timer_list since the latter is not a formal kernel ABI.
285 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
286 int clockbase;
287 switch (timebase) {
288 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
289 clockbase = SYSTEM_TIME_BOOTTIME;
290 break;
291 default:
292 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
293 break;
294 }
295 // try three times to get the clock offset, choose the one
296 // with the minimum gap in measurements.
297 const int tries = 3;
298 nsecs_t bestGap, measured;
299 for (int i = 0; i < tries; ++i) {
300 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
301 const nsecs_t tbase = systemTime(clockbase);
302 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
303 const nsecs_t gap = tmono2 - tmono;
304 if (i == 0 || gap < bestGap) {
305 bestGap = gap;
306 measured = tbase - ((tmono + tmono2) >> 1);
307 }
308 }
309
310 // to avoid micro-adjusting, we don't change the timebase
311 // unless it is significantly different.
312 //
313 // Assumption: It probably takes more than toleranceNs to
314 // suspend and resume the device.
315 static int64_t toleranceNs = 10000; // 10 us
316 if (llabs(*offset - measured) > toleranceNs) {
317 ALOGV("Adjusting timebase offset old: %lld new: %lld",
318 (long long)*offset, (long long)measured);
319 *offset = measured;
320 }
321 }
322
323 pthread_mutex_t mLock;
324 int32_t mCount;
325 int64_t mBoottimeOffset;
326} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800327
328// ----------------------------------------------------------------------------
329// CPU Stats
330// ----------------------------------------------------------------------------
331
332class CpuStats {
333public:
334 CpuStats();
335 void sample(const String8 &title);
336#ifdef DEBUG_CPU_USAGE
337private:
338 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700339 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800340
Andy Hung16698b82018-08-01 10:48:38 -0700341 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800342
343 int mCpuNum; // thread's current CPU number
344 int mCpukHz; // frequency of thread's current CPU in kHz
345#endif
346};
347
348CpuStats::CpuStats()
349#ifdef DEBUG_CPU_USAGE
350 : mCpuNum(-1), mCpukHz(-1)
351#endif
352{
353}
354
Glenn Kasten0f11b512014-01-31 16:18:54 -0800355void CpuStats::sample(const String8 &title
356#ifndef DEBUG_CPU_USAGE
357 __unused
358#endif
359 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800360#ifdef DEBUG_CPU_USAGE
361 // get current thread's delta CPU time in wall clock ns
362 double wcNs;
363 bool valid = mCpuUsage.sampleAndEnable(wcNs);
364
365 // record sample for wall clock statistics
366 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700367 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800368 }
369
370 // get the current CPU number
371 int cpuNum = sched_getcpu();
372
373 // get the current CPU frequency in kHz
374 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
375
376 // check if either CPU number or frequency changed
377 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
378 mCpuNum = cpuNum;
379 mCpukHz = cpukHz;
380 // ignore sample for purposes of cycles
381 valid = false;
382 }
383
384 // if no change in CPU number or frequency, then record sample for cycle statistics
385 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700386 const double cycles = wcNs * cpukHz * 0.000001;
387 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800388 }
389
Eric Tan5b13ff82018-07-27 11:20:17 -0700390 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800391 // mCpuUsage.elapsed() is expensive, so don't call it every loop
392 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700393 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800394 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700395 const double perLoop = elapsed / (double) n;
396 const double perLoop100 = perLoop * 0.01;
397 const double perLoop1k = perLoop * 0.001;
398 const double mean = mWcStats.getMean();
399 const double stddev = mWcStats.getStdDev();
400 const double minimum = mWcStats.getMin();
401 const double maximum = mWcStats.getMax();
402 const double meanCycles = mHzStats.getMean();
403 const double stddevCycles = mHzStats.getStdDev();
404 const double minCycles = mHzStats.getMin();
405 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800406 mCpuUsage.resetElapsed();
407 mWcStats.reset();
408 mHzStats.reset();
409 ALOGD("CPU usage for %s over past %.1f secs\n"
410 " (%u mixer loops at %.1f mean ms per loop):\n"
411 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
412 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
413 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
414 title.string(),
415 elapsed * .000000001, n, perLoop * .000001,
416 mean * .001,
417 stddev * .001,
418 minimum * .001,
419 maximum * .001,
420 mean / perLoop100,
421 stddev / perLoop100,
422 minimum / perLoop100,
423 maximum / perLoop100,
424 meanCycles / perLoop1k,
425 stddevCycles / perLoop1k,
426 minCycles / perLoop1k,
427 maxCycles / perLoop1k);
428
429 }
430 }
431#endif
432};
433
434// ----------------------------------------------------------------------------
435// ThreadBase
436// ----------------------------------------------------------------------------
437
Glenn Kasten97b7b752014-09-28 13:04:24 -0700438// static
439const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
440{
441 switch (type) {
442 case MIXER:
443 return "MIXER";
444 case DIRECT:
445 return "DIRECT";
446 case DUPLICATING:
447 return "DUPLICATING";
448 case RECORD:
449 return "RECORD";
450 case OFFLOAD:
451 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800452 case MMAP:
453 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700454 default:
455 return "unknown";
456 }
457}
458
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700461 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800462 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700463 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800464 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700465 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800466 }
467 return result;
468}
469
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700470std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700472 std::string result;
473 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800474 return result;
475}
476
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700477std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700478{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700479 std::string result;
480 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700481 return result;
482}
483
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800484const char *sourceToString(audio_source_t source)
485{
486 switch (source) {
487 case AUDIO_SOURCE_DEFAULT: return "default";
488 case AUDIO_SOURCE_MIC: return "mic";
489 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
490 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
491 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
492 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
493 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
494 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
495 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800496 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800497 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
498 case AUDIO_SOURCE_HOTWORD: return "hotword";
499 default: return "unknown";
500 }
501}
502
Eric Laurent81784c32012-11-19 14:55:58 -0800503AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700504 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800505 : Thread(false /*canCallJava*/),
506 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700507 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700508 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800509 // are set by PlaybackThread::readOutputParameters_l() or
510 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700511 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800512 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700513 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
514 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800515 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700516 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800517 mSystemReady(systemReady),
518 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800519{
Eric Laurent296fb132015-05-01 11:38:42 -0700520 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800521}
522
523AudioFlinger::ThreadBase::~ThreadBase()
524{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700525 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700526 mConfigEvents.clear();
527
Eric Laurent81784c32012-11-19 14:55:58 -0800528 // do not lock the mutex in destructor
529 releaseWakeLock_l();
530 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800531 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800532 binder->unlinkToDeath(mDeathRecipient);
533 }
534}
535
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700536status_t AudioFlinger::ThreadBase::readyToRun()
537{
538 status_t status = initCheck();
539 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800540 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700541 } else {
542 ALOGE("No working audio driver found.");
543 }
544 return status;
545}
546
Eric Laurent81784c32012-11-19 14:55:58 -0800547void AudioFlinger::ThreadBase::exit()
548{
549 ALOGV("ThreadBase::exit");
550 // do any cleanup required for exit to succeed
551 preExit();
552 {
553 // This lock prevents the following race in thread (uniprocessor for illustration):
554 // if (!exitPending()) {
555 // // context switch from here to exit()
556 // // exit() calls requestExit(), what exitPending() observes
557 // // exit() calls signal(), which is dropped since no waiters
558 // // context switch back from exit() to here
559 // mWaitWorkCV.wait(...);
560 // // now thread is hung
561 // }
562 AutoMutex lock(mLock);
563 requestExit();
564 mWaitWorkCV.broadcast();
565 }
566 // When Thread::requestExitAndWait is made virtual and this method is renamed to
567 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
568 requestExitAndWait();
569}
570
571status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
572{
Eric Laurent81784c32012-11-19 14:55:58 -0800573 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
574 Mutex::Autolock _l(mLock);
575
Eric Laurent10351942014-05-08 18:49:52 -0700576 return sendSetParameterConfigEvent_l(keyValuePairs);
577}
578
579// sendConfigEvent_l() must be called with ThreadBase::mLock held
580// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
581status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
582{
583 status_t status = NO_ERROR;
584
Eric Laurent72e3f392015-05-20 14:43:50 -0700585 if (event->mRequiresSystemReady && !mSystemReady) {
586 event->mWaitStatus = false;
587 mPendingConfigEvents.add(event);
588 return status;
589 }
Eric Laurent10351942014-05-08 18:49:52 -0700590 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700591 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800592 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700593 mLock.unlock();
594 {
595 Mutex::Autolock _l(event->mLock);
596 while (event->mWaitStatus) {
597 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
598 event->mStatus = TIMED_OUT;
599 event->mWaitStatus = false;
600 }
601 }
602 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800603 }
Eric Laurent10351942014-05-08 18:49:52 -0700604 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800605 return status;
606}
607
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700608void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800609{
610 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800612}
613
614// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700615void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800616{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700617 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700618 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800619}
620
Mikhail Naganov83f04272017-02-07 10:45:09 -0800621void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700622{
623 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700625}
626
Eric Laurent81784c32012-11-19 14:55:58 -0800627// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800628void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
629 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800630{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800631 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700632 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800633}
634
Eric Laurent10351942014-05-08 18:49:52 -0700635// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
636status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800637{
Andy Hung2ddee192015-12-18 17:34:44 -0800638 sp<ConfigEvent> configEvent;
639 AudioParameter param(keyValuePair);
640 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700641 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800642 setMasterMono_l(value != 0);
643 if (param.size() == 1) {
644 return NO_ERROR; // should be a solo parameter - we don't pass down
645 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700646 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800647 configEvent = new SetParameterConfigEvent(param.toString());
648 } else {
649 configEvent = new SetParameterConfigEvent(keyValuePair);
650 }
Eric Laurent10351942014-05-08 18:49:52 -0700651 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700652}
653
Eric Laurent1c333e22014-05-20 10:48:17 -0700654status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
655 const struct audio_patch *patch,
656 audio_patch_handle_t *handle)
657{
658 Mutex::Autolock _l(mLock);
659 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
660 status_t status = sendConfigEvent_l(configEvent);
661 if (status == NO_ERROR) {
662 CreateAudioPatchConfigEventData *data =
663 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
664 *handle = data->mHandle;
665 }
666 return status;
667}
668
669status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
670 const audio_patch_handle_t handle)
671{
672 Mutex::Autolock _l(mLock);
673 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
674 return sendConfigEvent_l(configEvent);
675}
676
677
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700678// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700679void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700680{
Eric Laurent10351942014-05-08 18:49:52 -0700681 bool configChanged = false;
682
Eric Laurent81784c32012-11-19 14:55:58 -0800683 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700684 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700685 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800686 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700687 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700688 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700689 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
690 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800691 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700692 true /*asynchronous*/);
693 if (err != 0) {
694 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700695 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700696 }
697 } break;
698 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700699 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700700 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700701 } break;
702 case CFG_EVENT_SET_PARAMETER: {
703 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
704 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
705 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700706 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
707 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700708 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700709 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700710 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700711 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700712 CreateAudioPatchConfigEventData *data =
713 (CreateAudioPatchConfigEventData *)event->mData.get();
714 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t newDevice = getDevice();
716 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
717 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
718 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 } break;
720 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700721 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700722 ReleaseAudioPatchConfigEventData *data =
723 (ReleaseAudioPatchConfigEventData *)event->mData.get();
724 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700725 const audio_devices_t newDevice = getDevice();
726 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
727 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
728 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700729 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700730 default:
Eric Laurent10351942014-05-08 18:49:52 -0700731 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700732 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800733 }
Eric Laurent10351942014-05-08 18:49:52 -0700734 {
735 Mutex::Autolock _l(event->mLock);
736 if (event->mWaitStatus) {
737 event->mWaitStatus = false;
738 event->mCond.signal();
739 }
740 }
741 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
742 }
743
744 if (configChanged) {
745 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800746 }
Eric Laurent81784c32012-11-19 14:55:58 -0800747}
748
Marco Nelissenb2208842014-02-07 14:00:50 -0800749String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
750 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700751 const audio_channel_representation_t representation =
752 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700753
754 switch (representation) {
755 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
756 if (output) {
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
759 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
761 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
762 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
764 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
766 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
771 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
772 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
773 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
774 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700775 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
776 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700777 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
778 } else {
779 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
780 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
781 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
782 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
783 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
784 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
785 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
786 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
787 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
788 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
789 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
790 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700791 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
792 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
793 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
794 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
795 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
796 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
798 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
799 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
800 }
801 const int len = s.length();
802 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700803 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700804 s.unlockBuffer(len - 2); // remove trailing ", "
805 }
806 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800807 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700808 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
809 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
810 return s;
811 default:
812 s.appendFormat("unknown mask, representation:%d bits:%#x",
813 representation, audio_channel_mask_get_bits(mask));
814 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800815 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800816}
817
Glenn Kasten0f11b512014-01-31 16:18:54 -0800818void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800819{
820 const size_t SIZE = 256;
821 char buffer[SIZE];
822 String8 result;
823
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800824 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
825 this, mThreadName, getTid(), type(), threadTypeToString(type()));
826
Eric Laurent81784c32012-11-19 14:55:58 -0800827 bool locked = AudioFlinger::dumpTryLock(mLock);
828 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800829 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800830 }
831
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700833 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700834 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700835 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700836 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700837 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700838 dprintf(fd, " Channel count: %u\n", mChannelCount);
839 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800840 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700842 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700843 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 size_t numConfig = mConfigEvents.size();
845 if (numConfig) {
846 for (size_t i = 0; i < numConfig; i++) {
847 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700848 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800849 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700850 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800851 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700852 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800853 }
Andy Hung293558a2017-03-21 12:19:20 -0700854 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700855 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
856 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800857 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800858
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700859 // Dump timestamp statistics for the Thread types that support it.
860 if (mType == RECORD
861 || mType == MIXER
862 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700863 || mType == DIRECT
864 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700865 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700866 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700867 }
868
Eric Laurent81784c32012-11-19 14:55:58 -0800869 if (locked) {
870 mLock.unlock();
871 }
872}
873
874void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
875{
876 const size_t SIZE = 256;
877 char buffer[SIZE];
878 String8 result;
879
Marco Nelissenb2208842014-02-07 14:00:50 -0800880 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000881 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800882 write(fd, buffer, strlen(buffer));
883
Marco Nelissenb2208842014-02-07 14:00:50 -0800884 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800885 sp<EffectChain> chain = mEffectChains[i];
886 if (chain != 0) {
887 chain->dump(fd, args);
888 }
889 }
890}
891
Andy Hungdae27702016-10-31 14:01:16 -0700892void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800893{
894 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700895 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800896}
897
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100898String16 AudioFlinger::ThreadBase::getWakeLockTag()
899{
900 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800901 case MIXER:
902 return String16("AudioMix");
903 case DIRECT:
904 return String16("AudioDirectOut");
905 case DUPLICATING:
906 return String16("AudioDup");
907 case RECORD:
908 return String16("AudioIn");
909 case OFFLOAD:
910 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800911 case MMAP:
912 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800913 default:
914 ALOG_ASSERT(false);
915 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100916 }
917}
918
Andy Hungdae27702016-10-31 14:01:16 -0700919void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800920{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800921 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800922 if (mPowerManager != 0) {
923 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700924 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
925 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700926 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100927 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700928 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800930 if (status == NO_ERROR) {
931 mWakeLockToken = binder;
932 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800933 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800934 }
Wei Jia3f273d12015-11-24 09:06:49 -0800935
Andy Hung3f0c9022016-01-15 17:49:46 -0800936 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800937 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
938 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800939}
940
941void AudioFlinger::ThreadBase::releaseWakeLock()
942{
943 Mutex::Autolock _l(mLock);
944 releaseWakeLock_l();
945}
946
947void AudioFlinger::ThreadBase::releaseWakeLock_l()
948{
Andy Hung3f0c9022016-01-15 17:49:46 -0800949 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800950 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800951 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800952 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700953 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
954 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800955 }
956 mWakeLockToken.clear();
957 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800958}
959
960void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700961 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800962 // use checkService() to avoid blocking if power service is not up yet
963 sp<IBinder> binder =
964 defaultServiceManager()->checkService(String16("power"));
965 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800966 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 } else {
968 mPowerManager = interface_cast<IPowerManager>(binder);
969 binder->linkToDeath(mDeathRecipient);
970 }
971 }
972}
973
Andy Hungd01b0f12016-11-07 16:10:30 -0800974void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700976
977#if !LOG_NDEBUG
978 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800979 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700980 s << uid << " ";
981 }
982 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
983#endif
984
Andy Hung438e7572015-12-14 15:51:17 -0800985 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
986 if (mSystemReady) {
987 ALOGE("no wake lock to update, but system ready!");
988 } else {
989 ALOGW("no wake lock to update, system not ready yet");
990 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800991 return;
992 }
993 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800994 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
995 status_t status = mPowerManager->updateWakeLockUids(
996 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
997 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800998 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800999 }
1000}
1001
Eric Laurent81784c32012-11-19 14:55:58 -08001002void AudioFlinger::ThreadBase::clearPowerManager()
1003{
1004 Mutex::Autolock _l(mLock);
1005 releaseWakeLock_l();
1006 mPowerManager.clear();
1007}
1008
Glenn Kasten0f11b512014-01-31 16:18:54 -08001009void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001010{
1011 sp<ThreadBase> thread = mThread.promote();
1012 if (thread != 0) {
1013 thread->clearPowerManager();
1014 }
1015 ALOGW("power manager service died !!!");
1016}
1017
Eric Laurent81784c32012-11-19 14:55:58 -08001018void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001019 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001020{
1021 sp<EffectChain> chain = getEffectChain_l(sessionId);
1022 if (chain != 0) {
1023 if (type != NULL) {
1024 chain->setEffectSuspended_l(type, suspend);
1025 } else {
1026 chain->setEffectSuspendedAll_l(suspend);
1027 }
1028 }
1029
1030 updateSuspendedSessions_l(type, suspend, sessionId);
1031}
1032
1033void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1034{
1035 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1036 if (index < 0) {
1037 return;
1038 }
1039
1040 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1041 mSuspendedSessions.valueAt(index);
1042
1043 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001044 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001045 for (int j = 0; j < desc->mRefCount; j++) {
1046 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1047 chain->setEffectSuspendedAll_l(true);
1048 } else {
1049 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1050 desc->mType.timeLow);
1051 chain->setEffectSuspended_l(&desc->mType, true);
1052 }
1053 }
1054 }
1055}
1056
1057void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1058 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001059 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001060{
1061 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1062
1063 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1064
1065 if (suspend) {
1066 if (index >= 0) {
1067 sessionEffects = mSuspendedSessions.valueAt(index);
1068 } else {
1069 mSuspendedSessions.add(sessionId, sessionEffects);
1070 }
1071 } else {
1072 if (index < 0) {
1073 return;
1074 }
1075 sessionEffects = mSuspendedSessions.valueAt(index);
1076 }
1077
1078
1079 int key = EffectChain::kKeyForSuspendAll;
1080 if (type != NULL) {
1081 key = type->timeLow;
1082 }
1083 index = sessionEffects.indexOfKey(key);
1084
1085 sp<SuspendedSessionDesc> desc;
1086 if (suspend) {
1087 if (index >= 0) {
1088 desc = sessionEffects.valueAt(index);
1089 } else {
1090 desc = new SuspendedSessionDesc();
1091 if (type != NULL) {
1092 desc->mType = *type;
1093 }
1094 sessionEffects.add(key, desc);
1095 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1096 }
1097 desc->mRefCount++;
1098 } else {
1099 if (index < 0) {
1100 return;
1101 }
1102 desc = sessionEffects.valueAt(index);
1103 if (--desc->mRefCount == 0) {
1104 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1105 sessionEffects.removeItemsAt(index);
1106 if (sessionEffects.isEmpty()) {
1107 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1108 sessionId);
1109 mSuspendedSessions.removeItem(sessionId);
1110 }
1111 }
1112 }
1113 if (!sessionEffects.isEmpty()) {
1114 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1115 }
1116}
1117
1118void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1119 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001120 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001121{
1122 Mutex::Autolock _l(mLock);
1123 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1124}
1125
1126void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1127 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001128 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001129{
1130 if (mType != RECORD) {
1131 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1132 // another session. This gives the priority to well behaved effect control panels
1133 // and applications not using global effects.
1134 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1135 // global effects
1136 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1137 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1138 }
1139 }
1140
1141 sp<EffectChain> chain = getEffectChain_l(sessionId);
1142 if (chain != 0) {
1143 chain->checkSuspendOnEffectEnabled(effect, enabled);
1144 }
1145}
1146
Eric Laurent4c415062016-06-17 16:14:16 -07001147// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1148status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1149 const effect_descriptor_t *desc, audio_session_t sessionId)
1150{
1151 // No global effect sessions on record threads
1152 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1153 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1154 desc->name, mThreadName);
1155 return BAD_VALUE;
1156 }
1157 // only pre processing effects on record thread
1158 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1159 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001163
1164 // always allow effects without processing load or latency
1165 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1166 return NO_ERROR;
1167 }
1168
Eric Laurent4c415062016-06-17 16:14:16 -07001169 audio_input_flags_t flags = mInput->flags;
1170 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1171 if (flags & AUDIO_INPUT_FLAG_RAW) {
1172 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1173 desc->name, mThreadName);
1174 return BAD_VALUE;
1175 }
1176 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1177 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1178 desc->name, mThreadName);
1179 return BAD_VALUE;
1180 }
1181 }
1182 return NO_ERROR;
1183}
1184
1185// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1186status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1187 const effect_descriptor_t *desc, audio_session_t sessionId)
1188{
1189 // no preprocessing on playback threads
1190 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1191 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1192 " thread %s", desc->name, mThreadName);
1193 return BAD_VALUE;
1194 }
1195
Eric Laurent3e4de772017-07-16 16:55:08 -07001196 // always allow effects without processing load or latency
1197 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1198 return NO_ERROR;
1199 }
1200
Eric Laurent4c415062016-06-17 16:14:16 -07001201 switch (mType) {
1202 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001203#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001204 // Reject any effect on mixer multichannel sinks.
1205 // TODO: fix both format and multichannel issues with effects.
1206 if (mChannelCount != FCC_2) {
1207 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1208 " thread %s", desc->name, mChannelCount, mThreadName);
1209 return BAD_VALUE;
1210 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001211#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001212 audio_output_flags_t flags = mOutput->flags;
1213 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1214 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1215 // global effects are applied only to non fast tracks if they are SW
1216 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1217 break;
1218 }
1219 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1220 // only post processing on output stage session
1221 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1222 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1223 " on output stage session", desc->name);
1224 return BAD_VALUE;
1225 }
1226 } else {
1227 // no restriction on effects applied on non fast tracks
1228 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1229 break;
1230 }
1231 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001232
Eric Laurent4c415062016-06-17 16:14:16 -07001233 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1234 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1235 desc->name);
1236 return BAD_VALUE;
1237 }
1238 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1239 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1240 " in fast mode", desc->name);
1241 return BAD_VALUE;
1242 }
1243 }
1244 } break;
1245 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001246 // nothing actionable on offload threads, if the effect:
1247 // - is offloadable: the effect can be created
1248 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1249 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001250 break;
1251 case DIRECT:
1252 // Reject any effect on Direct output threads for now, since the format of
1253 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1254 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1255 desc->name, mThreadName);
1256 return BAD_VALUE;
1257 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001258#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001259 // Reject any effect on mixer multichannel sinks.
1260 // TODO: fix both format and multichannel issues with effects.
1261 if (mChannelCount != FCC_2) {
1262 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1263 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1264 return BAD_VALUE;
1265 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001266#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001267 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1268 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1269 " thread %s", desc->name, mThreadName);
1270 return BAD_VALUE;
1271 }
1272 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1273 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1274 " DUPLICATING thread %s", desc->name, mThreadName);
1275 return BAD_VALUE;
1276 }
1277 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1278 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1279 " DUPLICATING thread %s", desc->name, mThreadName);
1280 return BAD_VALUE;
1281 }
1282 break;
1283 default:
1284 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1285 }
1286
1287 return NO_ERROR;
1288}
1289
Eric Laurent81784c32012-11-19 14:55:58 -08001290// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1291sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1292 const sp<AudioFlinger::Client>& client,
1293 const sp<IEffectClient>& effectClient,
1294 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001295 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001296 effect_descriptor_t *desc,
1297 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001298 status_t *status,
1299 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001300{
1301 sp<EffectModule> effect;
1302 sp<EffectHandle> handle;
1303 status_t lStatus;
1304 sp<EffectChain> chain;
1305 bool chainCreated = false;
1306 bool effectCreated = false;
1307 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001308 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001309
1310 lStatus = initCheck();
1311 if (lStatus != NO_ERROR) {
1312 ALOGW("createEffect_l() Audio driver not initialized.");
1313 goto Exit;
1314 }
1315
Eric Laurent81784c32012-11-19 14:55:58 -08001316 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1317
1318 { // scope for mLock
1319 Mutex::Autolock _l(mLock);
1320
Eric Laurent4c415062016-06-17 16:14:16 -07001321 lStatus = checkEffectCompatibility_l(desc, sessionId);
1322 if (lStatus != NO_ERROR) {
1323 goto Exit;
1324 }
1325
Eric Laurent81784c32012-11-19 14:55:58 -08001326 // check for existing effect chain with the requested audio session
1327 chain = getEffectChain_l(sessionId);
1328 if (chain == 0) {
1329 // create a new chain for this session
1330 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1331 chain = new EffectChain(this, sessionId);
1332 addEffectChain_l(chain);
1333 chain->setStrategy(getStrategyForSession_l(sessionId));
1334 chainCreated = true;
1335 } else {
1336 effect = chain->getEffectFromDesc_l(desc);
1337 }
1338
1339 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1340
1341 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001342 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001343 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001344 lStatus = AudioSystem::registerEffect(
1345 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001346 if (lStatus != NO_ERROR) {
1347 goto Exit;
1348 }
1349 effectRegistered = true;
1350 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001351 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001352 if (lStatus != NO_ERROR) {
1353 goto Exit;
1354 }
1355 effectCreated = true;
1356
1357 effect->setDevice(mOutDevice);
1358 effect->setDevice(mInDevice);
1359 effect->setMode(mAudioFlinger->getMode());
1360 effect->setAudioSource(mAudioSource);
1361 }
1362 // create effect handle and connect it to effect module
1363 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001364 lStatus = handle->initCheck();
1365 if (lStatus == OK) {
1366 lStatus = effect->addHandle(handle.get());
1367 }
Eric Laurent81784c32012-11-19 14:55:58 -08001368 if (enabled != NULL) {
1369 *enabled = (int)effect->isEnabled();
1370 }
1371 }
1372
1373Exit:
1374 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1375 Mutex::Autolock _l(mLock);
1376 if (effectCreated) {
1377 chain->removeEffect_l(effect);
1378 }
1379 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001380 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001381 }
1382 if (chainCreated) {
1383 removeEffectChain_l(chain);
1384 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001385 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001386 }
1387
Glenn Kasten9156ef32013-08-06 15:39:08 -07001388 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001389 return handle;
1390}
1391
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001392void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1393 bool unpinIfLast)
1394{
1395 bool remove = false;
1396 sp<EffectModule> effect;
1397 {
1398 Mutex::Autolock _l(mLock);
1399
1400 effect = handle->effect().promote();
1401 if (effect == 0) {
1402 return;
1403 }
1404 // restore suspended effects if the disconnected handle was enabled and the last one.
1405 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1406 if (remove) {
1407 removeEffect_l(effect, true);
1408 }
1409 }
1410 if (remove) {
1411 mAudioFlinger->updateOrphanEffectChains(effect);
1412 AudioSystem::unregisterEffect(effect->id());
1413 if (handle->enabled()) {
1414 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1415 }
1416 }
1417}
1418
Glenn Kastend848eb42016-03-08 13:42:11 -08001419sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1420 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001421{
1422 Mutex::Autolock _l(mLock);
1423 return getEffect_l(sessionId, effectId);
1424}
1425
Glenn Kastend848eb42016-03-08 13:42:11 -08001426sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1427 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001428{
1429 sp<EffectChain> chain = getEffectChain_l(sessionId);
1430 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1431}
1432
1433// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1434// PlaybackThread::mLock held
1435status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1436{
1437 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001438 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001439 sp<EffectChain> chain = getEffectChain_l(sessionId);
1440 bool chainCreated = false;
1441
Eric Laurent5baf2af2013-09-12 17:37:00 -07001442 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001443 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001444 this, effect->desc().name, effect->desc().flags);
1445
Eric Laurent81784c32012-11-19 14:55:58 -08001446 if (chain == 0) {
1447 // create a new chain for this session
1448 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1449 chain = new EffectChain(this, sessionId);
1450 addEffectChain_l(chain);
1451 chain->setStrategy(getStrategyForSession_l(sessionId));
1452 chainCreated = true;
1453 }
1454 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1455
1456 if (chain->getEffectFromId_l(effect->id()) != 0) {
1457 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1458 this, effect->desc().name, chain.get());
1459 return BAD_VALUE;
1460 }
1461
Eric Laurent5baf2af2013-09-12 17:37:00 -07001462 effect->setOffloaded(mType == OFFLOAD, mId);
1463
Eric Laurent81784c32012-11-19 14:55:58 -08001464 status_t status = chain->addEffect_l(effect);
1465 if (status != NO_ERROR) {
1466 if (chainCreated) {
1467 removeEffectChain_l(chain);
1468 }
1469 return status;
1470 }
1471
1472 effect->setDevice(mOutDevice);
1473 effect->setDevice(mInDevice);
1474 effect->setMode(mAudioFlinger->getMode());
1475 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001476
Eric Laurent81784c32012-11-19 14:55:58 -08001477 return NO_ERROR;
1478}
1479
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001480void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001481
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001482 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001483 effect_descriptor_t desc = effect->desc();
1484 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1485 detachAuxEffect_l(effect->id());
1486 }
1487
1488 sp<EffectChain> chain = effect->chain().promote();
1489 if (chain != 0) {
1490 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001491 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001492 removeEffectChain_l(chain);
1493 }
1494 } else {
1495 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1496 }
1497}
1498
1499void AudioFlinger::ThreadBase::lockEffectChains_l(
1500 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1501{
1502 effectChains = mEffectChains;
1503 for (size_t i = 0; i < mEffectChains.size(); i++) {
1504 mEffectChains[i]->lock();
1505 }
1506}
1507
1508void AudioFlinger::ThreadBase::unlockEffectChains(
1509 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1510{
1511 for (size_t i = 0; i < effectChains.size(); i++) {
1512 effectChains[i]->unlock();
1513 }
1514}
1515
Glenn Kastend848eb42016-03-08 13:42:11 -08001516sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001517{
1518 Mutex::Autolock _l(mLock);
1519 return getEffectChain_l(sessionId);
1520}
1521
Glenn Kastend848eb42016-03-08 13:42:11 -08001522sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1523 const
Eric Laurent81784c32012-11-19 14:55:58 -08001524{
1525 size_t size = mEffectChains.size();
1526 for (size_t i = 0; i < size; i++) {
1527 if (mEffectChains[i]->sessionId() == sessionId) {
1528 return mEffectChains[i];
1529 }
1530 }
1531 return 0;
1532}
1533
1534void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1535{
1536 Mutex::Autolock _l(mLock);
1537 size_t size = mEffectChains.size();
1538 for (size_t i = 0; i < size; i++) {
1539 mEffectChains[i]->setMode_l(mode);
1540 }
1541}
1542
Mikhail Naganovdc769682018-05-04 15:34:08 -07001543void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001544{
1545 config->type = AUDIO_PORT_TYPE_MIX;
1546 config->ext.mix.handle = mId;
1547 config->sample_rate = mSampleRate;
1548 config->format = mFormat;
1549 config->channel_mask = mChannelMask;
1550 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1551 AUDIO_PORT_CONFIG_FORMAT;
1552}
1553
Eric Laurent72e3f392015-05-20 14:43:50 -07001554void AudioFlinger::ThreadBase::systemReady()
1555{
1556 Mutex::Autolock _l(mLock);
1557 if (mSystemReady) {
1558 return;
1559 }
1560 mSystemReady = true;
1561
1562 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1563 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1564 }
1565 mPendingConfigEvents.clear();
1566}
1567
Andy Hungdae27702016-10-31 14:01:16 -07001568template <typename T>
1569ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1570 ssize_t index = mActiveTracks.indexOf(track);
1571 if (index >= 0) {
1572 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1573 return index;
1574 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001575 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001576 mActiveTracksGeneration++;
1577 mLatestActiveTrack = track;
1578 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001579 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001580 return mActiveTracks.add(track);
1581}
1582
1583template <typename T>
1584ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1585 ssize_t index = mActiveTracks.remove(track);
1586 if (index < 0) {
1587 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1588 return index;
1589 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001590 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001591 mActiveTracksGeneration++;
1592 --mBatteryCounter[track->uid()].second;
1593 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001594 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001595#ifdef TEE_SINK
1596 track->dumpTee(-1 /* fd */, "_REMOVE");
1597#endif
Andy Hungdae27702016-10-31 14:01:16 -07001598 return index;
1599}
1600
1601template <typename T>
1602void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1603 for (const sp<T> &track : mActiveTracks) {
1604 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001605 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001606 }
1607 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001608 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001609 mActiveTracks.clear();
1610 mLatestActiveTrack.clear();
1611 mBatteryCounter.clear();
1612}
1613
1614template <typename T>
1615void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1616 sp<ThreadBase> thread, bool force) {
1617 // Updates ActiveTracks client uids to the thread wakelock.
1618 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1619 thread->updateWakeLockUids_l(getWakeLockUids());
1620 mLastActiveTracksGeneration = mActiveTracksGeneration;
1621 }
1622
1623 // Updates BatteryNotifier uids
1624 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1625 const uid_t uid = it->first;
1626 ssize_t &previous = it->second.first;
1627 ssize_t &current = it->second.second;
1628 if (current > 0) {
1629 if (previous == 0) {
1630 BatteryNotifier::getInstance().noteStartAudio(uid);
1631 }
1632 previous = current;
1633 ++it;
1634 } else if (current == 0) {
1635 if (previous > 0) {
1636 BatteryNotifier::getInstance().noteStopAudio(uid);
1637 }
1638 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1639 } else /* (current < 0) */ {
1640 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1641 }
1642 }
1643}
Eric Laurent83b88082014-06-20 18:31:16 -07001644
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001645template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001646bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1647 const bool hasChanged = mHasChanged;
1648 mHasChanged = false;
1649 return hasChanged;
1650}
1651
1652template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001653void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1654 const char *funcName, const sp<T> &track) const {
1655 if (mLocalLog != nullptr) {
1656 String8 result;
1657 track->appendDump(result, false /* active */);
1658 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1659 }
1660}
1661
Eric Laurent6acd1d42017-01-04 14:23:29 -08001662void AudioFlinger::ThreadBase::broadcast_l()
1663{
1664 // Thread could be blocked waiting for async
1665 // so signal it to handle state changes immediately
1666 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1667 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1668 mSignalPending = true;
1669 mWaitWorkCV.broadcast();
1670}
1671
Eric Laurent81784c32012-11-19 14:55:58 -08001672// ----------------------------------------------------------------------------
1673// Playback
1674// ----------------------------------------------------------------------------
1675
1676AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1677 AudioStreamOut* output,
1678 audio_io_handle_t id,
1679 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001680 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001681 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001682 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001683 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001684 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001685 mMixerBuffer(NULL),
1686 mMixerBufferSize(0),
1687 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1688 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001689 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001690 mEffectBuffer(NULL),
1691 mEffectBufferSize(0),
1692 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1693 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001694 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001695 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001696 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001697 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001698 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001699 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001700 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001701 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001702 mMixerStatus(MIXER_IDLE),
1703 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001704 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001705 mBytesRemaining(0),
1706 mCurrentWriteLength(0),
1707 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001708 mWriteAckSequence(0),
1709 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001710 mScreenState(AudioFlinger::mScreenState),
1711 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001712 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001713 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1714 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001715{
Glenn Kastend7dca052015-03-05 16:05:54 -08001716 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1717 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001718
1719 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1720 // it would be safer to explicitly pass initial masterVolume/masterMute as
1721 // parameter.
1722 //
1723 // If the HAL we are using has support for master volume or master mute,
1724 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1725 // and the mute set to false).
1726 mMasterVolume = audioFlinger->masterVolume_l();
1727 mMasterMute = audioFlinger->masterMute_l();
1728 if (mOutput && mOutput->audioHwDev) {
1729 if (mOutput->audioHwDev->canSetMasterVolume()) {
1730 mMasterVolume = 1.0;
1731 }
1732
1733 if (mOutput->audioHwDev->canSetMasterMute()) {
1734 mMasterMute = false;
1735 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001736 mIsMsdDevice = strcmp(
1737 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001738 }
1739
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001740 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001741
Andy Hungc8fddf32018-08-08 18:32:37 -07001742 // TODO: We may also match on address as well as device type for
1743 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1744 if (type == MIXER || type == DIRECT) {
1745 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
1746 "audio.timestamp.corrected_output_devices",
1747 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1748 : AUDIO_DEVICE_NONE));
1749 }
1750
Eric Laurent223fd5c2014-11-11 13:43:36 -08001751 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001752 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001753 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001754 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001755 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1756 }
Eric Laurent98e38192018-02-15 18:31:53 -08001757 // Audio patch volume is always max
1758 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1759 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001760}
1761
1762AudioFlinger::PlaybackThread::~PlaybackThread()
1763{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001764 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001765 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001766 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001767 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001768}
1769
1770void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1771{
1772 dumpInternals(fd, args);
1773 dumpTracks(fd, args);
1774 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001775 dprintf(fd, " Local log:\n");
1776 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001777}
1778
Eric Tan1882f162018-08-02 18:05:39 -07001779Json::Value AudioFlinger::PlaybackThread::getJsonDump() const
Eric Tan7b651152018-07-13 10:17:19 -07001780{
Eric Tan1882f162018-08-02 18:05:39 -07001781 return Json::Value(Json::objectValue);
Eric Tan7b651152018-07-13 10:17:19 -07001782}
1783
Glenn Kasten0f11b512014-01-31 16:18:54 -08001784void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001785{
Eric Laurent81784c32012-11-19 14:55:58 -08001786 String8 result;
1787
Marco Nelissenb2208842014-02-07 14:00:50 -08001788 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001789 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1790 const stream_type_t *st = &mStreamTypes[i];
1791 if (i > 0) {
1792 result.appendFormat(", ");
1793 }
1794 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1795 if (st->mute) {
1796 result.append("M");
1797 }
1798 }
1799 result.append("\n");
1800 write(fd, result.string(), result.length());
1801 result.clear();
1802
Eric Laurent81784c32012-11-19 14:55:58 -08001803 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1804 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001805 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001806 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001807
1808 size_t numtracks = mTracks.size();
1809 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001810 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001811 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001812 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001813 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001814 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001815 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001816 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001817 for (size_t i = 0; i < numtracks; ++i) {
1818 sp<Track> track = mTracks[i];
1819 if (track != 0) {
1820 bool active = mActiveTracks.indexOf(track) >= 0;
1821 if (active) {
1822 numactiveseen++;
1823 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001824 result.append(prefix);
1825 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001826 }
1827 }
1828 } else {
1829 result.append("\n");
1830 }
1831 if (numactiveseen != numactive) {
1832 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001833 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001834 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001835 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001836 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001837 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001838 sp<Track> track = mActiveTracks[i];
1839 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001840 result.append(prefix);
1841 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001842 }
1843 }
1844 }
1845
1846 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001847}
1848
1849void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1850{
Glenn Kasten44182c22015-03-05 17:12:23 -08001851 dumpBase(fd, args);
1852
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001853 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Elliott Hughes87cebad2014-05-22 10:14:43 -07001854 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001855 dprintf(fd, " Last write occurred (msecs): %llu\n",
1856 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001857 dprintf(fd, " Total writes: %d\n", mNumWrites);
1858 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1859 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1860 dprintf(fd, " Suspend count: %d\n", mSuspended);
1861 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1862 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1863 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1864 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001865 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001866 AudioStreamOut *output = mOutput;
1867 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001868 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1869 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001870 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1871 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1872 if (mPipeSink.get() != nullptr) {
1873 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1874 }
1875 if (output != nullptr) {
1876 dprintf(fd, " Hal stream dump:\n");
1877 (void)output->stream->dump(fd);
1878 }
Eric Laurent81784c32012-11-19 14:55:58 -08001879}
1880
1881// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001882
1883void AudioFlinger::PlaybackThread::onFirstRef()
1884{
Glenn Kastend7dca052015-03-05 16:05:54 -08001885 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001886}
1887
1888// ThreadBase virtuals
1889void AudioFlinger::PlaybackThread::preExit()
1890{
1891 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001892 // FIXME this is using hard-coded strings but in the future, this functionality will be
1893 // converted to use audio HAL extensions required to support tunneling
1894 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1895 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001896}
1897
1898// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1899sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1900 const sp<AudioFlinger::Client>& client,
1901 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001902 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001903 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001904 audio_format_t format,
1905 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001906 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001907 size_t *pNotificationFrameCount,
1908 uint32_t notificationsPerBuffer,
1909 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001910 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001911 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001912 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001913 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001914 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001915 status_t *status,
1916 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001917{
Glenn Kasten74935e42013-12-19 08:56:45 -08001918 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001919 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001920 sp<Track> track;
1921 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001922 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001923 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001924 uint32_t sampleRate;
1925
1926 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1927 lStatus = BAD_VALUE;
1928 goto Exit;
1929 }
Eric Laurent21da6472017-11-09 16:29:26 -08001930
1931 if (*pSampleRate == 0) {
1932 *pSampleRate = mSampleRate;
1933 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001934 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001935
1936 // special case for FAST flag considered OK if fast mixer is present
1937 if (hasFastMixer()) {
1938 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1939 }
1940
1941 // Check if requested flags are compatible with output stream flags
1942 if ((*flags & outputFlags) != *flags) {
1943 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1944 *flags, outputFlags);
1945 *flags = (audio_output_flags_t)(*flags & outputFlags);
1946 }
Eric Laurent81784c32012-11-19 14:55:58 -08001947
Eric Laurent81784c32012-11-19 14:55:58 -08001948 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001949 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001950 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001951 // PCM data
1952 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001953 // TODO: extract as a data library function that checks that a computationally
1954 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001955 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001956 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1957 (channelMask == AUDIO_CHANNEL_OUT_MONO
1958 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001959 // hardware sample rate
1960 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001961 // normal mixer has an associated fast mixer
1962 hasFastMixer() &&
1963 // there are sufficient fast track slots available
1964 (mFastTrackAvailMask != 0)
1965 // FIXME test that MixerThread for this fast track has a capable output HAL
1966 // FIXME add a permission test also?
1967 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001968 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1969 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001970 // read the fast track multiplier property the first time it is needed
1971 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1972 if (ok != 0) {
1973 ALOGE("%s pthread_once failed: %d", __func__, ok);
1974 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001975 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001976 }
Eric Laurent4c415062016-06-17 16:14:16 -07001977
1978 // check compatibility with audio effects.
1979 { // scope for mLock
1980 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001981 for (audio_session_t session : {
1982 AUDIO_SESSION_OUTPUT_STAGE,
1983 AUDIO_SESSION_OUTPUT_MIX,
1984 sessionId,
1985 }) {
1986 sp<EffectChain> chain = getEffectChain_l(session);
1987 if (chain.get() != nullptr) {
1988 audio_output_flags_t old = *flags;
1989 chain->checkOutputFlagCompatibility(flags);
1990 if (old != *flags) {
1991 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1992 (int)session, (int)old, (int)*flags);
1993 }
Eric Laurent4c415062016-06-17 16:14:16 -07001994 }
1995 }
1996 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001997 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001998 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1999 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002000 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002001 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2002 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002003 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002004 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002005 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002006 audio_is_linear_pcm(format),
2007 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002008 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002009 }
2010 }
Eric Laurent21da6472017-11-09 16:29:26 -08002011
2012 if (!audio_has_proportional_frames(format)) {
2013 if (sharedBuffer != 0) {
2014 // Same comment as below about ignoring frameCount parameter for set()
2015 frameCount = sharedBuffer->size();
2016 } else if (frameCount == 0) {
2017 frameCount = mNormalFrameCount;
2018 }
2019 if (notificationFrameCount != frameCount) {
2020 notificationFrameCount = frameCount;
2021 }
2022 } else if (sharedBuffer != 0) {
2023 // FIXME: Ensure client side memory buffers need
2024 // not have additional alignment beyond sample
2025 // (e.g. 16 bit stereo accessed as 32 bit frame).
2026 size_t alignment = audio_bytes_per_sample(format);
2027 if (alignment & 1) {
2028 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2029 alignment = 1;
2030 }
2031 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2032 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2033 if (channelCount > 1) {
2034 // More than 2 channels does not require stronger alignment than stereo
2035 alignment <<= 1;
2036 }
2037 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2038 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2039 sharedBuffer->pointer(), channelCount);
2040 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002041 goto Exit;
2042 }
Eric Laurent21da6472017-11-09 16:29:26 -08002043
2044 // When initializing a shared buffer AudioTrack via constructors,
2045 // there's no frameCount parameter.
2046 // But when initializing a shared buffer AudioTrack via set(),
2047 // there _is_ a frameCount parameter. We silently ignore it.
2048 frameCount = sharedBuffer->size() / frameSize;
2049 } else {
2050 size_t minFrameCount = 0;
2051 // For fast tracks we try to respect the application's request for notifications per buffer.
2052 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2053 if (notificationsPerBuffer > 0) {
2054 // Avoid possible arithmetic overflow during multiplication.
2055 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2056 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2057 notificationsPerBuffer, mFrameCount);
2058 } else {
2059 minFrameCount = mFrameCount * notificationsPerBuffer;
2060 }
2061 }
2062 } else {
2063 // For normal PCM streaming tracks, update minimum frame count.
2064 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2065 // cover audio hardware latency.
2066 // This is probably too conservative, but legacy application code may depend on it.
2067 // If you change this calculation, also review the start threshold which is related.
2068 uint32_t latencyMs = latency_l();
2069 if (latencyMs == 0) {
2070 ALOGE("Error when retrieving output stream latency");
2071 lStatus = UNKNOWN_ERROR;
2072 goto Exit;
2073 }
2074
2075 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2076 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2077
Eric Laurent81784c32012-11-19 14:55:58 -08002078 }
Eric Laurent21da6472017-11-09 16:29:26 -08002079 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002080 frameCount = minFrameCount;
2081 }
Eric Laurent81784c32012-11-19 14:55:58 -08002082 }
Eric Laurent21da6472017-11-09 16:29:26 -08002083
2084 // Make sure that application is notified with sufficient margin before underrun.
2085 // The client can divide the AudioTrack buffer into sub-buffers,
2086 // and expresses its desire to server as the notification frame count.
2087 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2088 size_t maxNotificationFrames;
2089 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2090 // notify every HAL buffer, regardless of the size of the track buffer
2091 maxNotificationFrames = mFrameCount;
2092 } else {
2093 // For normal tracks, use at least double-buffering if no sample rate conversion,
2094 // or at least triple-buffering if there is sample rate conversion
2095 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2096 maxNotificationFrames = frameCount / nBuffering;
2097 // If client requested a fast track but this was denied, then use the smaller maximum.
2098 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2099 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2100 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2101 maxNotificationFrames = maxNotificationFramesFastDenied;
2102 }
2103 }
2104 }
2105 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2106 if (notificationFrameCount == 0) {
2107 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2108 maxNotificationFrames, frameCount);
2109 } else {
2110 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2111 notificationFrameCount, maxNotificationFrames, frameCount);
2112 }
2113 notificationFrameCount = maxNotificationFrames;
2114 }
2115 }
2116
Glenn Kasten74935e42013-12-19 08:56:45 -08002117 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002118 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002119
Glenn Kastenc3df8382014-03-13 15:05:25 -07002120 switch (mType) {
2121
2122 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002123 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002124 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002125 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2126 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002127 sampleRate, format, channelMask, mOutput, mFormat);
2128 lStatus = BAD_VALUE;
2129 goto Exit;
2130 }
2131 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002132 break;
2133
2134 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002136 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2137 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002138 sampleRate, format, channelMask, mOutput, mFormat);
2139 lStatus = BAD_VALUE;
2140 goto Exit;
2141 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002142 break;
2143
2144 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002145 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002146 ALOGE("createTrack_l() Bad parameter: format %#x \""
2147 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002148 format, mOutput, mFormat);
2149 lStatus = BAD_VALUE;
2150 goto Exit;
2151 }
Andy Hungcd044842014-08-07 11:04:34 -07002152 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002153 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2154 lStatus = BAD_VALUE;
2155 goto Exit;
2156 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002157 break;
2158
Eric Laurent81784c32012-11-19 14:55:58 -08002159 }
2160
2161 lStatus = initCheck();
2162 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002163 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002164 goto Exit;
2165 }
2166
2167 { // scope for mLock
2168 Mutex::Autolock _l(mLock);
2169
2170 // all tracks in same audio session must share the same routing strategy otherwise
2171 // conflicts will happen when tracks are moved from one output to another by audio policy
2172 // manager
2173 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2174 for (size_t i = 0; i < mTracks.size(); ++i) {
2175 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002176 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002177 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2178 if (sessionId == t->sessionId() && strategy != actual) {
2179 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2180 strategy, actual);
2181 lStatus = BAD_VALUE;
2182 goto Exit;
2183 }
2184 }
2185 }
2186
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002187 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002188 channelMask, frameCount,
2189 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002190 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002191
Glenn Kasten03003332013-08-06 15:40:54 -07002192 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2193 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002194 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002195 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002196 goto Exit;
2197 }
2198 mTracks.add(track);
2199
2200 sp<EffectChain> chain = getEffectChain_l(sessionId);
2201 if (chain != 0) {
2202 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2203 track->setMainBuffer(chain->inBuffer());
2204 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2205 chain->incTrackCnt();
2206 }
2207
Eric Laurent05067782016-06-01 18:27:28 -07002208 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002209 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2210 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2211 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002212 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002213 }
2214 }
2215
2216 lStatus = NO_ERROR;
2217
2218Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002219 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002220 return track;
2221}
2222
Andy Hung1bc088a2018-02-09 15:57:31 -08002223template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002224ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2225{
Andy Hungc0691382018-09-12 18:01:57 -07002226 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002227 const ssize_t index = mTracks.remove(track);
2228 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002229 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002230 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002231 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002232 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002233 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002234 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002235 }
2236 return index;
2237}
2238
Eric Laurent81784c32012-11-19 14:55:58 -08002239uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2240{
2241 return latency;
2242}
2243
2244uint32_t AudioFlinger::PlaybackThread::latency() const
2245{
2246 Mutex::Autolock _l(mLock);
2247 return latency_l();
2248}
2249uint32_t AudioFlinger::PlaybackThread::latency_l() const
2250{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002251 uint32_t latency;
2252 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2253 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002254 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002255 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002256}
2257
2258void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2259{
2260 Mutex::Autolock _l(mLock);
2261 // Don't apply master volume in SW if our HAL can do it for us.
2262 if (mOutput && mOutput->audioHwDev &&
2263 mOutput->audioHwDev->canSetMasterVolume()) {
2264 mMasterVolume = 1.0;
2265 } else {
2266 mMasterVolume = value;
2267 }
2268}
2269
2270void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2271{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002272 if (isDuplicating()) {
2273 return;
2274 }
Eric Laurent81784c32012-11-19 14:55:58 -08002275 Mutex::Autolock _l(mLock);
2276 // Don't apply master mute in SW if our HAL can do it for us.
2277 if (mOutput && mOutput->audioHwDev &&
2278 mOutput->audioHwDev->canSetMasterMute()) {
2279 mMasterMute = false;
2280 } else {
2281 mMasterMute = muted;
2282 }
2283}
2284
2285void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2286{
2287 Mutex::Autolock _l(mLock);
2288 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002289 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002290}
2291
2292void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2293{
2294 Mutex::Autolock _l(mLock);
2295 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002296 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002297}
2298
2299float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2300{
2301 Mutex::Autolock _l(mLock);
2302 return mStreamTypes[stream].volume;
2303}
2304
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002305void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2306{
2307 mOutput->stream->setVolume(left, right);
2308}
2309
Eric Laurent81784c32012-11-19 14:55:58 -08002310// addTrack_l() must be called with ThreadBase::mLock held
2311status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2312{
2313 status_t status = ALREADY_EXISTS;
2314
Eric Laurent81784c32012-11-19 14:55:58 -08002315 if (mActiveTracks.indexOf(track) < 0) {
2316 // the track is newly added, make sure it fills up all its
2317 // buffers before playing. This is to ensure the client will
2318 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002319 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002320 TrackBase::track_state state = track->mState;
2321 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002322 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323 mLock.lock();
2324 // abort track was stopped/paused while we released the lock
2325 if (state != track->mState) {
2326 if (status == NO_ERROR) {
2327 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002328 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329 mLock.lock();
2330 }
2331 return INVALID_OPERATION;
2332 }
2333 // abort if start is rejected by audio policy manager
2334 if (status != NO_ERROR) {
2335 return PERMISSION_DENIED;
2336 }
2337#ifdef ADD_BATTERY_DATA
2338 // to track the speaker usage
2339 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2340#endif
2341 }
2342
Eric Laurent51716182016-02-29 18:00:56 -08002343 // set retry count for buffer fill
2344 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002345 if (track->isStopping_1()) {
2346 track->mRetryCount = kMaxTrackStopRetriesOffload;
2347 } else {
2348 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2349 }
2350 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002351 } else {
2352 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002353 track->mFillingUpStatus =
2354 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002355 }
2356
Eric Laurent81784c32012-11-19 14:55:58 -08002357 track->mResetDone = false;
2358 track->mPresentationCompleteFrames = 0;
2359 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002360 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2361 if (chain != 0) {
2362 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2363 track->sessionId());
2364 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002365 }
2366
2367 status = NO_ERROR;
2368 }
2369
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002370 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002371 return status;
2372}
2373
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002375{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002377 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002378 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2379 track->mState = TrackBase::STOPPED;
2380 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002381 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002382 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002384 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002385
2386 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002387}
2388
2389void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2390{
2391 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002392
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002393 String8 result;
2394 track->appendDump(result, false /* active */);
2395 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002396
Eric Laurent81784c32012-11-19 14:55:58 -08002397 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002398 if (track->isFastTrack()) {
2399 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002400 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002401 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2402 mFastTrackAvailMask |= 1 << index;
2403 // redundant as track is about to be destroyed, for dumpsys only
2404 track->mFastIndex = -1;
2405 }
2406 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2407 if (chain != 0) {
2408 chain->decTrackCnt();
2409 }
2410}
2411
2412String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2413{
Eric Laurent81784c32012-11-19 14:55:58 -08002414 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002415 String8 out_s8;
2416 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2417 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002418 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002419 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002420}
2421
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002422void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002423 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2424 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002425
Eric Laurent73e26b62015-04-27 16:55:58 -07002426 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002427
2428 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002429 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002430 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002431 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002432 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002433 desc->mChannelMask = mChannelMask;
2434 desc->mSamplingRate = mSampleRate;
2435 desc->mFormat = mFormat;
2436 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002438 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002439 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002440 break;
2441
Eric Laurent73e26b62015-04-27 16:55:58 -07002442 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002443 default:
2444 break;
2445 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002446 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002447}
2448
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002449void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002450{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002451 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002452}
2453
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002454void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002456 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002457}
2458
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002459void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002460{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002461 mCallbackThread->setAsyncError();
2462}
2463
Eric Laurent3b4529e2013-09-05 18:09:19 -07002464void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002465{
2466 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002467 // reject out of sequence requests
2468 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2469 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002470 mWaitWorkCV.signal();
2471 }
2472}
2473
Eric Laurent3b4529e2013-09-05 18:09:19 -07002474void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002475{
2476 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002477 // reject out of sequence requests
2478 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002479 // Register discontinuity when HW drain is completed because that can cause
2480 // the timestamp frame position to reset to 0 for direct and offload threads.
2481 // (Out of sequence requests are ignored, since the discontinuity would be handled
2482 // elsewhere, e.g. in flush).
2483 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002484 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002485 mWaitWorkCV.signal();
2486 }
2487}
2488
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002489void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002490{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002491 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002492 mSampleRate = mOutput->getSampleRate();
2493 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002494 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002495 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002496 }
Andy Hung9a592762014-07-21 21:56:01 -07002497 if ((mType == MIXER || mType == DUPLICATING)
2498 && !isValidPcmSinkChannelMask(mChannelMask)) {
2499 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2500 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002501 }
Andy Hunge5412692014-05-16 11:25:07 -07002502 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002503
2504 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002505 status_t result = mOutput->stream->getFormat(&mHALFormat);
2506 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002507 // Get format from the shim, which will be different than the HAL format
2508 // if playing compressed audio over HDMI passthrough.
2509 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002510 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002511 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002512 }
Andy Hung6146c082014-03-18 11:56:15 -07002513 if ((mType == MIXER || mType == DUPLICATING)
2514 && !isValidPcmSinkFormat(mFormat)) {
2515 LOG_FATAL("HAL format %#x not supported for mixed output",
2516 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002517 }
Phil Burk062e67a2015-02-11 13:40:50 -08002518 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002519 result = mOutput->stream->getBufferSize(&mBufferSize);
2520 LOG_ALWAYS_FATAL_IF(result != OK,
2521 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002522 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002523 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002524 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002525 mFrameCount);
2526 }
2527
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002528 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2529 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002530 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002531 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002532 }
2533 }
2534
Eric Laurentd1f69b02014-12-15 14:33:13 -08002535 mHwSupportsPause = false;
2536 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002537 bool supportsPause = false, supportsResume = false;
2538 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2539 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002540 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002541 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002542 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543 } else if (supportsResume) {
2544 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002545 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002546 }
2547 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002548 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2549 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2550 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002551
Andy Hungfbfc3952015-01-15 13:33:51 -08002552 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2553 // For best precision, we use float instead of the associated output
2554 // device format (typically PCM 16 bit).
2555
2556 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2557 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2558 mBufferSize = mFrameSize * mFrameCount;
2559
2560 // TODO: We currently use the associated output device channel mask and sample rate.
2561 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2562 // (if a valid mask) to avoid premature downmix.
2563 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2564 // instead of the output device sample rate to avoid loss of high frequency information.
2565 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2566 }
2567
Andy Hung09a50072014-02-27 14:30:47 -08002568 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002569 double multiplier = 1.0;
2570 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2571 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002572 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2573 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002574
Eric Laurent81784c32012-11-19 14:55:58 -08002575 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2576 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2577 maxNormalFrameCount = maxNormalFrameCount & ~15;
2578 if (maxNormalFrameCount < minNormalFrameCount) {
2579 maxNormalFrameCount = minNormalFrameCount;
2580 }
2581 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2582 if (multiplier <= 1.0) {
2583 multiplier = 1.0;
2584 } else if (multiplier <= 2.0) {
2585 if (2 * mFrameCount <= maxNormalFrameCount) {
2586 multiplier = 2.0;
2587 } else {
2588 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2589 }
2590 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002591 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002592 }
2593 }
2594 mNormalFrameCount = multiplier * mFrameCount;
2595 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002596 if (mType == MIXER || mType == DUPLICATING) {
2597 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2598 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002599 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002600 mNormalFrameCount);
2601
Andy Hung08fb1742015-05-31 23:22:10 -07002602 // Check if we want to throttle the processing to no more than 2x normal rate
2603 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002604 mThreadThrottleTimeMs = 0;
2605 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002606 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2607
Andy Hung010a1a12014-03-13 13:57:33 -07002608 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2609 // Originally this was int16_t[] array, need to remove legacy implications.
2610 free(mSinkBuffer);
2611 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002612 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2613 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2614 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002615 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002616
Andy Hung69aed5f2014-02-25 17:24:40 -08002617 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2618 // drives the output.
2619 free(mMixerBuffer);
2620 mMixerBuffer = NULL;
2621 if (mMixerBufferEnabled) {
2622 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2623 mMixerBufferSize = mNormalFrameCount * mChannelCount
2624 * audio_bytes_per_sample(mMixerBufferFormat);
2625 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2626 }
Andy Hung98ef9782014-03-04 14:46:50 -08002627 free(mEffectBuffer);
2628 mEffectBuffer = NULL;
2629 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002630 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002631 mEffectBufferSize = mNormalFrameCount * mChannelCount
2632 * audio_bytes_per_sample(mEffectBufferFormat);
2633 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2634 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002635
Eric Laurent81784c32012-11-19 14:55:58 -08002636 // force reconfiguration of effect chains and engines to take new buffer size and audio
2637 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002638 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002639 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2640 // matter.
2641 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2642 Vector< sp<EffectChain> > effectChains = mEffectChains;
2643 for (size_t i = 0; i < effectChains.size(); i ++) {
2644 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2645 }
2646}
2647
Kevin Rocard069c2712018-03-29 19:09:14 -07002648void AudioFlinger::PlaybackThread::updateMetadata_l()
2649{
Kevin Rocard12381092018-04-11 09:19:59 -07002650 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2651 return; // That should not happen
2652 }
2653 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2654 for (const sp<Track> &track : mActiveTracks) {
2655 // Do not short-circuit as all hasChanged states must be reset
2656 // as all the metadata are going to be sent
2657 hasChanged |= track->readAndClearHasChanged();
2658 }
2659 if (!hasChanged) {
2660 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002661 }
2662 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002663 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002664 for (const sp<Track> &track : mActiveTracks) {
2665 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002666 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002667 }
Kevin Rocard12381092018-04-11 09:19:59 -07002668 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002669}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002670
Kevin Rocard12381092018-04-11 09:19:59 -07002671void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2672 const StreamOutHalInterface::SourceMetadata& metadata)
2673{
2674 mOutput->stream->updateSourceMetadata(metadata);
2675};
2676
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002677status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002678{
2679 if (halFrames == NULL || dspFrames == NULL) {
2680 return BAD_VALUE;
2681 }
2682 Mutex::Autolock _l(mLock);
2683 if (initCheck() != NO_ERROR) {
2684 return INVALID_OPERATION;
2685 }
Andy Hung818e7a32016-02-16 18:08:07 -08002686 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002687 *halFrames = framesWritten;
2688
2689 if (isSuspended()) {
2690 // return an estimation of rendered frames when the output is suspended
2691 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002692 *dspFrames = (uint32_t)
2693 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002694 return NO_ERROR;
2695 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002696 status_t status;
2697 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002698 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002699 *dspFrames = (size_t)frames;
2700 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002701 }
2702}
2703
Eric Laurent4c415062016-06-17 16:14:16 -07002704// hasAudioSession_l() must be called with ThreadBase::mLock held
2705uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002706{
Eric Laurent81784c32012-11-19 14:55:58 -08002707 uint32_t result = 0;
2708 if (getEffectChain_l(sessionId) != 0) {
2709 result = EFFECT_SESSION;
2710 }
2711
2712 for (size_t i = 0; i < mTracks.size(); ++i) {
2713 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002714 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002715 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002716 if (track->isFastTrack()) {
2717 result |= FAST_SESSION;
2718 }
Eric Laurent81784c32012-11-19 14:55:58 -08002719 break;
2720 }
2721 }
2722
2723 return result;
2724}
2725
Glenn Kastend848eb42016-03-08 13:42:11 -08002726uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002727{
2728 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2729 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2730 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2731 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2732 }
2733 for (size_t i = 0; i < mTracks.size(); i++) {
2734 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002735 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002736 return AudioSystem::getStrategyForStream(track->streamType());
2737 }
2738 }
2739 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2740}
2741
2742
Phil Burk062e67a2015-02-11 13:40:50 -08002743AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002744{
2745 Mutex::Autolock _l(mLock);
2746 return mOutput;
2747}
2748
Phil Burk062e67a2015-02-11 13:40:50 -08002749AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002750{
2751 Mutex::Autolock _l(mLock);
2752 AudioStreamOut *output = mOutput;
2753 mOutput = NULL;
2754 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2755 // must push a NULL and wait for ack
2756 mOutputSink.clear();
2757 mPipeSink.clear();
2758 mNormalSink.clear();
2759 return output;
2760}
2761
2762// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002763sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002764{
2765 if (mOutput == NULL) {
2766 return NULL;
2767 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002768 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002769}
2770
2771uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2772{
2773 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2774}
2775
2776status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2777{
2778 if (!isValidSyncEvent(event)) {
2779 return BAD_VALUE;
2780 }
2781
2782 Mutex::Autolock _l(mLock);
2783
2784 for (size_t i = 0; i < mTracks.size(); ++i) {
2785 sp<Track> track = mTracks[i];
2786 if (event->triggerSession() == track->sessionId()) {
2787 (void) track->setSyncEvent(event);
2788 return NO_ERROR;
2789 }
2790 }
2791
2792 return NAME_NOT_FOUND;
2793}
2794
2795bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2796{
2797 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2798}
2799
2800void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2801 const Vector< sp<Track> >& tracksToRemove)
2802{
2803 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002804 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002805 for (size_t i = 0 ; i < count ; i++) {
2806 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002807 if (track->isExternalTrack()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002808 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002809#ifdef ADD_BATTERY_DATA
2810 // to track the speaker usage
2811 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2812#endif
2813 if (track->isTerminated()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002814 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002815 }
Eric Laurent81784c32012-11-19 14:55:58 -08002816 }
2817 }
2818 }
Eric Laurent81784c32012-11-19 14:55:58 -08002819}
2820
2821void AudioFlinger::PlaybackThread::checkSilentMode_l()
2822{
2823 if (!mMasterMute) {
2824 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002825 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2826 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2827 return;
2828 }
Eric Laurent81784c32012-11-19 14:55:58 -08002829 if (property_get("ro.audio.silent", value, "0") > 0) {
2830 char *endptr;
2831 unsigned long ul = strtoul(value, &endptr, 0);
2832 if (*endptr == '\0' && ul != 0) {
2833 ALOGD("Silence is golden");
2834 // The setprop command will not allow a property to be changed after
2835 // the first time it is set, so we don't have to worry about un-muting.
2836 setMasterMute_l(true);
2837 }
2838 }
2839 }
2840}
2841
2842// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002843ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002844{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002845 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002846 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002847 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002848 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002849
2850 // If an NBAIO sink is present, use it to write the normal mixer's submix
2851 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002852
Andy Hung010a1a12014-03-13 13:57:33 -07002853 const size_t count = mBytesRemaining / mFrameSize;
2854
Simon Wilson2d590962012-11-29 15:18:50 -08002855 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002856 // update the setpoint when AudioFlinger::mScreenState changes
2857 uint32_t screenState = AudioFlinger::mScreenState;
2858 if (screenState != mScreenState) {
2859 mScreenState = screenState;
2860 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2861 if (pipe != NULL) {
2862 pipe->setAvgFrames((mScreenState & 1) ?
2863 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2864 }
2865 }
Andy Hung010a1a12014-03-13 13:57:33 -07002866 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002867 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002868 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002869 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002870#ifdef TEE_SINK
2871 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2872#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002873 } else {
2874 bytesWritten = framesWritten;
2875 }
2876 // otherwise use the HAL / AudioStreamOut directly
2877 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002879
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002881 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2882 mWriteAckSequence += 2;
2883 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002885 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002887 // FIXME We should have an implementation of timestamps for direct output threads.
2888 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002889 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002890
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 if (mUseAsyncWrite &&
2892 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2893 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002894 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002896 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 }
Eric Laurent81784c32012-11-19 14:55:58 -08002898 }
2899
Eric Laurent81784c32012-11-19 14:55:58 -08002900 mNumWrites++;
2901 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002902 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 return bytesWritten;
2904}
2905
2906void AudioFlinger::PlaybackThread::threadLoop_drain()
2907{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002908 bool supportsDrain = false;
2909 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2911 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002912 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2913 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002915 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002917 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002918 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 }
2920}
2921
2922void AudioFlinger::PlaybackThread::threadLoop_exit()
2923{
Eric Laurent275e8e92014-11-30 15:14:47 -08002924 {
2925 Mutex::Autolock _l(mLock);
2926 for (size_t i = 0; i < mTracks.size(); i++) {
2927 sp<Track> track = mTracks[i];
2928 track->invalidate();
2929 }
Andy Hungdae27702016-10-31 14:01:16 -07002930 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2931 // After we exit there are no more track changes sent to BatteryNotifier
2932 // because that requires an active threadLoop.
2933 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2934 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002935 }
Eric Laurent81784c32012-11-19 14:55:58 -08002936}
2937
2938/*
2939The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002940 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002941 - mActiveSleepTimeUs from activeSleepTimeUs()
2942 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002943 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2944 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002945 - maxPeriod from frame count and sample rate (MIXER only)
2946
2947The parameters that affect these derived values are:
2948 - frame count
2949 - frame size
2950 - sample rate
2951 - device type: A2DP or not
2952 - device latency
2953 - format: PCM or not
2954 - active sleep time
2955 - idle sleep time
2956*/
2957
2958void AudioFlinger::PlaybackThread::cacheParameters_l()
2959{
Andy Hung25c2dac2014-02-27 14:56:00 -08002960 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002961 mActiveSleepTimeUs = activeSleepTimeUs();
2962 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002963
2964 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2965 // truncating audio when going to standby.
2966 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2967 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2968 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2969 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2970 }
2971 }
Eric Laurent81784c32012-11-19 14:55:58 -08002972}
2973
Eric Laurent13084622016-05-17 10:51:49 -07002974bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002975{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002976 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002977 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002978 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002979 size_t size = mTracks.size();
2980 for (size_t i = 0; i < size; i++) {
2981 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002982 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002983 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002984 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002985 }
2986 }
Eric Laurent13084622016-05-17 10:51:49 -07002987 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002988}
2989
Haynes Mathew George05317d22016-05-03 16:34:26 -07002990void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2991{
2992 Mutex::Autolock _l(mLock);
2993 invalidateTracks_l(streamType);
2994}
2995
Eric Laurent81784c32012-11-19 14:55:58 -08002996status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2997{
Glenn Kastend848eb42016-03-08 13:42:11 -08002998 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002999 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003000 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003001 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3002 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3003 &halInBuffer);
3004 if (result != OK) return result;
3005 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003006 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003007 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003008 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003009 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003010 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003011 if (mType != DIRECT) {
3012 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003013 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003014 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003015 &halInBuffer);
3016 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003017#ifdef FLOAT_EFFECT_CHAIN
3018 buffer = halInBuffer->audioBuffer()->f32;
3019#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003020 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003021#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003022 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3023 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003024 }
3025
3026 // Attach all tracks with same session ID to this chain.
3027 for (size_t i = 0; i < mTracks.size(); ++i) {
3028 sp<Track> track = mTracks[i];
3029 if (session == track->sessionId()) {
3030 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3031 buffer);
3032 track->setMainBuffer(buffer);
3033 chain->incTrackCnt();
3034 }
3035 }
3036
3037 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003038 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003039 if (session == track->sessionId()) {
3040 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3041 chain->incActiveTrackCnt();
3042 }
3043 }
3044 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003045 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003046 chain->setInBuffer(halInBuffer);
3047 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003048 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003049 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003050 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3051 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003052 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003053 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003054 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003055 // Effect chain for other sessions are inserted at beginning of effect
3056 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003057 // sessions is not important.
3058 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3059 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3060 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003061 size_t size = mEffectChains.size();
3062 size_t i = 0;
3063 for (i = 0; i < size; i++) {
3064 if (mEffectChains[i]->sessionId() < session) {
3065 break;
3066 }
3067 }
3068 mEffectChains.insertAt(chain, i);
3069 checkSuspendOnAddEffectChain_l(chain);
3070
3071 return NO_ERROR;
3072}
3073
3074size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3075{
Glenn Kastend848eb42016-03-08 13:42:11 -08003076 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003077
3078 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3079
3080 for (size_t i = 0; i < mEffectChains.size(); i++) {
3081 if (chain == mEffectChains[i]) {
3082 mEffectChains.removeAt(i);
3083 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003084 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003085 if (session == track->sessionId()) {
3086 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3087 chain.get(), session);
3088 chain->decActiveTrackCnt();
3089 }
3090 }
3091
3092 // detach all tracks with same session ID from this chain
3093 for (size_t i = 0; i < mTracks.size(); ++i) {
3094 sp<Track> track = mTracks[i];
3095 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003096 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003097 chain->decTrackCnt();
3098 }
3099 }
3100 break;
3101 }
3102 }
3103 return mEffectChains.size();
3104}
3105
3106status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003107 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003108{
3109 Mutex::Autolock _l(mLock);
3110 return attachAuxEffect_l(track, EffectId);
3111}
3112
3113status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003114 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003115{
3116 status_t status = NO_ERROR;
3117
3118 if (EffectId == 0) {
3119 track->setAuxBuffer(0, NULL);
3120 } else {
3121 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3122 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3123 if (effect != 0) {
3124 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3125 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3126 } else {
3127 status = INVALID_OPERATION;
3128 }
3129 } else {
3130 status = BAD_VALUE;
3131 }
3132 }
3133 return status;
3134}
3135
3136void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3137{
3138 for (size_t i = 0; i < mTracks.size(); ++i) {
3139 sp<Track> track = mTracks[i];
3140 if (track->auxEffectId() == effectId) {
3141 attachAuxEffect_l(track, 0);
3142 }
3143 }
3144}
3145
3146bool AudioFlinger::PlaybackThread::threadLoop()
3147{
Glenn Kasten388d5712017-04-07 14:38:41 -07003148 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003149
Eric Laurent81784c32012-11-19 14:55:58 -08003150 Vector< sp<Track> > tracksToRemove;
3151
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003152 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003153 nsecs_t lastWriteFinished = -1; // time last server write completed
3154 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003155
3156 // MIXER
3157 nsecs_t lastWarning = 0;
3158
3159 // DUPLICATING
3160 // FIXME could this be made local to while loop?
3161 writeFrames = 0;
3162
3163 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003164 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003165
3166 if (mType == MIXER) {
3167 sleepTimeShift = 0;
3168 }
3169
3170 CpuStats cpuStats;
3171 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3172
3173 acquireWakeLock();
3174
Glenn Kasteneef598c2017-04-03 14:41:13 -07003175 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3176 // thread associated with this PlaybackThread.
3177 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3178 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003179 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3180 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003181 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003182 const char *logString = NULL;
3183
rago1bb90822017-05-02 18:31:48 -07003184 // Estimated time for next buffer to be written to hal. This is used only on
3185 // suspended mode (for now) to help schedule the wait time until next iteration.
3186 nsecs_t timeLoopNextNs = 0;
3187
Eric Laurent664539d2013-09-23 18:24:31 -07003188 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003189
Andy Hungf3234512018-07-03 14:51:47 -07003190 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3191 // TODO: add confirmation checks:
3192 // 1) DIRECT threads and linear PCM format really resets to 0?
3193 // 2) Is frame count really valid if not linear pcm?
3194 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3195 if (mType == OFFLOAD || mType == DIRECT) {
3196 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3197 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003198 audio_utils::Statistics<double> downstreamLatencyStatMs(0.999 /* alpha */);
3199 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003200
Eric Laurent81784c32012-11-19 14:55:58 -08003201 while (!exitPending())
3202 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003203 // Log merge requests are performed during AudioFlinger binder transactions, but
3204 // that does not cover audio playback. It's requested here for that reason.
3205 mAudioFlinger->requestLogMerge();
3206
Eric Laurent81784c32012-11-19 14:55:58 -08003207 cpuStats.sample(myName);
3208
3209 Vector< sp<EffectChain> > effectChains;
3210
Andy Hung2dbffc22018-08-08 18:50:41 -07003211 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3212 //
3213 // Note: we access outDevice() outside of mLock.
3214 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3215 // Here, we try for the AF lock, but do not block on it as the latency
3216 // is more informational.
3217 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3218 std::vector<PatchPanel::SoftwarePatch> swPatches;
3219 double latencyMs;
3220 status_t status = INVALID_OPERATION;
3221 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3222 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3223 && swPatches.size() > 0) {
3224 status = swPatches[0].getLatencyMs_l(&latencyMs);
3225 downstreamPatchHandle = swPatches[0].getPatchHandle();
3226 }
3227 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
3228 downstreamLatencyStatMs.reset();
3229 lastDownstreamPatchHandle = downstreamPatchHandle;
3230 }
3231 if (status == OK) {
3232 // verify downstream latency (we assume a max reasonable
3233 // latency of 1 second).
3234 if (latencyMs >= 0. && latencyMs <= 1000.) {
3235 ALOGV("new downstream latency %lf ms", latencyMs);
3236 downstreamLatencyStatMs.add(latencyMs);
3237 } else {
3238 ALOGD("out of range downstream latency %lf ms", latencyMs);
3239 }
3240 }
3241 mAudioFlinger->mLock.unlock();
3242 }
3243 } else {
3244 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3245 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
3246 downstreamLatencyStatMs.reset();
3247 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3248 }
3249 }
3250
Eric Laurent81784c32012-11-19 14:55:58 -08003251 { // scope for mLock
3252
3253 Mutex::Autolock _l(mLock);
3254
Eric Laurent021cf962014-05-13 10:18:14 -07003255 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003256
Glenn Kasteneef598c2017-04-03 14:41:13 -07003257 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003258 if (logString != NULL) {
3259 mNBLogWriter->logTimestamp();
3260 mNBLogWriter->log(logString);
3261 logString = NULL;
3262 }
3263
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003264 // Collect timestamp statistics for the Playback Thread types that support it.
3265 if (mType == MIXER
3266 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003267 || mType == DIRECT
3268 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003269 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003270 // and associate with the sink frames written out. We need
3271 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003272 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003273 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003274 if (mStandby) {
3275 mTimestampVerifier.discontinuity();
3276 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3277 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3278 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3279 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003280
3281 if (isTimestampCorrectionEnabled()) {
3282 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3283 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3284 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3285 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3286 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3287 = correctedTimestamp.mFrames;
3288 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3289 = correctedTimestamp.mTimeNs;
3290 ALOGV("TS_AFTER: %d %lld %lld", id(),
3291 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3292 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003293
3294 // Note: Downstream latency only added if timestamp correction enabled.
3295 if (downstreamLatencyStatMs.getN() > 0) { // we have latency info.
3296 const int64_t newPosition =
3297 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3298 - int64_t(downstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3299 // prevent retrograde
3300 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3301 newPosition,
3302 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3303 - mSuspendedFrames));
3304 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003305 }
3306
Andy Hung818e7a32016-02-16 18:08:07 -08003307 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003308 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003309
3310 // We keep track of the last valid kernel position in case we are in underrun
3311 // and the normal mixer period is the same as the fast mixer period, or there
3312 // is some error from the HAL.
3313 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3314 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3315 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3316 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3317 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3318
3319 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3320 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3321 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3322 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003323 }
3324
3325 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3326 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003327 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003328 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003329 }
3330
Andy Hung818e7a32016-02-16 18:08:07 -08003331 // copy over kernel info
3332 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003333 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3334 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003335 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3336 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003337 } else {
3338 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003339 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003340
Andy Hungc54b1ff2016-02-23 14:07:07 -08003341 // mFramesWritten for non-offloaded tracks are contiguous
3342 // even after standby() is called. This is useful for the track frame
3343 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003344 bool serverLocationUpdate = false;
3345 if (mFramesWritten != lastFramesWritten) {
3346 serverLocationUpdate = true;
3347 lastFramesWritten = mFramesWritten;
3348 }
3349 // Only update timestamps if there is a meaningful change.
3350 // Either the kernel timestamp must be valid or we have written something.
3351 if (kernelLocationUpdate || serverLocationUpdate) {
3352 if (serverLocationUpdate) {
3353 // use the time before we called the HAL write - it is a bit more accurate
3354 // to when the server last read data than the current time here.
3355 //
3356 // If we haven't written anything, mLastWriteTime will be -1
3357 // and we use systemTime().
3358 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3359 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3360 ? systemTime() : mLastWriteTime;
3361 }
Andy Hungdae27702016-10-31 14:01:16 -07003362
3363 for (const sp<Track> &t : mActiveTracks) {
3364 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003365 t->updateTrackFrameInfo(
3366 t->mAudioTrackServerProxy->framesReleased(),
3367 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003368 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003369 mTimestamp);
3370 }
Andy Hunge10393e2015-06-12 13:59:33 -07003371 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003372 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003373 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003374#if 0
3375 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003376 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003377 timespec ts;
3378 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003379 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003380 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003381 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003382 }
3383 ++z;
3384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003385 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003386 if (mSignalPending) {
3387 // A signal was raised while we were unlocked
3388 mSignalPending = false;
3389 } else if (waitingAsyncCallback_l()) {
3390 if (exitPending()) {
3391 break;
3392 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003393 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003394 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003395 releaseWakeLock_l();
3396 released = true;
3397 }
Andy Hung10cbff12017-02-21 17:30:14 -08003398
3399 const int64_t waitNs = computeWaitTimeNs_l();
3400 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3401 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3402 if (status == TIMED_OUT) {
3403 mSignalPending = true; // if timeout recheck everything
3404 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003405 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003406 if (released) {
3407 acquireWakeLock_l();
3408 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003409 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3410 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003411
3412 continue;
3413 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003414 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003415 isSuspended()) {
3416 // put audio hardware into standby after short delay
3417 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003418
3419 threadLoop_standby();
3420
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003421 // This is where we go into standby
3422 if (!mStandby) {
3423 LOG_AUDIO_STATE();
3424 }
Eric Laurent81784c32012-11-19 14:55:58 -08003425 mStandby = true;
3426 }
3427
Eric Tan39ec8d62018-07-24 09:49:29 -07003428 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003429 // we're about to wait, flush the binder command buffer
3430 IPCThreadState::self()->flushCommands();
3431
3432 clearOutputTracks();
3433
3434 if (exitPending()) {
3435 break;
3436 }
3437
3438 releaseWakeLock_l();
3439 // wait until we have something to do...
3440 ALOGV("%s going to sleep", myName.string());
3441 mWaitWorkCV.wait(mLock);
3442 ALOGV("%s waking up", myName.string());
3443 acquireWakeLock_l();
3444
3445 mMixerStatus = MIXER_IDLE;
3446 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3447 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003448 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003449 checkSilentMode_l();
3450
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003451 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3452 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003453 if (mType == MIXER) {
3454 sleepTimeShift = 0;
3455 }
3456
3457 continue;
3458 }
3459 }
Eric Laurent81784c32012-11-19 14:55:58 -08003460 // mMixerStatusIgnoringFastTracks is also updated internally
3461 mMixerStatus = prepareTracks_l(&tracksToRemove);
3462
Andy Hungdae27702016-10-31 14:01:16 -07003463 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003464
Kevin Rocard069c2712018-03-29 19:09:14 -07003465 updateMetadata_l();
3466
Eric Laurent81784c32012-11-19 14:55:58 -08003467 // prevent any changes in effect chain list and in each effect chain
3468 // during mixing and effect process as the audio buffers could be deleted
3469 // or modified if an effect is created or deleted
3470 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003471 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003472
Eric Laurentbfb1b832013-01-07 09:53:42 -08003473 if (mBytesRemaining == 0) {
3474 mCurrentWriteLength = 0;
3475 if (mMixerStatus == MIXER_TRACKS_READY) {
3476 // threadLoop_mix() sets mCurrentWriteLength
3477 threadLoop_mix();
3478 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3479 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003480 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003481 // must be written to HAL
3482 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003483 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003484 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003485 }
3486 }
Andy Hung98ef9782014-03-04 14:46:50 -08003487 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003488 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003489 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3490 // or mSinkBuffer (if there are no effects).
3491 //
3492 // This is done pre-effects computation; if effects change to
3493 // support higher precision, this needs to move.
3494 //
3495 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003496 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003497 if (mMixerBufferValid) {
3498 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3499 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3500
Andy Hung2ddee192015-12-18 17:34:44 -08003501 // mono blend occurs for mixer threads only (not direct or offloaded)
3502 // and is handled here if we're going directly to the sink.
3503 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003504 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3505 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003506 }
3507
Andy Hung98ef9782014-03-04 14:46:50 -08003508 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3509 mNormalFrameCount * mChannelCount);
3510 }
3511
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 mBytesRemaining = mCurrentWriteLength;
3513 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003514 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3515 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3516 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3517 mBytesWritten += mBytesRemaining;
3518 mFramesWritten += framesRemaining;
3519 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520 mBytesRemaining = 0;
3521 }
Eric Laurent81784c32012-11-19 14:55:58 -08003522
Eric Laurentbfb1b832013-01-07 09:53:42 -08003523 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003524 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003525 for (size_t i = 0; i < effectChains.size(); i ++) {
3526 effectChains[i]->process_l();
3527 }
Eric Laurent81784c32012-11-19 14:55:58 -08003528 }
3529 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003530 // Process effect chains for offloaded thread even if no audio
3531 // was read from audio track: process only updates effect state
3532 // and thus does have to be synchronized with audio writes but may have
3533 // to be called while waiting for async write callback
3534 if (mType == OFFLOAD) {
3535 for (size_t i = 0; i < effectChains.size(); i ++) {
3536 effectChains[i]->process_l();
3537 }
3538 }
Eric Laurent81784c32012-11-19 14:55:58 -08003539
Andy Hung98ef9782014-03-04 14:46:50 -08003540 // Only if the Effects buffer is enabled and there is data in the
3541 // Effects buffer (buffer valid), we need to
3542 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003543 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003544 if (mEffectBufferValid) {
3545 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003546
3547 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003548 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3549 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003550 }
3551
Andy Hung98ef9782014-03-04 14:46:50 -08003552 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3553 mNormalFrameCount * mChannelCount);
3554 }
3555
Eric Laurent81784c32012-11-19 14:55:58 -08003556 // enable changes in effect chain
3557 unlockEffectChains(effectChains);
3558
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003560 // mSleepTimeUs == 0 means we must write to audio hardware
3561 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003562 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003563 // We save lastWriteFinished here, as previousLastWriteFinished,
3564 // for throttling. On thread start, previousLastWriteFinished will be
3565 // set to -1, which properly results in no throttling after the first write.
3566 nsecs_t previousLastWriteFinished = lastWriteFinished;
3567 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003568 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003569 // FIXME rewrite to reduce number of system calls
3570 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003571 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003572 lastWriteFinished = systemTime();
3573 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 if (ret < 0) {
3575 mBytesRemaining = 0;
3576 } else {
3577 mBytesWritten += ret;
3578 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003579 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580 }
3581 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3582 (mMixerStatus == MIXER_DRAIN_ALL)) {
3583 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003584 }
Andy Hung08fb1742015-05-31 23:22:10 -07003585 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003586 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003587 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003588 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003589 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003590 ATRACE_NAME("underrun");
3591 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003592 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003593 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003594 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 }
Andy Hung08fb1742015-05-31 23:22:10 -07003596
3597 if (mThreadThrottle
3598 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3599 && ret > 0) { // we wrote something
3600 // Limit MixerThread data processing to no more than twice the
3601 // expected processing rate.
3602 //
3603 // This helps prevent underruns with NuPlayer and other applications
3604 // which may set up buffers that are close to the minimum size, or use
3605 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3606 //
3607 // The throttle smooths out sudden large data drains from the device,
3608 // e.g. when it comes out of standby, which often causes problems with
3609 // (1) mixer threads without a fast mixer (which has its own warm-up)
3610 // (2) minimum buffer sized tracks (even if the track is full,
3611 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003612 //
3613 // Total time spent in last processing cycle equals time spent in
3614 // 1. threadLoop_write, as well as time spent in
3615 // 2. threadLoop_mix (significant for heavy mixing, especially
3616 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003617
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003618 // it's OK if deltaMs (and deltaNs) is an overestimate.
3619 nsecs_t deltaNs;
3620 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3621 __builtin_sub_overflow(
3622 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3623 const int32_t deltaMs = deltaNs / 1000000;
3624
Ivan Lozanoea04d392017-11-07 14:37:07 -08003625 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003626 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3627 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003628 // notify of throttle start on verbose log
3629 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3630 "mixer(%p) throttle begin:"
3631 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003632 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003633 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003634 // Throttle must be attributed to the previous mixer loop's write time
3635 // to allow back-to-back throttling.
3636 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003637 } else {
3638 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3639 if (diff > 0) {
3640 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003641 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003642 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3643 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003644 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003645 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3646 }
Andy Hung08fb1742015-05-31 23:22:10 -07003647 }
3648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 }
Eric Laurent81784c32012-11-19 14:55:58 -08003650
Eric Laurentbfb1b832013-01-07 09:53:42 -08003651 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003652 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003653 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003654 // suspended requires accurate metering of sleep time.
3655 if (isSuspended()) {
3656 // advance by expected sleepTime
3657 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3658 const nsecs_t nowNs = systemTime();
3659
3660 // compute expected next time vs current time.
3661 // (negative deltas are treated as delays).
3662 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3663 if (deltaNs < -kMaxNextBufferDelayNs) {
3664 // Delays longer than the max allowed trigger a reset.
3665 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3666 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3667 timeLoopNextNs = nowNs + deltaNs;
3668 } else if (deltaNs < 0) {
3669 // Delays within the max delay allowed: zero the delta/sleepTime
3670 // to help the system catch up in the next iteration(s)
3671 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3672 deltaNs = 0;
3673 }
3674 // update sleep time (which is >= 0)
3675 mSleepTimeUs = deltaNs / 1000;
3676 }
Eric Laurente93cc032016-05-05 10:15:10 -07003677 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3678 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003679 }
Glenn Kastene7754022014-10-31 12:11:26 -07003680 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 }
Eric Laurent81784c32012-11-19 14:55:58 -08003682 }
3683
3684 // Finally let go of removed track(s), without the lock held
3685 // since we can't guarantee the destructors won't acquire that
3686 // same lock. This will also mutate and push a new fast mixer state.
3687 threadLoop_removeTracks(tracksToRemove);
3688 tracksToRemove.clear();
3689
3690 // FIXME I don't understand the need for this here;
3691 // it was in the original code but maybe the
3692 // assignment in saveOutputTracks() makes this unnecessary?
3693 clearOutputTracks();
3694
3695 // Effect chains will be actually deleted here if they were removed from
3696 // mEffectChains list during mixing or effects processing
3697 effectChains.clear();
3698
3699 // FIXME Note that the above .clear() is no longer necessary since effectChains
3700 // is now local to this block, but will keep it for now (at least until merge done).
3701 }
3702
Eric Laurentbfb1b832013-01-07 09:53:42 -08003703 threadLoop_exit();
3704
Eric Laurentcf817a22014-08-04 20:36:31 -07003705 if (!mStandby) {
3706 threadLoop_standby();
3707 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003708 }
3709
3710 releaseWakeLock();
3711
3712 ALOGV("Thread %p type %d exiting", this, mType);
3713 return false;
3714}
3715
Eric Laurentbfb1b832013-01-07 09:53:42 -08003716// removeTracks_l() must be called with ThreadBase::mLock held
3717void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3718{
3719 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003720 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003721 for (size_t i=0 ; i<count ; i++) {
3722 const sp<Track>& track = tracksToRemove.itemAt(i);
3723 mActiveTracks.remove(track);
3724 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3725 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3726 if (chain != 0) {
3727 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3728 track->sessionId());
3729 chain->decActiveTrackCnt();
3730 }
3731 if (track->isTerminated()) {
3732 removeTrack_l(track);
3733 }
3734 }
3735 }
3736
3737}
Eric Laurent81784c32012-11-19 14:55:58 -08003738
Eric Laurentaccc1472013-09-20 09:36:34 -07003739status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3740{
3741 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003742 ExtendedTimestamp ets;
3743 status_t status = mNormalSink->getTimestamp(ets);
3744 if (status == NO_ERROR) {
3745 status = ets.getBestTimestamp(&timestamp);
3746 }
3747 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003748 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003749 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003750 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003751 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003752 timestamp.mPosition = (uint32_t)position64;
3753 return NO_ERROR;
3754 }
3755 }
3756 return INVALID_OPERATION;
3757}
Eric Laurent1c333e22014-05-20 10:48:17 -07003758
Eric Laurent054d9d32015-04-24 08:48:48 -07003759status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3760 audio_patch_handle_t *handle)
3761{
Andy Hungf60abce2016-08-26 11:37:54 -07003762 status_t status;
3763 if (property_get_bool("af.patch_park", false /* default_value */)) {
3764 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3765 // or if HAL does not properly lock against access.
3766 AutoPark<FastMixer> park(mFastMixer);
3767 status = PlaybackThread::createAudioPatch_l(patch, handle);
3768 } else {
3769 status = PlaybackThread::createAudioPatch_l(patch, handle);
3770 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003771 return status;
3772}
3773
Eric Laurent1c333e22014-05-20 10:48:17 -07003774status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3775 audio_patch_handle_t *handle)
3776{
3777 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003778
3779 // store new device and send to effects
3780 audio_devices_t type = AUDIO_DEVICE_NONE;
3781 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3782 type |= patch->sinks[i].ext.device.type;
3783 }
3784
3785#ifdef ADD_BATTERY_DATA
3786 // when changing the audio output device, call addBatteryData to notify
3787 // the change
3788 if (mOutDevice != type) {
3789 uint32_t params = 0;
3790 // check whether speaker is on
3791 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3792 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003793 }
3794
Eric Laurent054d9d32015-04-24 08:48:48 -07003795 audio_devices_t deviceWithoutSpeaker
3796 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3797 // check if any other device (except speaker) is on
3798 if (type & deviceWithoutSpeaker) {
3799 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3800 }
3801
3802 if (params != 0) {
3803 addBatteryData(params);
3804 }
3805 }
3806#endif
3807
3808 for (size_t i = 0; i < mEffectChains.size(); i++) {
3809 mEffectChains[i]->setDevice_l(type);
3810 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003811
3812 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3813 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3814 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003815 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003816 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003817
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003818 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003819 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3820 status = hwDevice->createAudioPatch(patch->num_sources,
3821 patch->sources,
3822 patch->num_sinks,
3823 patch->sinks,
3824 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003825 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003826 char *address;
3827 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3828 //FIXME: we only support address on first sink with HAL version < 3.0
3829 address = audio_device_address_to_parameter(
3830 patch->sinks[0].ext.device.type,
3831 patch->sinks[0].ext.device.address);
3832 } else {
3833 address = (char *)calloc(1, 1);
3834 }
3835 AudioParameter param = AudioParameter(String8(address));
3836 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003837 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003838 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003839 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003840 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003841 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003842 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003843 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3844 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003845 return status;
3846}
3847
Eric Laurent054d9d32015-04-24 08:48:48 -07003848status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3849{
Andy Hungf60abce2016-08-26 11:37:54 -07003850 status_t status;
3851 if (property_get_bool("af.patch_park", false /* default_value */)) {
3852 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3853 // or if HAL does not properly lock against access.
3854 AutoPark<FastMixer> park(mFastMixer);
3855 status = PlaybackThread::releaseAudioPatch_l(handle);
3856 } else {
3857 status = PlaybackThread::releaseAudioPatch_l(handle);
3858 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003859 return status;
3860}
3861
Eric Laurent1c333e22014-05-20 10:48:17 -07003862status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3863{
3864 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003865
3866 mOutDevice = AUDIO_DEVICE_NONE;
3867
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003868 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003869 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3870 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003871 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003872 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003873 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003874 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003875 }
3876 return status;
3877}
3878
Eric Laurent83b88082014-06-20 18:31:16 -07003879void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3880{
3881 Mutex::Autolock _l(mLock);
3882 mTracks.add(track);
3883}
3884
3885void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3886{
3887 Mutex::Autolock _l(mLock);
3888 destroyTrack_l(track);
3889}
3890
Mikhail Naganovdc769682018-05-04 15:34:08 -07003891void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003892{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003893 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003894 config->role = AUDIO_PORT_ROLE_SOURCE;
3895 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3896 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003897 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3898 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3899 config->flags.output = mOutput->flags;
3900 }
Eric Laurent83b88082014-06-20 18:31:16 -07003901}
3902
Eric Laurent81784c32012-11-19 14:55:58 -08003903// ----------------------------------------------------------------------------
3904
3905AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003906 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3907 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003908 // mAudioMixer below
3909 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003910 mFastMixerFutex(0),
3911 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003912 // mOutputSink below
3913 // mPipeSink below
3914 // mNormalSink below
3915{
3916 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003917 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003918 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003919 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3920 mNormalFrameCount);
3921 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3922
Andy Hungfbfc3952015-01-15 13:33:51 -08003923 if (type == DUPLICATING) {
3924 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3925 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3926 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3927 return;
3928 }
Eric Laurent81784c32012-11-19 14:55:58 -08003929 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003930 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003931 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003932 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003933#if !LOG_NDEBUG
3934 ssize_t index =
3935#else
3936 (void)
3937#endif
3938 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003939 ALOG_ASSERT(index == 0);
3940
3941 // initialize fast mixer depending on configuration
3942 bool initFastMixer;
3943 switch (kUseFastMixer) {
3944 case FastMixer_Never:
3945 initFastMixer = false;
3946 break;
3947 case FastMixer_Always:
3948 initFastMixer = true;
3949 break;
3950 case FastMixer_Static:
3951 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003952 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3953 // where the period is less than an experimentally determined threshold that can be
3954 // scheduled reliably with CFS. However, the BT A2DP HAL is
3955 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3956 initFastMixer = mFrameCount < mNormalFrameCount
3957 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003958 break;
3959 }
Andy Hungfda69402017-02-15 14:33:12 -08003960 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3961 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3962 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003963 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003964 audio_format_t fastMixerFormat;
3965 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3966 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3967 } else {
3968 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3969 }
3970 if (mFormat != fastMixerFormat) {
3971 // change our Sink format to accept our intermediate precision
3972 mFormat = fastMixerFormat;
3973 free(mSinkBuffer);
3974 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3975 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3976 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3977 }
Eric Laurent81784c32012-11-19 14:55:58 -08003978
3979 // create a MonoPipe to connect our submix to FastMixer
3980 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003981
Andy Hung1258c1a2014-05-23 21:22:17 -07003982 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003983 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003984 format.mFormat = fastMixerFormat;
3985 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3986
Eric Laurent81784c32012-11-19 14:55:58 -08003987 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3988 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3989 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3990 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3991 const NBAIO_Format offers[1] = {format};
3992 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003993#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003994 ssize_t index =
3995#else
3996 (void)
3997#endif
3998 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003999 ALOG_ASSERT(index == 0);
4000 monoPipe->setAvgFrames((mScreenState & 1) ?
4001 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4002 mPipeSink = monoPipe;
4003
Eric Laurent81784c32012-11-19 14:55:58 -08004004 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004005 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004006 FastMixerStateQueue *sq = mFastMixer->sq();
4007#ifdef STATE_QUEUE_DUMP
4008 sq->setObserverDump(&mStateQueueObserverDump);
4009 sq->setMutatorDump(&mStateQueueMutatorDump);
4010#endif
4011 FastMixerState *state = sq->begin();
4012 FastTrack *fastTrack = &state->mFastTracks[0];
4013 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4014 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4015 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004016 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
4017 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08004018 fastTrack->mGeneration++;
4019 state->mFastTracksGen++;
4020 state->mTrackMask = 1;
4021 // fast mixer will use the HAL output sink
4022 state->mOutputSink = mOutputSink.get();
4023 state->mOutputSinkGen++;
4024 state->mFrameCount = mFrameCount;
4025 state->mCommand = FastMixerState::COLD_IDLE;
4026 // already done in constructor initialization list
4027 //mFastMixerFutex = 0;
4028 state->mColdFutexAddr = &mFastMixerFutex;
4029 state->mColdGen++;
4030 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004031 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4032 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004033 sq->end();
4034 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4035
Eric Tan0513b5d2018-09-17 10:32:48 -07004036 NBLog::thread_info_t info;
4037 info.id = mId;
4038 info.type = NBLog::FASTMIXER;
4039 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4040
Eric Laurent81784c32012-11-19 14:55:58 -08004041 // start the fast mixer
4042 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4043 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004044 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004045 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004046
4047#ifdef AUDIO_WATCHDOG
4048 // create and start the watchdog
4049 mAudioWatchdog = new AudioWatchdog();
4050 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4051 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4052 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004053 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004054#endif
Andy Hung8946a282018-04-19 20:04:56 -07004055 } else {
4056#ifdef TEE_SINK
4057 // Only use the MixerThread tee if there is no FastMixer.
4058 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4059 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4060#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004061 }
4062
4063 switch (kUseFastMixer) {
4064 case FastMixer_Never:
4065 case FastMixer_Dynamic:
4066 mNormalSink = mOutputSink;
4067 break;
4068 case FastMixer_Always:
4069 mNormalSink = mPipeSink;
4070 break;
4071 case FastMixer_Static:
4072 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4073 break;
4074 }
4075}
4076
4077AudioFlinger::MixerThread::~MixerThread()
4078{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004079 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004080 FastMixerStateQueue *sq = mFastMixer->sq();
4081 FastMixerState *state = sq->begin();
4082 if (state->mCommand == FastMixerState::COLD_IDLE) {
4083 int32_t old = android_atomic_inc(&mFastMixerFutex);
4084 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004085 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004086 }
4087 }
4088 state->mCommand = FastMixerState::EXIT;
4089 sq->end();
4090 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4091 mFastMixer->join();
4092 // Though the fast mixer thread has exited, it's state queue is still valid.
4093 // We'll use that extract the final state which contains one remaining fast track
4094 // corresponding to our sub-mix.
4095 state = sq->begin();
4096 ALOG_ASSERT(state->mTrackMask == 1);
4097 FastTrack *fastTrack = &state->mFastTracks[0];
4098 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4099 delete fastTrack->mBufferProvider;
4100 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004101 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004102#ifdef AUDIO_WATCHDOG
4103 if (mAudioWatchdog != 0) {
4104 mAudioWatchdog->requestExit();
4105 mAudioWatchdog->requestExitAndWait();
4106 mAudioWatchdog.clear();
4107 }
4108#endif
4109 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004110 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004111 delete mAudioMixer;
4112}
4113
4114
4115uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4116{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004117 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004118 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4119 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4120 }
4121 return latency;
4122}
4123
4124
4125void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4126{
4127 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4128}
4129
Eric Laurentbfb1b832013-01-07 09:53:42 -08004130ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004131{
4132 // FIXME we should only do one push per cycle; confirm this is true
4133 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004134 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004135 FastMixerStateQueue *sq = mFastMixer->sq();
4136 FastMixerState *state = sq->begin();
4137 if (state->mCommand != FastMixerState::MIX_WRITE &&
4138 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4139 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004140
4141 // FIXME workaround for first HAL write being CPU bound on some devices
4142 ATRACE_BEGIN("write");
4143 mOutput->write((char *)mSinkBuffer, 0);
4144 ATRACE_END();
4145
Eric Laurent81784c32012-11-19 14:55:58 -08004146 int32_t old = android_atomic_inc(&mFastMixerFutex);
4147 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004148 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004149 }
4150#ifdef AUDIO_WATCHDOG
4151 if (mAudioWatchdog != 0) {
4152 mAudioWatchdog->resume();
4153 }
4154#endif
4155 }
4156 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004157#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004158 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004159 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004160#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004161 sq->end();
4162 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4163 if (kUseFastMixer == FastMixer_Dynamic) {
4164 mNormalSink = mPipeSink;
4165 }
4166 } else {
4167 sq->end(false /*didModify*/);
4168 }
4169 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004171}
4172
4173void AudioFlinger::MixerThread::threadLoop_standby()
4174{
4175 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004176 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004177 FastMixerStateQueue *sq = mFastMixer->sq();
4178 FastMixerState *state = sq->begin();
4179 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004180 // Report any frames trapped in the Monopipe
4181 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4182 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4183 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4184 "monoPipeWritten:%lld monoPipeLeft:%lld",
4185 (long long)mFramesWritten, (long long)mSuspendedFrames,
4186 (long long)mPipeSink->framesWritten(), pipeFrames);
4187 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4188
Eric Laurent81784c32012-11-19 14:55:58 -08004189 state->mCommand = FastMixerState::COLD_IDLE;
4190 state->mColdFutexAddr = &mFastMixerFutex;
4191 state->mColdGen++;
4192 mFastMixerFutex = 0;
4193 sq->end();
4194 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4195 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4196 if (kUseFastMixer == FastMixer_Dynamic) {
4197 mNormalSink = mOutputSink;
4198 }
4199#ifdef AUDIO_WATCHDOG
4200 if (mAudioWatchdog != 0) {
4201 mAudioWatchdog->pause();
4202 }
4203#endif
4204 } else {
4205 sq->end(false /*didModify*/);
4206 }
4207 }
4208 PlaybackThread::threadLoop_standby();
4209}
4210
Eric Laurentbfb1b832013-01-07 09:53:42 -08004211bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4212{
4213 return false;
4214}
4215
4216bool AudioFlinger::PlaybackThread::shouldStandby_l()
4217{
4218 return !mStandby;
4219}
4220
4221bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4222{
4223 Mutex::Autolock _l(mLock);
4224 return waitingAsyncCallback_l();
4225}
4226
Eric Laurent81784c32012-11-19 14:55:58 -08004227// shared by MIXER and DIRECT, overridden by DUPLICATING
4228void AudioFlinger::PlaybackThread::threadLoop_standby()
4229{
4230 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004231 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004232 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004233 // discard any pending drain or write ack by incrementing sequence
4234 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4235 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004236 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004237 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4238 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004239 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004240 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004241}
4242
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004243void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4244{
4245 ALOGV("signal playback thread");
4246 broadcast_l();
4247}
4248
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004249void AudioFlinger::PlaybackThread::onAsyncError()
4250{
4251 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4252 invalidateTracks((audio_stream_type_t)i);
4253 }
4254}
4255
Eric Laurent81784c32012-11-19 14:55:58 -08004256void AudioFlinger::MixerThread::threadLoop_mix()
4257{
Eric Laurent81784c32012-11-19 14:55:58 -08004258 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004259 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004260 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004261 // increase sleep time progressively when application underrun condition clears.
4262 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4263 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4264 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004265 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004266 sleepTimeShift--;
4267 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004268 mSleepTimeUs = 0;
4269 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004270 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004271
Eric Laurent81784c32012-11-19 14:55:58 -08004272}
4273
4274void AudioFlinger::MixerThread::threadLoop_sleepTime()
4275{
4276 // If no tracks are ready, sleep once for the duration of an output
4277 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004278 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004279 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004280 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4281 // Using the Monopipe availableToWrite, we estimate the
4282 // sleep time to retry for more data (before we underrun).
4283 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4284 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4285 const size_t pipeFrames = monoPipe->maxFrames();
4286 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4287 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4288 const size_t framesDelay = std::min(
4289 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4290 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4291 pipeFrames, framesLeft, framesDelay);
4292 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4293 } else {
4294 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4295 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4296 mSleepTimeUs = kMinThreadSleepTimeUs;
4297 }
4298 // reduce sleep time in case of consecutive application underruns to avoid
4299 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4300 // duration we would end up writing less data than needed by the audio HAL if
4301 // the condition persists.
4302 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4303 sleepTimeShift++;
4304 }
Eric Laurent81784c32012-11-19 14:55:58 -08004305 }
4306 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004307 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004308 }
4309 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004310 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4311 // before effects processing or output.
4312 if (mMixerBufferValid) {
4313 memset(mMixerBuffer, 0, mMixerBufferSize);
4314 } else {
4315 memset(mSinkBuffer, 0, mSinkBufferSize);
4316 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004317 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004318 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4319 "anticipated start");
4320 }
4321 // TODO add standby time extension fct of effect tail
4322}
4323
4324// prepareTracks_l() must be called with ThreadBase::mLock held
4325AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4326 Vector< sp<Track> > *tracksToRemove)
4327{
Andy Hungc0691382018-09-12 18:01:57 -07004328 // clean up deleted track ids in AudioMixer before allocating new tracks
4329 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4330 // for each trackId, destroy it in the AudioMixer
4331 if (mAudioMixer->exists(trackId)) {
4332 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004333 }
4334 });
Andy Hungc0691382018-09-12 18:01:57 -07004335 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004336
4337 mixer_state mixerStatus = MIXER_IDLE;
4338 // find out which tracks need to be processed
4339 size_t count = mActiveTracks.size();
4340 size_t mixedTracks = 0;
4341 size_t tracksWithEffect = 0;
4342 // counts only _active_ fast tracks
4343 size_t fastTracks = 0;
4344 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4345
4346 float masterVolume = mMasterVolume;
4347 bool masterMute = mMasterMute;
4348
4349 if (masterMute) {
4350 masterVolume = 0;
4351 }
4352 // Delegate master volume control to effect in output mix effect chain if needed
4353 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4354 if (chain != 0) {
4355 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4356 chain->setVolume_l(&v, &v);
4357 masterVolume = (float)((v + (1 << 23)) >> 24);
4358 chain.clear();
4359 }
4360
4361 // prepare a new state to push
4362 FastMixerStateQueue *sq = NULL;
4363 FastMixerState *state = NULL;
4364 bool didModify = false;
4365 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004366 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004367 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004368 sq = mFastMixer->sq();
4369 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004370 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004371 }
4372
Andy Hung69aed5f2014-02-25 17:24:40 -08004373 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004374 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004375
Andy Hungbd3b2b02018-05-21 10:53:11 -07004376 // DeferredOperations handles statistics after setting mixerStatus.
4377 class DeferredOperations {
4378 public:
4379 DeferredOperations(mixer_state *mixerStatus)
4380 : mMixerStatus(mixerStatus) { }
4381
4382 // when leaving scope, tally frames properly.
4383 ~DeferredOperations() {
4384 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4385 // because that is when the underrun occurs.
4386 // We do not distinguish between FastTracks and NormalTracks here.
4387 if (*mMixerStatus == MIXER_TRACKS_READY) {
4388 for (const auto &underrun : mUnderrunFrames) {
4389 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4390 underrun.second);
4391 }
4392 }
4393 }
4394
4395 // tallyUnderrunFrames() is called to update the track counters
4396 // with the number of underrun frames for a particular mixer period.
4397 // We defer tallying until we know the final mixer status.
4398 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4399 mUnderrunFrames.emplace_back(track, underrunFrames);
4400 }
4401
4402 private:
4403 const mixer_state * const mMixerStatus;
4404 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4405 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4406
Eric Laurent81784c32012-11-19 14:55:58 -08004407 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004408 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004409
4410 // this const just means the local variable doesn't change
4411 Track* const track = t.get();
4412
4413 // process fast tracks
4414 if (track->isFastTrack()) {
4415
4416 // It's theoretically possible (though unlikely) for a fast track to be created
4417 // and then removed within the same normal mix cycle. This is not a problem, as
4418 // the track never becomes active so it's fast mixer slot is never touched.
4419 // The converse, of removing an (active) track and then creating a new track
4420 // at the identical fast mixer slot within the same normal mix cycle,
4421 // is impossible because the slot isn't marked available until the end of each cycle.
4422 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004423 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004424 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4425 FastTrack *fastTrack = &state->mFastTracks[j];
4426
4427 // Determine whether the track is currently in underrun condition,
4428 // and whether it had a recent underrun.
4429 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4430 FastTrackUnderruns underruns = ftDump->mUnderruns;
4431 uint32_t recentFull = (underruns.mBitFields.mFull -
4432 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4433 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4434 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4435 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4436 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4437 uint32_t recentUnderruns = recentPartial + recentEmpty;
4438 track->mObservedUnderruns = underruns;
4439 // don't count underruns that occur while stopping or pausing
4440 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004441 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004442 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4443 recentUnderruns > 0) {
4444 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004445 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004446 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004447 // Immediately account for FastTrack underruns.
4448 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004449
4450 // This is similar to the state machine for normal tracks,
4451 // with a few modifications for fast tracks.
4452 bool isActive = true;
4453 switch (track->mState) {
4454 case TrackBase::STOPPING_1:
4455 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004456 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004457 track->mState = TrackBase::STOPPING_2;
4458 }
4459 break;
4460 case TrackBase::PAUSING:
4461 // ramp down is not yet implemented
4462 track->setPaused();
4463 break;
4464 case TrackBase::RESUMING:
4465 // ramp up is not yet implemented
4466 track->mState = TrackBase::ACTIVE;
4467 break;
4468 case TrackBase::ACTIVE:
4469 if (recentFull > 0 || recentPartial > 0) {
4470 // track has provided at least some frames recently: reset retry count
4471 track->mRetryCount = kMaxTrackRetries;
4472 }
4473 if (recentUnderruns == 0) {
4474 // no recent underruns: stay active
4475 break;
4476 }
4477 // there has recently been an underrun of some kind
4478 if (track->sharedBuffer() == 0) {
4479 // were any of the recent underruns "empty" (no frames available)?
4480 if (recentEmpty == 0) {
4481 // no, then ignore the partial underruns as they are allowed indefinitely
4482 break;
4483 }
4484 // there has recently been an "empty" underrun: decrement the retry counter
4485 if (--(track->mRetryCount) > 0) {
4486 break;
4487 }
4488 // indicate to client process that the track was disabled because of underrun;
4489 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004490 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004491 // remove from active list, but state remains ACTIVE [confusing but true]
4492 isActive = false;
4493 break;
4494 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004495 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004496 case TrackBase::STOPPING_2:
4497 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004498 case TrackBase::STOPPED:
4499 case TrackBase::FLUSHED: // flush() while active
4500 // Check for presentation complete if track is inactive
4501 // We have consumed all the buffers of this track.
4502 // This would be incomplete if we auto-paused on underrun
4503 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004504 uint32_t latency = 0;
4505 status_t result = mOutput->stream->getLatency(&latency);
4506 ALOGE_IF(result != OK,
4507 "Error when retrieving output stream latency: %d", result);
4508 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004509 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004510 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4511 // track stays in active list until presentation is complete
4512 break;
4513 }
4514 }
4515 if (track->isStopping_2()) {
4516 track->mState = TrackBase::STOPPED;
4517 }
4518 if (track->isStopped()) {
4519 // Can't reset directly, as fast mixer is still polling this track
4520 // track->reset();
4521 // So instead mark this track as needing to be reset after push with ack
4522 resetMask |= 1 << i;
4523 }
4524 isActive = false;
4525 break;
4526 case TrackBase::IDLE:
4527 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004528 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004529 }
4530
4531 if (isActive) {
4532 // was it previously inactive?
4533 if (!(state->mTrackMask & (1 << j))) {
4534 ExtendedAudioBufferProvider *eabp = track;
4535 VolumeProvider *vp = track;
4536 fastTrack->mBufferProvider = eabp;
4537 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004538 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004539 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004540 fastTrack->mGeneration++;
4541 state->mTrackMask |= 1 << j;
4542 didModify = true;
4543 // no acknowledgement required for newly active tracks
4544 }
Kevin Rocard12381092018-04-11 09:19:59 -07004545 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004546 // cache the combined master volume and stream type volume for fast mixer; this
4547 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004548 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004549 proxy->framesReleased()).first;
4550 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004551 * mStreamTypes[track->streamType()].volume
4552 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004553 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004554 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4555 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4556 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4557 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004558 ++fastTracks;
4559 } else {
4560 // was it previously active?
4561 if (state->mTrackMask & (1 << j)) {
4562 fastTrack->mBufferProvider = NULL;
4563 fastTrack->mGeneration++;
4564 state->mTrackMask &= ~(1 << j);
4565 didModify = true;
4566 // If any fast tracks were removed, we must wait for acknowledgement
4567 // because we're about to decrement the last sp<> on those tracks.
4568 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4569 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004570 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4571 // AudioTrack may start (which may not be with a start() but with a write()
4572 // after underrun) and immediately paused or released. In that case the
4573 // FastTrack state hasn't had time to update.
4574 // TODO Remove the ALOGW when this theory is confirmed.
4575 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004576 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4577 j, track->mState, state->mTrackMask, recentUnderruns,
4578 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004579 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004580 }
4581 tracksToRemove->add(track);
4582 // Avoids a misleading display in dumpsys
4583 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4584 }
4585 continue;
4586 }
4587
4588 { // local variable scope to avoid goto warning
4589
4590 audio_track_cblk_t* cblk = track->cblk();
4591
4592 // The first time a track is added we wait
4593 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004594 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004595
4596 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004597 // use the trackId as the AudioMixer name.
4598 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004599 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004600 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004601 track->mChannelMask,
4602 track->mFormat,
4603 track->mSessionId);
4604 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004605 ALOGW("%s(): AudioMixer cannot create track(%d)"
4606 " mask %#x, format %#x, sessionId %d",
4607 __func__, trackId,
4608 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004609 tracksToRemove->add(track);
4610 track->invalidate(); // consider it dead.
4611 continue;
4612 }
4613 }
4614
Eric Laurent81784c32012-11-19 14:55:58 -08004615 // make sure that we have enough frames to mix one full buffer.
4616 // enforce this condition only once to enable draining the buffer in case the client
4617 // app does not call stop() and relies on underrun to stop:
4618 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4619 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004620 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004621 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004622 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004623
4624 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004625 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004626 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4627 // add frames already consumed but not yet released by the resampler
4628 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004629 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004630
Eric Laurent81784c32012-11-19 14:55:58 -08004631 uint32_t minFrames = 1;
4632 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4633 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004634 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004635 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004636
4637 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004638 if (ATRACE_ENABLED()) {
4639 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004640 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004641 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004642 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004643 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004644 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004645 !track->isPaused() && !track->isTerminated())
4646 {
Andy Hungc0691382018-09-12 18:01:57 -07004647 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004648
4649 mixedTracks++;
4650
Andy Hung69aed5f2014-02-25 17:24:40 -08004651 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4652 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004653 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004654 if (track->mainBuffer() != mSinkBuffer &&
4655 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004656 if (mEffectBufferEnabled) {
4657 mEffectBufferValid = true; // Later can set directly.
4658 }
Eric Laurent81784c32012-11-19 14:55:58 -08004659 chain = getEffectChain_l(track->sessionId());
4660 // Delegate volume control to effect in track effect chain if needed
4661 if (chain != 0) {
4662 tracksWithEffect++;
4663 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004664 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004665 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004666 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
4668 }
4669
4670
4671 int param = AudioMixer::VOLUME;
4672 if (track->mFillingUpStatus == Track::FS_FILLED) {
4673 // no ramp for the first volume setting
4674 track->mFillingUpStatus = Track::FS_ACTIVE;
4675 if (track->mState == TrackBase::RESUMING) {
4676 track->mState = TrackBase::ACTIVE;
4677 param = AudioMixer::RAMP_VOLUME;
4678 }
Andy Hungc0691382018-09-12 18:01:57 -07004679 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004680 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004681 // FIXME should not make a decision based on mServer
4682 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004683 // If the track is stopped before the first frame was mixed,
4684 // do not apply ramp
4685 param = AudioMixer::RAMP_VOLUME;
4686 }
4687
4688 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004689 uint32_t vl, vr; // in U8.24 integer format
4690 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004691 // read original volumes with volume control
4692 float typeVolume = mStreamTypes[track->streamType()].volume;
4693 float v = masterVolume * typeVolume;
4694
Glenn Kastene4756fe2012-11-29 13:38:14 -08004695 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004696 vl = vr = 0;
4697 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004698 if (track->isPausing()) {
4699 track->setPaused();
4700 }
4701 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004702 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004703 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004704 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4705 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004706 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004707 if (vlf > GAIN_FLOAT_UNITY) {
4708 ALOGV("Track left volume out of range: %.3g", vlf);
4709 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004710 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004711 if (vrf > GAIN_FLOAT_UNITY) {
4712 ALOGV("Track right volume out of range: %.3g", vrf);
4713 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004714 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004715 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004716 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004717 // now apply the master volume and stream type volume and shaper volume
4718 vlf *= v * vh;
4719 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004720 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004721 // then derive vl and vr as U8.24 versions for the effect chain
4722 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4723 vl = (uint32_t) (scaleto8_24 * vlf);
4724 vr = (uint32_t) (scaleto8_24 * vrf);
4725 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004726 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004727 // send level comes from shared memory and so may be corrupt
4728 if (sendLevel > MAX_GAIN_INT) {
4729 ALOGV("Track send level out of range: %04X", sendLevel);
4730 sendLevel = MAX_GAIN_INT;
4731 }
Andy Hung6be49402014-05-30 10:42:03 -07004732 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4733 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004735
Kevin Rocard12381092018-04-11 09:19:59 -07004736 track->setFinalVolume((vrf + vlf) / 2.f);
4737
Eric Laurent81784c32012-11-19 14:55:58 -08004738 // Delegate volume control to effect in track effect chain if needed
4739 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4740 // Do not ramp volume if volume is controlled by effect
4741 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004742 // Update remaining floating point volume levels
4743 vlf = (float)vl / (1 << 24);
4744 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004745 track->mHasVolumeController = true;
4746 } else {
4747 // force no volume ramp when volume controller was just disabled or removed
4748 // from effect chain to avoid volume spike
4749 if (track->mHasVolumeController) {
4750 param = AudioMixer::VOLUME;
4751 }
4752 track->mHasVolumeController = false;
4753 }
4754
Eric Laurent7c29ec92017-09-20 17:54:22 -07004755 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4756 // still applied by the mixer.
4757 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4758 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4759 if (v != mLeftVolFloat) {
4760 status_t result = mOutput->stream->setVolume(v, v);
4761 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4762 if (result == OK) {
4763 mLeftVolFloat = v;
4764 }
4765 }
4766 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4767 // remove stream volume contribution from software volume.
4768 if (v != 0.0f && mLeftVolFloat == v) {
4769 vlf = min(1.0f, vlf / v);
4770 vrf = min(1.0f, vrf / v);
4771 vaf = min(1.0f, vaf / v);
4772 }
4773 }
Eric Laurent81784c32012-11-19 14:55:58 -08004774 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004775 mAudioMixer->setBufferProvider(trackId, track);
4776 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004777
Andy Hungc0691382018-09-12 18:01:57 -07004778 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4779 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4780 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004781 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004782 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004783 AudioMixer::TRACK,
4784 AudioMixer::FORMAT, (void *)track->format());
4785 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004786 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004787 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004788 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004789 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004790 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004791 AudioMixer::TRACK,
4792 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004793 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004794 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004795 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004796 if (reqSampleRate == 0) {
4797 reqSampleRate = mSampleRate;
4798 } else if (reqSampleRate > maxSampleRate) {
4799 reqSampleRate = maxSampleRate;
4800 }
Eric Laurent81784c32012-11-19 14:55:58 -08004801 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004802 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004803 AudioMixer::RESAMPLE,
4804 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004805 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004806
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004807 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004808 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004809 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07004810 AudioMixer::TIMESTRETCH,
4811 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004812 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004813
Andy Hung69aed5f2014-02-25 17:24:40 -08004814 /*
4815 * Select the appropriate output buffer for the track.
4816 *
Andy Hung98ef9782014-03-04 14:46:50 -08004817 * Tracks with effects go into their own effects chain buffer
4818 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004819 *
4820 * Other tracks can use mMixerBuffer for higher precision
4821 * channel accumulation. If this buffer is enabled
4822 * (mMixerBufferEnabled true), then selected tracks will accumulate
4823 * into it.
4824 *
4825 */
4826 if (mMixerBufferEnabled
4827 && (track->mainBuffer() == mSinkBuffer
4828 || track->mainBuffer() == mMixerBuffer)) {
4829 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004830 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004831 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004832 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004833 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004834 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004835 AudioMixer::TRACK,
4836 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4837 // TODO: override track->mainBuffer()?
4838 mMixerBufferValid = true;
4839 } else {
4840 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004841 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004842 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004843 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004844 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004845 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004846 AudioMixer::TRACK,
4847 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4848 }
Eric Laurent81784c32012-11-19 14:55:58 -08004849 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004850 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004851 AudioMixer::TRACK,
4852 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4853
4854 // reset retry count
4855 track->mRetryCount = kMaxTrackRetries;
4856
4857 // If one track is ready, set the mixer ready if:
4858 // - the mixer was not ready during previous round OR
4859 // - no other track is not ready
4860 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4861 mixerStatus != MIXER_TRACKS_ENABLED) {
4862 mixerStatus = MIXER_TRACKS_READY;
4863 }
4864 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004865 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004866 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07004867 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
4868 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004869 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004870 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004871 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004872
Eric Laurent81784c32012-11-19 14:55:58 -08004873 // clear effect chain input buffer if an active track underruns to avoid sending
4874 // previous audio buffer again to effects
4875 chain = getEffectChain_l(track->sessionId());
4876 if (chain != 0) {
4877 chain->clearInputBuffer();
4878 }
4879
Andy Hungc0691382018-09-12 18:01:57 -07004880 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004881 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4882 track->isStopped() || track->isPaused()) {
4883 // We have consumed all the buffers of this track.
4884 // Remove it from the list of active tracks.
4885 // TODO: use actual buffer filling status instead of latency when available from
4886 // audio HAL
4887 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004888 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004889 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4890 if (track->isStopped()) {
4891 track->reset();
4892 }
4893 tracksToRemove->add(track);
4894 }
4895 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // No buffers for this track. Give it a few chances to
4897 // fill a buffer, then remove it from active list.
4898 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07004899 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
4900 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004901 tracksToRemove->add(track);
4902 // indicate to client process that the track was disabled because of underrun;
4903 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004904 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004905 // If one track is not ready, mark the mixer also not ready if:
4906 // - the mixer was ready during previous round OR
4907 // - no other track is ready
4908 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4909 mixerStatus != MIXER_TRACKS_READY) {
4910 mixerStatus = MIXER_TRACKS_ENABLED;
4911 }
4912 }
Andy Hungc0691382018-09-12 18:01:57 -07004913 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004914 }
4915
4916 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004917
4918 }
4919
4920 // Push the new FastMixer state if necessary
4921 bool pauseAudioWatchdog = false;
4922 if (didModify) {
4923 state->mFastTracksGen++;
4924 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4925 if (kUseFastMixer == FastMixer_Dynamic &&
4926 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4927 state->mCommand = FastMixerState::COLD_IDLE;
4928 state->mColdFutexAddr = &mFastMixerFutex;
4929 state->mColdGen++;
4930 mFastMixerFutex = 0;
4931 if (kUseFastMixer == FastMixer_Dynamic) {
4932 mNormalSink = mOutputSink;
4933 }
4934 // If we go into cold idle, need to wait for acknowledgement
4935 // so that fast mixer stops doing I/O.
4936 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4937 pauseAudioWatchdog = true;
4938 }
Eric Laurent81784c32012-11-19 14:55:58 -08004939 }
4940 if (sq != NULL) {
4941 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004942 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4943 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4944 // when bringing the output sink into standby.)
4945 //
4946 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4947 //
4948 // This occurs with BT suspend when we idle the FastMixer with
4949 // active tracks, which may be added or removed.
4950 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004951 }
4952#ifdef AUDIO_WATCHDOG
4953 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4954 mAudioWatchdog->pause();
4955 }
4956#endif
4957
4958 // Now perform the deferred reset on fast tracks that have stopped
4959 while (resetMask != 0) {
4960 size_t i = __builtin_ctz(resetMask);
4961 ALOG_ASSERT(i < count);
4962 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004963 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004964 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4965 track->reset();
4966 }
4967
Andy Hung80d03d22018-04-10 10:32:11 -07004968 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4969 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4970 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4971 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4972 // See also the implementation of destroyTrack_l().
4973 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07004974 const int trackId = track->id();
4975 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
4976 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07004977 }
4978 }
4979
Eric Laurent81784c32012-11-19 14:55:58 -08004980 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004981 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004982
Eric Laurent97d547d2014-09-02 14:45:53 -07004983 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4984 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004985 }
4986
4987 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004988 // as long as there are effects we should clear the effects buffer, to avoid
4989 // passing a non-clean buffer to the effect chain
4990 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004991 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004992 // sink or mix buffer must be cleared if all tracks are connected to an
4993 // effect chain as in this case the mixer will not write to the sink or mix buffer
4994 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004995 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4996 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004997 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004998 if (mMixerBufferValid) {
4999 memset(mMixerBuffer, 0, mMixerBufferSize);
5000 // TODO: In testing, mSinkBuffer below need not be cleared because
5001 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5002 // after mixing.
5003 //
5004 // To enforce this guarantee:
5005 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5006 // (mixedTracks == 0 && fastTracks > 0))
5007 // must imply MIXER_TRACKS_READY.
5008 // Later, we may clear buffers regardless, and skip much of this logic.
5009 }
Andy Hung98ef9782014-03-04 14:46:50 -08005010 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005011 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005012 }
5013
5014 // if any fast tracks, then status is ready
5015 mMixerStatusIgnoringFastTracks = mixerStatus;
5016 if (fastTracks > 0) {
5017 mixerStatus = MIXER_TRACKS_READY;
5018 }
5019 return mixerStatus;
5020}
5021
Eric Laurentad7dd962016-09-22 12:38:37 -07005022// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005023uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005024{
5025 uint32_t trackCount = 0;
5026 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005027 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005028 trackCount++;
5029 }
5030 }
5031 return trackCount;
5032}
5033
Andy Hung1bc088a2018-02-09 15:57:31 -08005034// isTrackAllowed_l() must be called with ThreadBase::mLock held
5035bool AudioFlinger::MixerThread::isTrackAllowed_l(
5036 audio_channel_mask_t channelMask, audio_format_t format,
5037 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005038{
Andy Hung1bc088a2018-02-09 15:57:31 -08005039 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5040 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005041 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005042 // Check validity as we don't call AudioMixer::create() here.
5043 if (!AudioMixer::isValidFormat(format)) {
5044 ALOGW("%s: invalid format: %#x", __func__, format);
5045 return false;
5046 }
5047 if (!AudioMixer::isValidChannelMask(channelMask)) {
5048 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5049 return false;
5050 }
5051 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005052}
5053
Eric Laurent10351942014-05-08 18:49:52 -07005054// checkForNewParameter_l() must be called with ThreadBase::mLock held
5055bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5056 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005057{
Eric Laurent81784c32012-11-19 14:55:58 -08005058 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005059 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005060
Eric Laurent10351942014-05-08 18:49:52 -07005061 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005062
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005063 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005064
Eric Laurent10351942014-05-08 18:49:52 -07005065 AudioParameter param = AudioParameter(keyValuePair);
5066 int value;
5067 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5068 reconfig = true;
5069 }
5070 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005071 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005072 status = BAD_VALUE;
5073 } else {
5074 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005075 reconfig = true;
5076 }
Eric Laurent10351942014-05-08 18:49:52 -07005077 }
5078 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005079 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005080 status = BAD_VALUE;
5081 } else {
5082 // no need to save value, since it's constant
5083 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005084 }
Eric Laurent10351942014-05-08 18:49:52 -07005085 }
5086 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5087 // do not accept frame count changes if tracks are open as the track buffer
5088 // size depends on frame count and correct behavior would not be guaranteed
5089 // if frame count is changed after track creation
5090 if (!mTracks.isEmpty()) {
5091 status = INVALID_OPERATION;
5092 } else {
5093 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005094 }
Eric Laurent10351942014-05-08 18:49:52 -07005095 }
5096 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005097#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005098 // when changing the audio output device, call addBatteryData to notify
5099 // the change
5100 if (mOutDevice != value) {
5101 uint32_t params = 0;
5102 // check whether speaker is on
5103 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5104 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005105 }
Eric Laurent10351942014-05-08 18:49:52 -07005106
5107 audio_devices_t deviceWithoutSpeaker
5108 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5109 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005110 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005111 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5112 }
5113
5114 if (params != 0) {
5115 addBatteryData(params);
5116 }
5117 }
Eric Laurent81784c32012-11-19 14:55:58 -08005118#endif
5119
Eric Laurent10351942014-05-08 18:49:52 -07005120 // forward device change to effects that have requested to be
5121 // aware of attached audio device.
5122 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005123 a2dpDeviceChanged =
5124 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005125 mOutDevice = value;
5126 for (size_t i = 0; i < mEffectChains.size(); i++) {
5127 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
5129 }
Eric Laurent10351942014-05-08 18:49:52 -07005130 }
Eric Laurent81784c32012-11-19 14:55:58 -08005131
Eric Laurent10351942014-05-08 18:49:52 -07005132 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005133 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005134 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005135 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005136 mStandby = true;
5137 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005138 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005139 }
Eric Laurent10351942014-05-08 18:49:52 -07005140 if (status == NO_ERROR && reconfig) {
5141 readOutputParameters_l();
5142 delete mAudioMixer;
5143 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005144 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005145 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005146 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005147 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005148 track->mChannelMask,
5149 track->mFormat,
5150 track->mSessionId);
5151 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005152 "%s(): AudioMixer cannot create track(%d)"
5153 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005154 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005155 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005156 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005157 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005158 }
Eric Laurent81784c32012-11-19 14:55:58 -08005159 }
5160
Eric Laurent42537be2016-01-08 17:16:42 -08005161 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005162}
5163
5164
5165void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5166{
Eric Laurent81784c32012-11-19 14:55:58 -08005167 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005168 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005169 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005170 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005171 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005172 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005173 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005174 } else {
5175 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005176 }
Eric Laurent81784c32012-11-19 14:55:58 -08005177
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005178 if (hasFastMixer()) {
5179 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5180
5181 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5182 // while we are dumping it. It may be inconsistent, but it won't mutate!
5183 // This is a large object so we place it on the heap.
5184 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07005185 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005186 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005187
5188#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005189 // Similar for state queue
5190 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5191 observerCopy.dump(fd);
5192 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5193 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005194#endif
5195
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005196#ifdef AUDIO_WATCHDOG
5197 if (mAudioWatchdog != 0) {
5198 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5199 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5200 wdCopy.dump(fd);
5201 }
5202#endif
5203
5204 } else {
5205 dprintf(fd, " No FastMixer\n");
5206 }
Eric Laurent81784c32012-11-19 14:55:58 -08005207}
5208
Eric Tan1882f162018-08-02 18:05:39 -07005209Json::Value AudioFlinger::MixerThread::getJsonDump() const
Eric Tan7b651152018-07-13 10:17:19 -07005210{
Eric Tan1882f162018-08-02 18:05:39 -07005211 Json::Value root;
5212 if (hasFastMixer()) {
5213 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5214 // while we are dumping it. It may be inconsistent, but it won't mutate!
5215 // This is a large object so we place it on the heap.
5216 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5217 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
5218 root["fastmixer_stats"] = copy->getJsonDump();
5219 } else {
5220 root["fastmixer_stats"] = "no_fastmixer";
5221 }
5222 return root;
Eric Tan7b651152018-07-13 10:17:19 -07005223}
5224
Eric Laurent81784c32012-11-19 14:55:58 -08005225uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5226{
5227 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5228}
5229
5230uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5231{
5232 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5233}
5234
5235void AudioFlinger::MixerThread::cacheParameters_l()
5236{
5237 PlaybackThread::cacheParameters_l();
5238
5239 // FIXME: Relaxed timing because of a certain device that can't meet latency
5240 // Should be reduced to 2x after the vendor fixes the driver issue
5241 // increase threshold again due to low power audio mode. The way this warning
5242 // threshold is calculated and its usefulness should be reconsidered anyway.
5243 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5244}
5245
5246// ----------------------------------------------------------------------------
5247
5248AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005249 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5250 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005251{
5252}
5253
Eric Laurentbfb1b832013-01-07 09:53:42 -08005254AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5255 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005256 ThreadBase::type_t type, bool systemReady)
5257 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005258 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259{
5260}
5261
Eric Laurent81784c32012-11-19 14:55:58 -08005262AudioFlinger::DirectOutputThread::~DirectOutputThread()
5263{
5264}
5265
Eric Laurent5850c4c2016-11-10 13:04:31 -08005266void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005267{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005268 float left, right;
5269
5270 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5271 left = right = 0;
5272 } else {
5273 float typeVolume = mStreamTypes[track->streamType()].volume;
5274 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005275 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005276
Andy Hung10cbff12017-02-21 17:30:14 -08005277 // Get volumeshaper scaling
5278 std::pair<float /* volume */, bool /* active */>
5279 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005280 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005281 v *= vh.first;
5282 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005283
Glenn Kastenc56f3422014-03-21 17:53:17 -07005284 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5285 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5286 if (left > GAIN_FLOAT_UNITY) {
5287 left = GAIN_FLOAT_UNITY;
5288 }
5289 left *= v;
5290 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5291 if (right > GAIN_FLOAT_UNITY) {
5292 right = GAIN_FLOAT_UNITY;
5293 }
5294 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005295 }
5296
5297 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005298 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299 if (left != mLeftVolFloat || right != mRightVolFloat) {
5300 mLeftVolFloat = left;
5301 mRightVolFloat = right;
5302
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 // Delegate volume control to effect in track effect chain if needed
5304 // only one effect chain can be present on DirectOutputThread, so if
5305 // there is one, the track is connected to it
5306 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005307 // if effect chain exists, volume is handled by it.
5308 // Convert volumes from float to 8.24
5309 uint32_t vl = (uint32_t)(left * (1 << 24));
5310 uint32_t vr = (uint32_t)(right * (1 << 24));
5311 // Direct/Offload effect chains set output volume in setVolume_l().
5312 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5313 } else {
5314 // otherwise we directly set the volume.
5315 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 }
5318 }
5319}
5320
Phil Burk43b4dcc2015-06-09 16:53:44 -07005321void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5322{
5323 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005324 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005325
Eric Laurent0f0631e2015-07-06 18:01:25 -07005326 if (previousTrack != 0 && latestTrack != 0) {
5327 if (mType == DIRECT) {
5328 if (previousTrack.get() != latestTrack.get()) {
5329 mFlushPending = true;
5330 }
5331 } else /* mType == OFFLOAD */ {
5332 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5333 mFlushPending = true;
5334 }
5335 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005336 }
5337 PlaybackThread::onAddNewTrack_l();
5338}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005339
Eric Laurent81784c32012-11-19 14:55:58 -08005340AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5341 Vector< sp<Track> > *tracksToRemove
5342)
5343{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005344 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005345 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005346 bool doHwPause = false;
5347 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005348
5349 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005350 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005351 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005352 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005353 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005354 continue;
5355 }
5356
Eric Laurent5850c4c2016-11-10 13:04:31 -08005357 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005358#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005359 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005360#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005361 // Only consider last track started for volume and mixer state control.
5362 // In theory an older track could underrun and restart after the new one starts
5363 // but as we only care about the transition phase between two tracks on a
5364 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005365 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005366 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005367
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005368 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005369 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005370 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005371 doHwPause = true;
5372 mHwPaused = true;
5373 }
5374 tracksToRemove->add(track);
5375 } else if (track->isFlushPending()) {
5376 track->flushAck();
5377 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005378 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005379 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005380 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005381 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005382 if (last) {
5383 mLeftVolFloat = mRightVolFloat = -1.0;
5384 if (mHwPaused) {
5385 doHwResume = true;
5386 mHwPaused = false;
5387 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005388 }
5389 }
5390
Eric Laurent81784c32012-11-19 14:55:58 -08005391 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005392 // for all its buffers to be filled before processing it.
5393 // Allow draining the buffer in case the client
5394 // app does not call stop() and relies on underrun to stop:
5395 // hence the test on (track->mRetryCount > 1).
5396 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005397 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005398 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005399 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005400 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005401 minFrames = mNormalFrameCount;
5402 } else {
5403 minFrames = 1;
5404 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005405
Eric Laurentab5cdba2014-06-09 17:22:27 -07005406 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5407 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005408 {
Andy Hungc0691382018-09-12 18:01:57 -07005409 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005410
5411 if (track->mFillingUpStatus == Track::FS_FILLED) {
5412 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005413 if (last) {
5414 // make sure processVolume_l() will apply new volume even if 0
5415 mLeftVolFloat = mRightVolFloat = -1.0;
5416 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005417 if (!mHwSupportsPause) {
5418 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005419 }
5420 }
5421
5422 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005423 processVolume_l(track, last);
5424 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005425 sp<Track> previousTrack = mPreviousTrack.promote();
5426 if (previousTrack != 0) {
5427 if (track != previousTrack.get()) {
5428 // Flush any data still being written from last track
5429 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005430 // Invalidate previous track to force a seek when resuming.
5431 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005432 }
5433 }
5434 mPreviousTrack = track;
5435
Eric Laurentd595b7c2013-04-03 17:27:56 -07005436 // reset retry count
5437 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005438 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005439 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005440 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005441 doHwResume = true;
5442 mHwPaused = false;
5443 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005444 }
Eric Laurent81784c32012-11-19 14:55:58 -08005445 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005446 // clear effect chain input buffer if the last active track started underruns
5447 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005448 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005449 mEffectChains[0]->clearInputBuffer();
5450 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005451 if (track->isStopping_1()) {
5452 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005453 if (last && mHwPaused) {
5454 doHwResume = true;
5455 mHwPaused = false;
5456 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005457 }
5458 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5459 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005460 // We have consumed all the buffers of this track.
5461 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005462 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005463 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005464 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5465 } else {
5466 audioHALFrames = 0;
5467 }
5468
Andy Hung818e7a32016-02-16 18:08:07 -08005469 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005470 if (mStandby || !last ||
5471 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005472 if (track->isStopping_2()) {
5473 track->mState = TrackBase::STOPPED;
5474 }
Eric Laurent81784c32012-11-19 14:55:58 -08005475 if (track->isStopped()) {
5476 track->reset();
5477 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005478 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005479 }
5480 } else {
5481 // No buffers for this track. Give it a few chances to
5482 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005483 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005484 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005485 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005486 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005487 // indicate to client process that the track was disabled because of underrun;
5488 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005489 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005490 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005491 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5492 "minFrames = %u, mFormat = %#x",
5493 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005494 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005495 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005496 doHwPause = true;
5497 mHwPaused = true;
5498 }
Eric Laurent81784c32012-11-19 14:55:58 -08005499 }
5500 }
5501 }
5502 }
5503
Eric Laurentd1f69b02014-12-15 14:33:13 -08005504 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005505 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005506 for (size_t i = 0; i < mTracks.size(); i++) {
5507 if (mTracks[i]->isFlushPending()) {
5508 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005509 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005510 }
5511 }
5512 }
5513
5514 // make sure the pause/flush/resume sequence is executed in the right order.
5515 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5516 // before flush and then resume HW. This can happen in case of pause/flush/resume
5517 // if resume is received before pause is executed.
5518 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005519 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005520 status_t result = mOutput->stream->pause();
5521 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005522 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005523 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005524 flushHw_l();
5525 }
5526 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005527 status_t result = mOutput->stream->resume();
5528 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005529 }
Eric Laurent81784c32012-11-19 14:55:58 -08005530 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005531 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005532
5533 return mixerStatus;
5534}
5535
5536void AudioFlinger::DirectOutputThread::threadLoop_mix()
5537{
Eric Laurent81784c32012-11-19 14:55:58 -08005538 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005539 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005540 // output audio to hardware
5541 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005542 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005543 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005544 status_t status = mActiveTrack->getNextBuffer(&buffer);
5545 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005546 // no need to pad with 0 for compressed audio
5547 if (audio_has_proportional_frames(mFormat)) {
5548 memset(curBuf, 0, frameCount * mFrameSize);
5549 }
Eric Laurent81784c32012-11-19 14:55:58 -08005550 break;
5551 }
5552 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5553 frameCount -= buffer.frameCount;
5554 curBuf += buffer.frameCount * mFrameSize;
5555 mActiveTrack->releaseBuffer(&buffer);
5556 }
Andy Hung2098f272014-02-27 14:00:06 -08005557 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005558 mSleepTimeUs = 0;
5559 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005560 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005561}
5562
5563void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5564{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005565 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005566 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005567 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005568 return;
5569 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005570 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005571 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005572 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005573 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005574 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005575 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005576 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005577 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005578 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005579 }
5580}
5581
Eric Laurentd1f69b02014-12-15 14:33:13 -08005582void AudioFlinger::DirectOutputThread::threadLoop_exit()
5583{
5584 {
5585 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005586 for (size_t i = 0; i < mTracks.size(); i++) {
5587 if (mTracks[i]->isFlushPending()) {
5588 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005589 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005590 }
5591 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005592 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005593 flushHw_l();
5594 }
5595 }
5596 PlaybackThread::threadLoop_exit();
5597}
5598
5599// must be called with thread mutex locked
5600bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5601{
5602 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005603 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005604
vivek mehta9cd7ad12016-03-17 00:18:29 -07005605 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5606 return !mStandby;
5607 }
5608
Eric Laurentd1f69b02014-12-15 14:33:13 -08005609 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5610 // after a timeout and we will enter standby then.
5611 if (mTracks.size() > 0) {
5612 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005613 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5614 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005615 }
5616
Eric Laurent5cff4032015-05-26 13:49:58 -07005617 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005618}
5619
Eric Laurent10351942014-05-08 18:49:52 -07005620// checkForNewParameter_l() must be called with ThreadBase::mLock held
5621bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5622 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005623{
5624 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005625 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005626
Eric Laurent10351942014-05-08 18:49:52 -07005627 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005628
Eric Laurent10351942014-05-08 18:49:52 -07005629 AudioParameter param = AudioParameter(keyValuePair);
5630 int value;
5631 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5632 // forward device change to effects that have requested to be
5633 // aware of attached audio device.
5634 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005635 a2dpDeviceChanged =
5636 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005637 mOutDevice = value;
5638 for (size_t i = 0; i < mEffectChains.size(); i++) {
5639 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005640 }
5641 }
Eric Laurent81784c32012-11-19 14:55:58 -08005642 }
Eric Laurent10351942014-05-08 18:49:52 -07005643 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5644 // do not accept frame count changes if tracks are open as the track buffer
5645 // size depends on frame count and correct behavior would not be garantied
5646 // if frame count is changed after track creation
5647 if (!mTracks.isEmpty()) {
5648 status = INVALID_OPERATION;
5649 } else {
5650 reconfig = true;
5651 }
5652 }
5653 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005654 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005655 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005656 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005657 mStandby = true;
5658 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005659 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005660 }
5661 if (status == NO_ERROR && reconfig) {
5662 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005663 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005664 }
5665 }
5666
Eric Laurent42537be2016-01-08 17:16:42 -08005667 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005668}
5669
5670uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5671{
5672 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005673 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005674 time = PlaybackThread::activeSleepTimeUs();
5675 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005676 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005677 }
5678 return time;
5679}
5680
5681uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5682{
5683 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005684 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005685 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5686 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005687 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005688 }
5689 return time;
5690}
5691
5692uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5693{
5694 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005695 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005696 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5697 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005698 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
5700 return time;
5701}
5702
5703void AudioFlinger::DirectOutputThread::cacheParameters_l()
5704{
5705 PlaybackThread::cacheParameters_l();
5706
5707 // use shorter standby delay as on normal output to release
5708 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005709 // no delay on outputs with HW A/V sync
5710 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005711 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005712 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005713 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005714 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005715 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005716 }
Eric Laurent81784c32012-11-19 14:55:58 -08005717}
5718
Eric Laurente659ef42014-09-29 13:06:46 -07005719void AudioFlinger::DirectOutputThread::flushHw_l()
5720{
Phil Burk062e67a2015-02-11 13:40:50 -08005721 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005722 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005723 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005724 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005725}
5726
Andy Hung10cbff12017-02-21 17:30:14 -08005727int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5728 // If a VolumeShaper is active, we must wake up periodically to update volume.
5729 const int64_t NS_PER_MS = 1000000;
5730 return mVolumeShaperActive ?
5731 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5732}
5733
Eric Laurent81784c32012-11-19 14:55:58 -08005734// ----------------------------------------------------------------------------
5735
Eric Laurentbfb1b832013-01-07 09:53:42 -08005736AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005737 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005738 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005739 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005740 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005741 mDrainSequence(0),
5742 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005743{
5744}
5745
5746AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5747{
5748}
5749
5750void AudioFlinger::AsyncCallbackThread::onFirstRef()
5751{
5752 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5753}
5754
5755bool AudioFlinger::AsyncCallbackThread::threadLoop()
5756{
5757 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005758 uint32_t writeAckSequence;
5759 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005760 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005761
5762 {
5763 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005764 while (!((mWriteAckSequence & 1) ||
5765 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005766 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005767 exitPending())) {
5768 mWaitWorkCV.wait(mLock);
5769 }
5770
Eric Laurentbfb1b832013-01-07 09:53:42 -08005771 if (exitPending()) {
5772 break;
5773 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005774 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5775 mWriteAckSequence, mDrainSequence);
5776 writeAckSequence = mWriteAckSequence;
5777 mWriteAckSequence &= ~1;
5778 drainSequence = mDrainSequence;
5779 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005780 asyncError = mAsyncError;
5781 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005782 }
5783 {
Eric Laurent4de95592013-09-26 15:28:21 -07005784 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5785 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005786 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005787 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005788 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005789 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005790 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005791 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005792 if (asyncError) {
5793 playbackThread->onAsyncError();
5794 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005795 }
5796 }
5797 }
5798 return false;
5799}
5800
5801void AudioFlinger::AsyncCallbackThread::exit()
5802{
5803 ALOGV("AsyncCallbackThread::exit");
5804 Mutex::Autolock _l(mLock);
5805 requestExit();
5806 mWaitWorkCV.broadcast();
5807}
5808
Eric Laurent3b4529e2013-09-05 18:09:19 -07005809void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005810{
5811 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005812 // bit 0 is cleared
5813 mWriteAckSequence = sequence << 1;
5814}
5815
5816void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5817{
5818 Mutex::Autolock _l(mLock);
5819 // ignore unexpected callbacks
5820 if (mWriteAckSequence & 2) {
5821 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005822 mWaitWorkCV.signal();
5823 }
5824}
5825
Eric Laurent3b4529e2013-09-05 18:09:19 -07005826void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005827{
5828 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005829 // bit 0 is cleared
5830 mDrainSequence = sequence << 1;
5831}
5832
5833void AudioFlinger::AsyncCallbackThread::resetDraining()
5834{
5835 Mutex::Autolock _l(mLock);
5836 // ignore unexpected callbacks
5837 if (mDrainSequence & 2) {
5838 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005839 mWaitWorkCV.signal();
5840 }
5841}
5842
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005843void AudioFlinger::AsyncCallbackThread::setAsyncError()
5844{
5845 Mutex::Autolock _l(mLock);
5846 mAsyncError = true;
5847 mWaitWorkCV.signal();
5848}
5849
Eric Laurentbfb1b832013-01-07 09:53:42 -08005850
5851// ----------------------------------------------------------------------------
5852AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005853 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5854 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005855 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5856 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005857{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005858 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005859 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005860 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005861}
5862
Eric Laurentbfb1b832013-01-07 09:53:42 -08005863void AudioFlinger::OffloadThread::threadLoop_exit()
5864{
5865 if (mFlushPending || mHwPaused) {
5866 // If a flush is pending or track was paused, just discard buffered data
5867 flushHw_l();
5868 } else {
5869 mMixerStatus = MIXER_DRAIN_ALL;
5870 threadLoop_drain();
5871 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005872 if (mUseAsyncWrite) {
5873 ALOG_ASSERT(mCallbackThread != 0);
5874 mCallbackThread->exit();
5875 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005876 PlaybackThread::threadLoop_exit();
5877}
5878
5879AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5880 Vector< sp<Track> > *tracksToRemove
5881)
5882{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005883 size_t count = mActiveTracks.size();
5884
5885 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005886 bool doHwPause = false;
5887 bool doHwResume = false;
5888
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005889 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005890
Eric Laurentbfb1b832013-01-07 09:53:42 -08005891 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005892 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005893 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005894#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005895 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005896#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005897 // Only consider last track started for volume and mixer state control.
5898 // In theory an older track could underrun and restart after the new one starts
5899 // but as we only care about the transition phase between two tracks on a
5900 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005901 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005902 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005903
Haynes Mathew George7844f672014-01-15 12:32:55 -08005904 if (track->isInvalid()) {
5905 ALOGW("An invalidated track shouldn't be in active list");
5906 tracksToRemove->add(track);
5907 continue;
5908 }
5909
5910 if (track->mState == TrackBase::IDLE) {
5911 ALOGW("An idle track shouldn't be in active list");
5912 continue;
5913 }
5914
Eric Laurentbfb1b832013-01-07 09:53:42 -08005915 if (track->isPausing()) {
5916 track->setPaused();
5917 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005918 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005919 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005920 mHwPaused = true;
5921 }
5922 // If we were part way through writing the mixbuffer to
5923 // the HAL we must save this until we resume
5924 // BUG - this will be wrong if a different track is made active,
5925 // in that case we want to discard the pending data in the
5926 // mixbuffer and tell the client to present it again when the
5927 // track is resumed
5928 mPausedWriteLength = mCurrentWriteLength;
5929 mPausedBytesRemaining = mBytesRemaining;
5930 mBytesRemaining = 0; // stop writing
5931 }
5932 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005933 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005934 if (track->isStopping_1()) {
5935 track->mRetryCount = kMaxTrackStopRetriesOffload;
5936 } else {
5937 track->mRetryCount = kMaxTrackRetriesOffload;
5938 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005939 track->flushAck();
5940 if (last) {
5941 mFlushPending = true;
5942 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005943 } else if (track->isResumePending()){
5944 track->resumeAck();
5945 if (last) {
5946 if (mPausedBytesRemaining) {
5947 // Need to continue write that was interrupted
5948 mCurrentWriteLength = mPausedWriteLength;
5949 mBytesRemaining = mPausedBytesRemaining;
5950 mPausedBytesRemaining = 0;
5951 }
5952 if (mHwPaused) {
5953 doHwResume = true;
5954 mHwPaused = false;
5955 // threadLoop_mix() will handle the case that we need to
5956 // resume an interrupted write
5957 }
5958 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005959 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005960
Eric Laurent3df841a2016-07-15 15:15:40 -07005961 mLeftVolFloat = mRightVolFloat = -1.0;
5962
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005963 // Do not handle new data in this iteration even if track->framesReady()
5964 mixerStatus = MIXER_TRACKS_ENABLED;
5965 }
5966 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005967 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07005968 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005969 if (track->mFillingUpStatus == Track::FS_FILLED) {
5970 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005971 if (last) {
5972 // make sure processVolume_l() will apply new volume even if 0
5973 mLeftVolFloat = mRightVolFloat = -1.0;
5974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005975 }
5976
5977 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005978 sp<Track> previousTrack = mPreviousTrack.promote();
5979 if (previousTrack != 0) {
5980 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005981 // Flush any data still being written from last track
5982 mBytesRemaining = 0;
5983 if (mPausedBytesRemaining) {
5984 // Last track was paused so we also need to flush saved
5985 // mixbuffer state and invalidate track so that it will
5986 // re-submit that unwritten data when it is next resumed
5987 mPausedBytesRemaining = 0;
5988 // Invalidate is a bit drastic - would be more efficient
5989 // to have a flag to tell client that some of the
5990 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005991 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005992 }
5993 // flush data already sent to the DSP if changing audio session as audio
5994 // comes from a different source. Also invalidate previous track to force a
5995 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005996 if (previousTrack->sessionId() != track->sessionId()) {
5997 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005998 }
5999 }
6000 }
6001 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006002 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006003 if (track->isStopping_1()) {
6004 track->mRetryCount = kMaxTrackStopRetriesOffload;
6005 } else {
6006 track->mRetryCount = kMaxTrackRetriesOffload;
6007 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006008 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006009 mixerStatus = MIXER_TRACKS_READY;
6010 }
6011 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006012 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006013 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006014 if (--(track->mRetryCount) <= 0) {
6015 // Hardware buffer can hold a large amount of audio so we must
6016 // wait for all current track's data to drain before we say
6017 // that the track is stopped.
6018 if (mBytesRemaining == 0) {
6019 // Only start draining when all data in mixbuffer
6020 // has been written
6021 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6022 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6023 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6024 if (last && !mStandby) {
6025 // do not modify drain sequence if we are already draining. This happens
6026 // when resuming from pause after drain.
6027 if ((mDrainSequence & 1) == 0) {
6028 mSleepTimeUs = 0;
6029 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6030 mixerStatus = MIXER_DRAIN_TRACK;
6031 mDrainSequence += 2;
6032 }
6033 if (mHwPaused) {
6034 // It is possible to move from PAUSED to STOPPING_1 without
6035 // a resume so we must ensure hardware is running
6036 doHwResume = true;
6037 mHwPaused = false;
6038 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006039 }
6040 }
Eric Laurente93cc032016-05-05 10:15:10 -07006041 } else if (last) {
6042 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6043 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006044 }
6045 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006046 // Drain has completed or we are in standby, signal presentation complete
6047 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006048 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006049 uint32_t latency = 0;
6050 status_t result = mOutput->stream->getLatency(&latency);
6051 ALOGE_IF(result != OK,
6052 "Error when retrieving output stream latency: %d", result);
6053 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006054 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006055 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006056 track->presentationComplete(framesWritten, audioHALFrames);
6057 track->reset();
6058 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006059 // DIRECT and OFFLOADED stop resets frame counts.
6060 if (!mUseAsyncWrite) {
6061 // If we don't get explicit drain notification we must
6062 // register discontinuity regardless of whether this is
6063 // the previous (!last) or the upcoming (last) track
6064 // to avoid skipping the discontinuity.
6065 mTimestampVerifier.discontinuity();
6066 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006067 }
6068 } else {
6069 // No buffers for this track. Give it a few chances to
6070 // fill a buffer, then remove it from active list.
6071 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006072 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006073 uint64_t position = 0;
6074 struct timespec unused;
6075 // The running check restarts the retry counter at least once.
6076 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6077 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6078 running = true;
6079 mOffloadUnderrunPosition = position;
6080 }
6081 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006082 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6083 (long long)position, (long long)mOffloadUnderrunPosition);
6084 }
6085 if (running) { // still running, give us more time.
6086 track->mRetryCount = kMaxTrackRetriesOffload;
6087 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006088 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6089 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006090 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006091 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006092 // it will then automatically call start() when data is available
6093 track->disable();
6094 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006095 } else if (last){
6096 mixerStatus = MIXER_TRACKS_ENABLED;
6097 }
6098 }
6099 }
6100 // compute volume for this track
6101 processVolume_l(track, last);
6102 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006103
Eric Laurentea0fade2013-10-04 16:23:48 -07006104 // make sure the pause/flush/resume sequence is executed in the right order.
6105 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6106 // before flush and then resume HW. This can happen in case of pause/flush/resume
6107 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006108 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006109 status_t result = mOutput->stream->pause();
6110 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006111 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006112 if (mFlushPending) {
6113 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006114 }
Eric Laurentfd477972013-10-25 18:10:40 -07006115 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006116 status_t result = mOutput->stream->resume();
6117 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006118 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006119
Eric Laurentbfb1b832013-01-07 09:53:42 -08006120 // remove all the tracks that need to be...
6121 removeTracks_l(*tracksToRemove);
6122
6123 return mixerStatus;
6124}
6125
Eric Laurentbfb1b832013-01-07 09:53:42 -08006126// must be called with thread mutex locked
6127bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6128{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006129 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6130 mWriteAckSequence, mDrainSequence);
6131 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006132 return true;
6133 }
6134 return false;
6135}
6136
Eric Laurentbfb1b832013-01-07 09:53:42 -08006137bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6138{
6139 Mutex::Autolock _l(mLock);
6140 return waitingAsyncCallback_l();
6141}
6142
6143void AudioFlinger::OffloadThread::flushHw_l()
6144{
Eric Laurente659ef42014-09-29 13:06:46 -07006145 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006146 // Flush anything still waiting in the mixbuffer
6147 mCurrentWriteLength = 0;
6148 mBytesRemaining = 0;
6149 mPausedWriteLength = 0;
6150 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006151 // reset bytes written count to reflect that DSP buffers are empty after flush.
6152 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006153 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006154
Eric Laurentbfb1b832013-01-07 09:53:42 -08006155 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006156 // discard any pending drain or write ack by incrementing sequence
6157 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6158 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006159 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006160 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6161 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006162 }
6163}
6164
Haynes Mathew George05317d22016-05-03 16:34:26 -07006165void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6166{
6167 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006168 if (PlaybackThread::invalidateTracks_l(streamType)) {
6169 mFlushPending = true;
6170 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006171}
6172
Eric Laurentbfb1b832013-01-07 09:53:42 -08006173// ----------------------------------------------------------------------------
6174
Eric Laurent81784c32012-11-19 14:55:58 -08006175AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006176 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006177 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006178 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006179 mWaitTimeMs(UINT_MAX)
6180{
6181 addOutputTrack(mainThread);
6182}
6183
6184AudioFlinger::DuplicatingThread::~DuplicatingThread()
6185{
6186 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6187 mOutputTracks[i]->destroy();
6188 }
6189}
6190
6191void AudioFlinger::DuplicatingThread::threadLoop_mix()
6192{
6193 // mix buffers...
6194 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006195 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006196 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006197 if (mMixerBufferValid) {
6198 memset(mMixerBuffer, 0, mMixerBufferSize);
6199 } else {
6200 memset(mSinkBuffer, 0, mSinkBufferSize);
6201 }
Eric Laurent81784c32012-11-19 14:55:58 -08006202 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006203 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006204 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006205 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006206 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006207}
6208
6209void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6210{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006211 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006212 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006213 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006214 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006215 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006216 }
6217 } else if (mBytesWritten != 0) {
6218 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6219 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006220 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006221 } else {
6222 // flush remaining overflow buffers in output tracks
6223 writeFrames = 0;
6224 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006225 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006226 }
6227}
6228
Eric Laurentbfb1b832013-01-07 09:53:42 -08006229ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006230{
6231 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006232 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6233
6234 // Consider the first OutputTrack for timestamp and frame counting.
6235
6236 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6237 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6238 // we always claim success.
6239 if (i == 0) {
6240 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6241 ALOGD_IF(correction != 0 && writeFrames != 0,
6242 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6243 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6244 mFramesWritten -= correction;
6245 }
6246
6247 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006248 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006249 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006250 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006251}
6252
6253void AudioFlinger::DuplicatingThread::threadLoop_standby()
6254{
6255 // DuplicatingThread implements standby by stopping all tracks
6256 for (size_t i = 0; i < outputTracks.size(); i++) {
6257 outputTracks[i]->stop();
6258 }
6259}
6260
Andy Hung1bc088a2018-02-09 15:57:31 -08006261void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6262{
6263 MixerThread::dumpInternals(fd, args);
6264
6265 std::stringstream ss;
6266 const size_t numTracks = mOutputTracks.size();
6267 ss << " " << numTracks << " OutputTracks";
6268 if (numTracks > 0) {
6269 ss << ":";
6270 for (const auto &track : mOutputTracks) {
6271 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006272 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006273 if (thread.get() != nullptr) {
6274 ss << thread.get() << ", " << thread->id();
6275 } else {
6276 ss << "null";
6277 }
6278 ss << ")";
6279 }
6280 }
6281 ss << "\n";
6282 std::string result = ss.str();
6283 write(fd, result.c_str(), result.size());
6284}
6285
Eric Laurent81784c32012-11-19 14:55:58 -08006286void AudioFlinger::DuplicatingThread::saveOutputTracks()
6287{
6288 outputTracks = mOutputTracks;
6289}
6290
6291void AudioFlinger::DuplicatingThread::clearOutputTracks()
6292{
6293 outputTracks.clear();
6294}
6295
6296void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6297{
6298 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006299 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6300 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6301 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6302 const size_t frameCount =
6303 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6304 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6305 // from different OutputTracks and their associated MixerThreads (e.g. one may
6306 // nearly empty and the other may be dropping data).
6307
6308 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006309 this,
6310 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006311 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006312 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006313 frameCount,
6314 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006315 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6316 if (status != NO_ERROR) {
6317 ALOGE("addOutputTrack() initCheck failed %d", status);
6318 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006319 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006320 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6321 mOutputTracks.add(outputTrack);
6322 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6323 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006324}
6325
6326void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6327{
6328 Mutex::Autolock _l(mLock);
6329 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6330 if (mOutputTracks[i]->thread() == thread) {
6331 mOutputTracks[i]->destroy();
6332 mOutputTracks.removeAt(i);
6333 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006334 if (thread->getOutput() == mOutput) {
6335 mOutput = NULL;
6336 }
Eric Laurent81784c32012-11-19 14:55:58 -08006337 return;
6338 }
6339 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006340 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006341}
6342
6343// caller must hold mLock
6344void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6345{
6346 mWaitTimeMs = UINT_MAX;
6347 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6348 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6349 if (strong != 0) {
6350 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6351 if (waitTimeMs < mWaitTimeMs) {
6352 mWaitTimeMs = waitTimeMs;
6353 }
6354 }
6355 }
6356}
6357
6358
6359bool AudioFlinger::DuplicatingThread::outputsReady(
6360 const SortedVector< sp<OutputTrack> > &outputTracks)
6361{
6362 for (size_t i = 0; i < outputTracks.size(); i++) {
6363 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6364 if (thread == 0) {
6365 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6366 outputTracks[i].get());
6367 return false;
6368 }
6369 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6370 // see note at standby() declaration
6371 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6372 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6373 thread.get());
6374 return false;
6375 }
6376 }
6377 return true;
6378}
6379
Kevin Rocard12381092018-04-11 09:19:59 -07006380void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6381 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006382{
Kevin Rocard12381092018-04-11 09:19:59 -07006383 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6384 outputTrack->setMetadatas(metadata.tracks);
6385 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006386}
6387
Eric Laurent81784c32012-11-19 14:55:58 -08006388uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6389{
6390 return (mWaitTimeMs * 1000) / 2;
6391}
6392
6393void AudioFlinger::DuplicatingThread::cacheParameters_l()
6394{
6395 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6396 updateWaitTime_l();
6397
6398 MixerThread::cacheParameters_l();
6399}
6400
Eric Laurent6acd1d42017-01-04 14:23:29 -08006401
Eric Laurent81784c32012-11-19 14:55:58 -08006402// ----------------------------------------------------------------------------
6403// Record
6404// ----------------------------------------------------------------------------
6405
6406AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6407 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006408 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006409 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006410 audio_devices_t inDevice,
6411 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006412 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006413 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006414 mInput(input),
6415 mActiveTracks(&this->mLocalLog),
6416 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006417 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006418 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006419 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6420 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006421 // mFastCapture below
6422 , mFastCaptureFutex(0)
6423 // mInputSource
6424 // mPipeSink
6425 // mPipeSource
6426 , mPipeFramesP2(0)
6427 // mPipeMemory
6428 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006429 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006430 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006431{
Glenn Kastend7dca052015-03-05 16:05:54 -08006432 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6433 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006434
Andy Hungc8fddf32018-08-08 18:32:37 -07006435 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6436 mIsMsdDevice = strcmp(
6437 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6438 }
6439
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006440 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006441
Andy Hungc8fddf32018-08-08 18:32:37 -07006442 // TODO: We may also match on address as well as device type for
6443 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6444 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6445 "audio.timestamp.corrected_input_devices",
6446 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6447 : AUDIO_DEVICE_NONE));
6448
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006449 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006450 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006451 size_t numCounterOffers = 0;
6452 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006453#if !LOG_NDEBUG
6454 ssize_t index =
6455#else
6456 (void)
6457#endif
6458 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006459 ALOG_ASSERT(index == 0);
6460
6461 // initialize fast capture depending on configuration
6462 bool initFastCapture;
6463 switch (kUseFastCapture) {
6464 case FastCapture_Never:
6465 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006466 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006467 break;
6468 case FastCapture_Always:
6469 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006470 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006471 break;
6472 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006473 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006474 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6475 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6476 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006477 break;
6478 // case FastCapture_Dynamic:
6479 }
6480
6481 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006482 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006483 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006484 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6485 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006486 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006487 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006488 const sp<MemoryDealer> roHeap(readOnlyHeap());
6489 sp<IMemory> pipeMemory;
6490 if ((roHeap == 0) ||
6491 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006492 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6493 ALOGE("not enough memory for pipe buffer size=%zu; "
6494 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6495 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6496 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006497 goto failed;
6498 }
6499 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6500 memset(pipeBuffer, 0, pipeSize);
6501 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6502 const NBAIO_Format offers[1] = {format};
6503 size_t numCounterOffers = 0;
6504 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6505 ALOG_ASSERT(index == 0);
6506 mPipeSink = pipe;
6507 PipeReader *pipeReader = new PipeReader(*pipe);
6508 numCounterOffers = 0;
6509 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6510 ALOG_ASSERT(index == 0);
6511 mPipeSource = pipeReader;
6512 mPipeFramesP2 = pipeFramesP2;
6513 mPipeMemory = pipeMemory;
6514
6515 // create fast capture
6516 mFastCapture = new FastCapture();
6517 FastCaptureStateQueue *sq = mFastCapture->sq();
6518#ifdef STATE_QUEUE_DUMP
6519 // FIXME
6520#endif
6521 FastCaptureState *state = sq->begin();
6522 state->mCblk = NULL;
6523 state->mInputSource = mInputSource.get();
6524 state->mInputSourceGen++;
6525 state->mPipeSink = pipe;
6526 state->mPipeSinkGen++;
6527 state->mFrameCount = mFrameCount;
6528 state->mCommand = FastCaptureState::COLD_IDLE;
6529 // already done in constructor initialization list
6530 //mFastCaptureFutex = 0;
6531 state->mColdFutexAddr = &mFastCaptureFutex;
6532 state->mColdGen++;
6533 state->mDumpState = &mFastCaptureDumpState;
6534#ifdef TEE_SINK
6535 // FIXME
6536#endif
6537 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6538 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6539 sq->end();
6540 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6541
6542 // start the fast capture
6543 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6544 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006545 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006546 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006547#ifdef AUDIO_WATCHDOG
6548 // FIXME
6549#endif
6550
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006551 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006552 }
Andy Hung8946a282018-04-19 20:04:56 -07006553#ifdef TEE_SINK
6554 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6555 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6556#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006557failed: ;
6558
6559 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006560}
6561
Eric Laurent81784c32012-11-19 14:55:58 -08006562AudioFlinger::RecordThread::~RecordThread()
6563{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006564 if (mFastCapture != 0) {
6565 FastCaptureStateQueue *sq = mFastCapture->sq();
6566 FastCaptureState *state = sq->begin();
6567 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6568 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6569 if (old == -1) {
6570 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6571 }
6572 }
6573 state->mCommand = FastCaptureState::EXIT;
6574 sq->end();
6575 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6576 mFastCapture->join();
6577 mFastCapture.clear();
6578 }
6579 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006580 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006581 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006582}
6583
6584void AudioFlinger::RecordThread::onFirstRef()
6585{
Glenn Kastend7dca052015-03-05 16:05:54 -08006586 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006587}
6588
Eric Laurent555530a2017-02-07 18:17:24 -08006589void AudioFlinger::RecordThread::preExit()
6590{
6591 ALOGV(" preExit()");
6592 Mutex::Autolock _l(mLock);
6593 for (size_t i = 0; i < mTracks.size(); i++) {
6594 sp<RecordTrack> track = mTracks[i];
6595 track->invalidate();
6596 }
6597 mActiveTracks.clear();
6598 mStartStopCond.broadcast();
6599}
6600
Eric Laurent81784c32012-11-19 14:55:58 -08006601bool AudioFlinger::RecordThread::threadLoop()
6602{
Eric Laurent81784c32012-11-19 14:55:58 -08006603 nsecs_t lastWarning = 0;
6604
6605 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006606
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006607reacquire_wakelock:
6608 sp<RecordTrack> activeTrack;
6609 {
6610 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006611 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006612 }
6613
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006614 // used to request a deferred sleep, to be executed later while mutex is unlocked
6615 uint32_t sleepUs = 0;
6616
6617 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006618 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006619 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006620
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006621 // activeTracks accumulates a copy of a subset of mActiveTracks
6622 Vector< sp<RecordTrack> > activeTracks;
6623
Glenn Kasten735f45f2014-08-18 15:51:59 -07006624 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006625 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006626
Glenn Kasten735f45f2014-08-18 15:51:59 -07006627 // reference to a fast track which is about to be removed
6628 sp<RecordTrack> fastTrackToRemove;
6629
Eric Laurent81784c32012-11-19 14:55:58 -08006630 { // scope for mLock
6631 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006632
Eric Laurent021cf962014-05-13 10:18:14 -07006633 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006634
Eric Laurent000a4192014-01-29 15:17:32 -08006635 // check exitPending here because checkForNewParameters_l() and
6636 // checkForNewParameters_l() can temporarily release mLock
6637 if (exitPending()) {
6638 break;
6639 }
6640
Eric Laurent5c25d562016-07-13 17:17:45 -07006641 // sleep with mutex unlocked
6642 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006643 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006644 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6645 ATRACE_END();
6646 sleepUs = 0;
6647 continue;
6648 }
6649
Glenn Kasten2b806402013-11-20 16:37:38 -08006650 // if no active track(s), then standby and release wakelock
6651 size_t size = mActiveTracks.size();
6652 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006653 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006654 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006655 releaseWakeLock_l();
6656 ALOGV("RecordThread: loop stopping");
6657 // go to sleep
6658 mWaitWorkCV.wait(mLock);
6659 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006660 goto reacquire_wakelock;
6661 }
6662
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006663 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006664 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006665 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006666
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006667 activeTrack = mActiveTracks[i];
6668 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006669 if (activeTrack->isFastTrack()) {
6670 ALOG_ASSERT(fastTrackToRemove == 0);
6671 fastTrackToRemove = activeTrack;
6672 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006673 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006674 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006675 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006676 continue;
6677 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006678
6679 TrackBase::track_state activeTrackState = activeTrack->mState;
6680 switch (activeTrackState) {
6681
6682 case TrackBase::PAUSING:
6683 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006684 doBroadcast = true;
6685 size--;
6686 continue;
6687
6688 case TrackBase::STARTING_1:
6689 sleepUs = 10000;
6690 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006691 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006692 continue;
6693
6694 case TrackBase::STARTING_2:
6695 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006696 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006697 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006698 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006699 break;
6700
6701 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006702 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006703 break;
6704
6705 case TrackBase::IDLE:
6706 i++;
6707 continue;
6708
6709 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006710 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006711 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006712
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006713 activeTracks.add(activeTrack);
6714 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006715
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006716 if (activeTrack->isFastTrack()) {
6717 ALOG_ASSERT(!mFastTrackAvail);
6718 ALOG_ASSERT(fastTrack == 0);
6719 fastTrack = activeTrack;
6720 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006721 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006722
Andy Hungdae27702016-10-31 14:01:16 -07006723 mActiveTracks.updatePowerState(this);
6724
Kevin Rocard069c2712018-03-29 19:09:14 -07006725 updateMetadata_l();
6726
Eric Laurent5c25d562016-07-13 17:17:45 -07006727 if (allStopped) {
6728 standbyIfNotAlreadyInStandby();
6729 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006730 if (doBroadcast) {
6731 mStartStopCond.broadcast();
6732 }
6733
6734 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006735 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006736 if (sleepUs == 0) {
6737 sleepUs = kRecordThreadSleepUs;
6738 }
6739 continue;
6740 }
6741 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006742
Eric Laurent81784c32012-11-19 14:55:58 -08006743 lockEffectChains_l(effectChains);
6744 }
6745
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006746 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006747
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006748 size_t size = effectChains.size();
6749 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006750 // thread mutex is not locked, but effect chain is locked
6751 effectChains[i]->process_l();
6752 }
6753
Glenn Kasten735f45f2014-08-18 15:51:59 -07006754 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006755 if (mFastCapture != 0) {
6756 FastCaptureStateQueue *sq = mFastCapture->sq();
6757 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006758 bool didModify = false;
6759 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006760 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6761 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6762 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6763 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6764 if (old == -1) {
6765 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6766 }
6767 }
6768 state->mCommand = FastCaptureState::READ_WRITE;
6769#if 0 // FIXME
6770 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006771 FastThreadDumpState::kSamplingNforLowRamDevice :
6772 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006773#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006774 didModify = true;
6775 }
6776 audio_track_cblk_t *cblkOld = state->mCblk;
6777 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6778 if (cblkNew != cblkOld) {
6779 state->mCblk = cblkNew;
6780 // block until acked if removing a fast track
6781 if (cblkOld != NULL) {
6782 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6783 }
6784 didModify = true;
6785 }
jiabin01c8f562018-07-19 17:47:28 -07006786 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6787 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6788 if (state->mFastPatchRecordBufferProvider != abp) {
6789 state->mFastPatchRecordBufferProvider = abp;
6790 state->mFastPatchRecordFormat = fastTrack == 0 ?
6791 AUDIO_FORMAT_INVALID : fastTrack->format();
6792 didModify = true;
6793 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006794 sq->end(didModify);
6795 if (didModify) {
6796 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006797#if 0
6798 if (kUseFastCapture == FastCapture_Dynamic) {
6799 mNormalSource = mPipeSource;
6800 }
6801#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006802 }
6803 }
6804
Glenn Kasten735f45f2014-08-18 15:51:59 -07006805 // now run the fast track destructor with thread mutex unlocked
6806 fastTrackToRemove.clear();
6807
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006808 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6809 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6810 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6811 // If destination is non-contiguous, first read past the nominal end of buffer, then
6812 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006813
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006814 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006815 ssize_t framesRead;
6816
6817 // If an NBAIO source is present, use it to read the normal capture's data
6818 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006819 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006820
6821 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6822 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6823 // we immediately retry the read() to get data and prevent another overflow.
6824 for (int retries = 0; retries <= 2; ++retries) {
6825 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6826 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6827 framesToRead);
6828 if (framesRead != OVERRUN) break;
6829 }
6830
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006831 const ssize_t availableToRead = mPipeSource->availableToRead();
6832 if (availableToRead >= 0) {
6833 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6834 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6835 "more frames to read than fifo size, %zd > %zu",
6836 availableToRead, mPipeFramesP2);
6837 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6838 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6839 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6840 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006841 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6842 }
6843 if (framesRead < 0) {
6844 status_t status = (status_t) framesRead;
6845 switch (status) {
6846 case OVERRUN:
6847 ALOGW("overrun on read from pipe");
6848 framesRead = 0;
6849 break;
6850 case NEGOTIATE:
6851 ALOGE("re-negotiation is needed");
6852 framesRead = -1; // Will cause an attempt to recover.
6853 break;
6854 default:
6855 ALOGE("unknown error %d on read from pipe", status);
6856 break;
6857 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006858 }
6859 // otherwise use the HAL / AudioStreamIn directly
6860 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006861 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006862 size_t bytesRead;
6863 status_t result = mInput->stream->read(
6864 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006865 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006866 if (result < 0) {
6867 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006868 } else {
6869 framesRead = bytesRead / mFrameSize;
6870 }
6871 }
6872
Andy Hung3f0c9022016-01-15 17:49:46 -08006873 // Update server timestamp with server stats
6874 // systemTime() is optional if the hardware supports timestamps.
6875 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6876 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6877
6878 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006879 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006880 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006881 if (mStandby) {
6882 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07006883 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
6884 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
6885
6886 mTimestampVerifier.add(position, time, mSampleRate);
6887
6888 // Correct timestamps
6889 if (isTimestampCorrectionEnabled()) {
6890 ALOGV("TS_BEFORE: %d %lld %lld",
6891 id(), (long long)time, (long long)position);
6892 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
6893 position = correctedTimestamp.mFrames;
6894 time = correctedTimestamp.mTimeNs;
6895 ALOGV("TS_AFTER: %d %lld %lld",
6896 id(), (long long)time, (long long)position);
6897 }
6898
Andy Hung3f0c9022016-01-15 17:49:46 -08006899 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6900 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6901 // Note: In general record buffers should tend to be empty in
6902 // a properly running pipeline.
6903 //
6904 // Also, it is not advantageous to call get_presentation_position during the read
6905 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006906 } else {
6907 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006908 }
6909 }
6910 // Use this to track timestamp information
6911 // ALOGD("%s", mTimestamp.toString().c_str());
6912
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006913 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006914 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006915 // Force input into standby so that it tries to recover at next read attempt
6916 inputStandBy();
6917 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006918 }
6919 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006920 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006921 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006922 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07006923 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006924
Andy Hung8946a282018-04-19 20:04:56 -07006925#ifdef TEE_SINK
6926 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6927#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006928 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006929 {
6930 size_t part1 = mRsmpInFramesP2 - rear;
6931 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006932 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006933 (framesRead - part1) * mFrameSize);
6934 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006935 }
6936 rear = mRsmpInRear += framesRead;
6937
6938 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006939
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006940 // loop over each active track
6941 for (size_t i = 0; i < size; i++) {
6942 activeTrack = activeTracks[i];
6943
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006944 // skip fast tracks, as those are handled directly by FastCapture
6945 if (activeTrack->isFastTrack()) {
6946 continue;
6947 }
6948
Andy Hung73c02e42015-03-29 01:13:58 -07006949 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006950 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6951
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006952 enum {
6953 OVERRUN_UNKNOWN,
6954 OVERRUN_TRUE,
6955 OVERRUN_FALSE
6956 } overrun = OVERRUN_UNKNOWN;
6957
6958 // loop over getNextBuffer to handle circular sink
6959 for (;;) {
6960
6961 activeTrack->mSink.frameCount = ~0;
6962 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6963 size_t framesOut = activeTrack->mSink.frameCount;
6964 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6965
Andy Hung73c02e42015-03-29 01:13:58 -07006966 // check available frames and handle overrun conditions
6967 // if the record track isn't draining fast enough.
6968 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006969 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006970 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6971 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006972 overrun = OVERRUN_TRUE;
6973 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006974 if (framesOut == 0 || framesIn == 0) {
6975 break;
6976 }
6977
Andy Hung6770c6f2015-04-07 13:43:36 -07006978 // Don't allow framesOut to be larger than what is possible with resampling
6979 // from framesIn.
6980 // This isn't strictly necessary but helps limit buffer resizing in
6981 // RecordBufferConverter. TODO: remove when no longer needed.
6982 framesOut = min(framesOut,
6983 destinationFramesPossible(
6984 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006985
6986 if (activeTrack->isDirect()) {
6987 // No RecordBufferConverter used for compressed formats. Pass
6988 // straight from RecordThread buffer to RecordTrack buffer.
6989 AudioBufferProvider::Buffer buffer;
6990 buffer.frameCount = framesOut;
6991 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6992 if (status == OK && buffer.frameCount != 0) {
6993 ALOGV_IF(buffer.frameCount != framesOut,
6994 "%s() read less than expected (%zu vs %zu)",
6995 __func__, buffer.frameCount, framesOut);
6996 framesOut = buffer.frameCount;
6997 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
6998 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6999 } else {
7000 framesOut = 0;
7001 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7002 __func__, status, buffer.frameCount);
7003 }
7004 } else {
7005 // process frames from the RecordThread buffer provider to the RecordTrack
7006 // buffer
7007 framesOut = activeTrack->mRecordBufferConverter->convert(
7008 activeTrack->mSink.raw,
7009 activeTrack->mResamplerBufferProvider,
7010 framesOut);
7011 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007012
7013 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7014 overrun = OVERRUN_FALSE;
7015 }
7016
7017 if (activeTrack->mFramesToDrop == 0) {
7018 if (framesOut > 0) {
7019 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007020 // Sanitize before releasing if the track has no access to the source data
7021 // An idle UID receives silence from non virtual devices until active
7022 if (activeTrack->isSilenced()) {
7023 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7024 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007025 activeTrack->releaseBuffer(&activeTrack->mSink);
7026 }
7027 } else {
7028 // FIXME could do a partial drop of framesOut
7029 if (activeTrack->mFramesToDrop > 0) {
7030 activeTrack->mFramesToDrop -= framesOut;
7031 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007032 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007033 }
7034 } else {
7035 activeTrack->mFramesToDrop += framesOut;
7036 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7037 activeTrack->mSyncStartEvent->isCancelled()) {
7038 ALOGW("Synced record %s, session %d, trigger session %d",
7039 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7040 activeTrack->sessionId(),
7041 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007042 activeTrack->mSyncStartEvent->triggerSession() :
7043 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007044 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007045 }
7046 }
7047 }
7048
7049 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007050 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007051 }
7052 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007053
7054 switch (overrun) {
7055 case OVERRUN_TRUE:
7056 // client isn't retrieving buffers fast enough
7057 if (!activeTrack->setOverflow()) {
7058 nsecs_t now = systemTime();
7059 // FIXME should lastWarning per track?
7060 if ((now - lastWarning) > kWarningThrottleNs) {
7061 ALOGW("RecordThread: buffer overflow");
7062 lastWarning = now;
7063 }
7064 }
7065 break;
7066 case OVERRUN_FALSE:
7067 activeTrack->clearOverflow();
7068 break;
7069 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007070 break;
7071 }
7072
Andy Hung3f0c9022016-01-15 17:49:46 -08007073 // update frame information and push timestamp out
7074 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007075 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007076 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7077 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007078 }
7079
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007080unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007081 // enable changes in effect chain
7082 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007083 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007084 }
7085
Glenn Kasten93e471f2013-08-19 08:40:07 -07007086 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007087
7088 {
7089 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007090 for (size_t i = 0; i < mTracks.size(); i++) {
7091 sp<RecordTrack> track = mTracks[i];
7092 track->invalidate();
7093 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007094 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007095 mStartStopCond.broadcast();
7096 }
7097
7098 releaseWakeLock();
7099
7100 ALOGV("RecordThread %p exiting", this);
7101 return false;
7102}
7103
Glenn Kasten93e471f2013-08-19 08:40:07 -07007104void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007105{
7106 if (!mStandby) {
7107 inputStandBy();
7108 mStandby = true;
7109 }
7110}
7111
7112void AudioFlinger::RecordThread::inputStandBy()
7113{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007114 // Idle the fast capture if it's currently running
7115 if (mFastCapture != 0) {
7116 FastCaptureStateQueue *sq = mFastCapture->sq();
7117 FastCaptureState *state = sq->begin();
7118 if (!(state->mCommand & FastCaptureState::IDLE)) {
7119 state->mCommand = FastCaptureState::COLD_IDLE;
7120 state->mColdFutexAddr = &mFastCaptureFutex;
7121 state->mColdGen++;
7122 mFastCaptureFutex = 0;
7123 sq->end();
7124 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7125 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7126#if 0
7127 if (kUseFastCapture == FastCapture_Dynamic) {
7128 // FIXME
7129 }
7130#endif
7131#ifdef AUDIO_WATCHDOG
7132 // FIXME
7133#endif
7134 } else {
7135 sq->end(false /*didModify*/);
7136 }
7137 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007138 status_t result = mInput->stream->standby();
7139 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007140
7141 // If going into standby, flush the pipe source.
7142 if (mPipeSource.get() != nullptr) {
7143 const ssize_t flushed = mPipeSource->flush();
7144 if (flushed > 0) {
7145 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7146 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7147 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7148 }
7149 }
Eric Laurent81784c32012-11-19 14:55:58 -08007150}
7151
Glenn Kasten05997e22014-03-13 15:08:33 -07007152// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007153sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007154 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007155 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007156 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007157 audio_format_t format,
7158 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007159 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007160 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007161 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007162 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007163 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007164 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007165 status_t *status,
7166 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007167{
Glenn Kasten74935e42013-12-19 08:56:45 -08007168 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007169 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007170 sp<RecordTrack> track;
7171 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007172 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007173 audio_input_flags_t requestedFlags = *flags;
7174 uint32_t sampleRate;
7175
7176 lStatus = initCheck();
7177 if (lStatus != NO_ERROR) {
7178 ALOGE("createRecordTrack_l() audio driver not initialized");
7179 goto Exit;
7180 }
7181
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007182 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7183 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7184 lStatus = BAD_VALUE;
7185 goto Exit;
7186 }
7187
Eric Laurentf14db3c2017-12-08 14:20:36 -08007188 if (*pSampleRate == 0) {
7189 *pSampleRate = mSampleRate;
7190 }
7191 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007192
7193 // special case for FAST flag considered OK if fast capture is present
7194 if (hasFastCapture()) {
7195 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7196 }
7197
Eric Laurentf14db3c2017-12-08 14:20:36 -08007198 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007199 if ((*flags & inputFlags) != *flags) {
7200 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7201 " input flags (%08x)",
7202 *flags, inputFlags);
7203 *flags = (audio_input_flags_t)(*flags & inputFlags);
7204 }
Eric Laurent81784c32012-11-19 14:55:58 -08007205
Glenn Kasten90e58b12013-07-31 16:16:02 -07007206 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007207 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007208 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007209 // we formerly checked for a callback handler (non-0 tid),
7210 // but that is no longer required for TRANSFER_OBTAIN mode
7211 //
Glenn Kasten74105912014-07-03 12:28:53 -07007212 // frame count is not specified, or is exactly the pipe depth
7213 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007214 // PCM data
7215 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007216 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007217 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007218 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007219 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007220 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007221 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007222 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007223 hasFastCapture() &&
7224 // there are sufficient fast track slots available
7225 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007226 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007227 // check compatibility with audio effects.
7228 Mutex::Autolock _l(mLock);
7229 // Do not accept FAST flag if the session has software effects
7230 sp<EffectChain> chain = getEffectChain_l(sessionId);
7231 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007232 audio_input_flags_t old = *flags;
7233 chain->checkInputFlagCompatibility(flags);
7234 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007235 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7236 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007237 }
7238 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007239 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007240 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7241 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007242 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007243 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7244 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007245 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007246 this, frameCount, mFrameCount, mPipeFramesP2,
7247 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007248 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007249 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007250 }
7251 }
7252
Eric Laurentf14db3c2017-12-08 14:20:36 -08007253 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7254 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7255 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7256 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7257 lStatus = BAD_TYPE;
7258 goto Exit;
7259 }
7260
Glenn Kasten74105912014-07-03 12:28:53 -07007261 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007262 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007263 // fast track: frame count is exactly the pipe depth
7264 frameCount = mPipeFramesP2;
7265 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007266 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007267 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007268 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7269 // or 20 ms if there is a fast capture
7270 // TODO This could be a roundupRatio inline, and const
7271 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7272 * sampleRate + mSampleRate - 1) / mSampleRate;
7273 // minimum number of notification periods is at least kMinNotifications,
7274 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7275 static const size_t kMinNotifications = 3;
7276 static const uint32_t kMinMs = 30;
7277 // TODO This could be a roundupRatio inline
7278 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7279 // TODO This could be a roundupRatio inline
7280 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7281 maxNotificationFrames;
7282 const size_t minFrameCount = maxNotificationFrames *
7283 max(kMinNotifications, minNotificationsByMs);
7284 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007285 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7286 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007287 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007288 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007289 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007290 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007291
7292 { // scope for mLock
7293 Mutex::Autolock _l(mLock);
7294
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007295 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007296 format, channelMask, frameCount,
7297 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007298 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007299
Glenn Kasten03003332013-08-06 15:40:54 -07007300 lStatus = track->initCheck();
7301 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007302 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007303 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007304 goto Exit;
7305 }
7306 mTracks.add(track);
7307
Eric Laurent05067782016-06-01 18:27:28 -07007308 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007309 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7310 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7311 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007312 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007313 }
Eric Laurent81784c32012-11-19 14:55:58 -08007314 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007315
Eric Laurent81784c32012-11-19 14:55:58 -08007316 lStatus = NO_ERROR;
7317
7318Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007319 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007320 return track;
7321}
7322
7323status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7324 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007325 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007326{
7327 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7328 sp<ThreadBase> strongMe = this;
7329 status_t status = NO_ERROR;
7330
7331 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007332 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007333 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007334 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007335 triggerSession,
7336 recordTrack->sessionId(),
7337 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007338 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007339 // Sync event can be cancelled by the trigger session if the track is not in a
7340 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007341 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007342 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007343 } else {
7344 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007345 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007346 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007347 }
7348 }
7349
7350 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007351 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007352 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007353 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7354 if (recordTrack->mState == TrackBase::PAUSING) {
7355 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007356 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007357 } else {
7358 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007359 }
7360 return status;
7361 }
7362
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007363 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7364 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7365 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007366 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007367 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007368 status_t status = NO_ERROR;
7369 if (recordTrack->isExternalTrack()) {
7370 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007371 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007372 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007373 mLock.lock();
7374 // FIXME should verify that recordTrack is still in mActiveTracks
7375 if (status != NO_ERROR) {
7376 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007377 recordTrack->clearSyncStartEvent();
7378 ALOGV("RecordThread::start error %d", status);
7379 return status;
7380 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007381 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007382 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007383 // Catch up with current buffer indices if thread is already running.
7384 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7385 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7386 // see previously buffered data before it called start(), but with greater risk of overrun.
7387
Andy Hung73c02e42015-03-29 01:13:58 -07007388 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007389 if (!recordTrack->isDirect()) {
7390 // clear any converter state as new data will be discontinuous
7391 recordTrack->mRecordBufferConverter->reset();
7392 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007393 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007394 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007395 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007396 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007397 ALOGV("Record failed to start");
7398 status = BAD_VALUE;
7399 goto startError;
7400 }
Eric Laurent81784c32012-11-19 14:55:58 -08007401 return status;
7402 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007403
Eric Laurent81784c32012-11-19 14:55:58 -08007404startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007405 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007406 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007407 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007408 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007409 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007410 return status;
7411}
7412
Eric Laurent81784c32012-11-19 14:55:58 -08007413void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7414{
7415 sp<SyncEvent> strongEvent = event.promote();
7416
7417 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007418 sp<RefBase> ptr = strongEvent->cookie().promote();
7419 if (ptr != 0) {
7420 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7421 recordTrack->handleSyncStartEvent(strongEvent);
7422 }
Eric Laurent81784c32012-11-19 14:55:58 -08007423 }
7424}
7425
Glenn Kastena8356f62013-07-25 14:37:52 -07007426bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007427 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007428 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007429 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007430 return false;
7431 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007432 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007433 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007434 // signal thread to stop
7435 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007436 // do not wait for mStartStopCond if exiting
7437 if (exitPending()) {
7438 return true;
7439 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007440 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007441 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007442 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007443 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007444 ALOGV("Record stopped OK");
7445 return true;
7446 }
7447 return false;
7448}
7449
Glenn Kasten0f11b512014-01-31 16:18:54 -08007450bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007451{
7452 return false;
7453}
7454
Glenn Kasten0f11b512014-01-31 16:18:54 -08007455status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007456{
7457#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7458 if (!isValidSyncEvent(event)) {
7459 return BAD_VALUE;
7460 }
7461
Glenn Kastend848eb42016-03-08 13:42:11 -08007462 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007463 status_t ret = NAME_NOT_FOUND;
7464
7465 Mutex::Autolock _l(mLock);
7466
7467 for (size_t i = 0; i < mTracks.size(); i++) {
7468 sp<RecordTrack> track = mTracks[i];
7469 if (eventSession == track->sessionId()) {
7470 (void) track->setSyncEvent(event);
7471 ret = NO_ERROR;
7472 }
7473 }
7474 return ret;
7475#else
7476 return BAD_VALUE;
7477#endif
7478}
7479
jiabin653cc0a2018-01-17 17:54:10 -08007480status_t AudioFlinger::RecordThread::getActiveMicrophones(
7481 std::vector<media::MicrophoneInfo>* activeMicrophones)
7482{
7483 ALOGV("RecordThread::getActiveMicrophones");
7484 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007485 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7486 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007487}
7488
Kevin Rocard069c2712018-03-29 19:09:14 -07007489void AudioFlinger::RecordThread::updateMetadata_l()
7490{
7491 if (mInput == nullptr || mInput->stream == nullptr ||
7492 !mActiveTracks.readAndClearHasChanged()) {
7493 return;
7494 }
7495 StreamInHalInterface::SinkMetadata metadata;
7496 for (const sp<RecordTrack> &track : mActiveTracks) {
7497 // No track is invalid as this is called after prepareTrack_l in the same critical section
7498 metadata.tracks.push_back({
7499 .source = track->attributes().source,
7500 .gain = 1, // capture tracks do not have volumes
7501 });
7502 }
7503 mInput->stream->updateSinkMetadata(metadata);
7504}
7505
Eric Laurent81784c32012-11-19 14:55:58 -08007506// destroyTrack_l() must be called with ThreadBase::mLock held
7507void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7508{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007509 track->terminate();
7510 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007511 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007512 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007513 removeTrack_l(track);
7514 }
7515}
7516
7517void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7518{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007519 String8 result;
7520 track->appendDump(result, false /* active */);
7521 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7522
Eric Laurent81784c32012-11-19 14:55:58 -08007523 mTracks.remove(track);
7524 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007525 if (track->isFastTrack()) {
7526 ALOG_ASSERT(!mFastTrackAvail);
7527 mFastTrackAvail = true;
7528 }
Eric Laurent81784c32012-11-19 14:55:58 -08007529}
7530
7531void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7532{
7533 dumpInternals(fd, args);
7534 dumpTracks(fd, args);
7535 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007536 dprintf(fd, " Local log:\n");
7537 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007538}
7539
7540void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7541{
Glenn Kasten44182c22015-03-05 17:12:23 -08007542 dumpBase(fd, args);
7543
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007544 AudioStreamIn *input = mInput;
7545 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7546 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7547 input, flags, inputFlagsToString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007548 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007549 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007550 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007551 }
Andy Hungbfa64962017-06-12 14:43:19 -07007552
7553 if (input != nullptr) {
7554 dprintf(fd, " Hal stream dump:\n");
7555 (void)input->stream->dump(fd);
7556 }
7557
Andy Hung7f39f562018-08-08 17:30:20 -07007558 const double latencyMs = audio_is_linear_pcm(mFormat)
7559 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
Andy Hung20bd30b2018-06-01 15:39:35 -07007560 if (latencyMs != 0.) {
7561 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7562 } else {
7563 dprintf(fd, " NormalRecord latency ms: unavail\n");
7564 }
7565
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007566 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007567 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007568
Glenn Kasten2f90c512015-12-02 11:40:09 -08007569 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7570 // while we are dumping it. It may be inconsistent, but it won't mutate!
7571 // This is a large object so we place it on the heap.
7572 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07007573 std::unique_ptr<FastCaptureDumpState> copy(new FastCaptureDumpState(mFastCaptureDumpState));
Glenn Kasten2f90c512015-12-02 11:40:09 -08007574 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007575}
7576
Glenn Kasten0f11b512014-01-31 16:18:54 -08007577void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007578{
Eric Laurent81784c32012-11-19 14:55:58 -08007579 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007580 size_t numtracks = mTracks.size();
7581 size_t numactive = mActiveTracks.size();
7582 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007583 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007584 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007585 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007586 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007587 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007588 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007589 for (size_t i = 0; i < numtracks ; ++i) {
7590 sp<RecordTrack> track = mTracks[i];
7591 if (track != 0) {
7592 bool active = mActiveTracks.indexOf(track) >= 0;
7593 if (active) {
7594 numactiveseen++;
7595 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007596 result.append(prefix);
7597 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007598 }
Eric Laurent81784c32012-11-19 14:55:58 -08007599 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007600 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007601 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007602 }
7603
Marco Nelissenb2208842014-02-07 14:00:50 -08007604 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007605 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007606 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007607 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007608 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007609 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007610 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007611 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007612 result.append(prefix);
7613 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007614 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007615 }
Eric Laurent81784c32012-11-19 14:55:58 -08007616
7617 }
7618 write(fd, result.string(), result.size());
7619}
7620
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007621void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7622{
7623 Mutex::Autolock _l(mLock);
7624 for (size_t i = 0; i < mTracks.size() ; i++) {
7625 sp<RecordTrack> track = mTracks[i];
7626 if (track != 0 && track->uid() == uid) {
7627 track->setSilenced(silenced);
7628 }
7629 }
7630}
Andy Hung73c02e42015-03-29 01:13:58 -07007631
7632void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7633{
7634 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7635 RecordThread *recordThread = (RecordThread *) threadBase.get();
7636 mRsmpInFront = recordThread->mRsmpInRear;
7637 mRsmpInUnrel = 0;
7638}
7639
7640void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7641 size_t *framesAvailable, bool *hasOverrun)
7642{
7643 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7644 RecordThread *recordThread = (RecordThread *) threadBase.get();
7645 const int32_t rear = recordThread->mRsmpInRear;
7646 const int32_t front = mRsmpInFront;
7647 const ssize_t filled = rear - front;
7648
7649 size_t framesIn;
7650 bool overrun = false;
7651 if (filled < 0) {
7652 // should not happen, but treat like a massive overrun and re-sync
7653 framesIn = 0;
7654 mRsmpInFront = rear;
7655 overrun = true;
7656 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7657 framesIn = (size_t) filled;
7658 } else {
7659 // client is not keeping up with server, but give it latest data
7660 framesIn = recordThread->mRsmpInFrames;
7661 mRsmpInFront = /* front = */ rear - framesIn;
7662 overrun = true;
7663 }
7664 if (framesAvailable != NULL) {
7665 *framesAvailable = framesIn;
7666 }
7667 if (hasOverrun != NULL) {
7668 *hasOverrun = overrun;
7669 }
7670}
7671
Eric Laurent81784c32012-11-19 14:55:58 -08007672// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007673status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007674 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007675{
Andy Hung73c02e42015-03-29 01:13:58 -07007676 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007677 if (threadBase == 0) {
7678 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007679 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007680 return NOT_ENOUGH_DATA;
7681 }
7682 RecordThread *recordThread = (RecordThread *) threadBase.get();
7683 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007684 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007685 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007686 // FIXME should not be P2 (don't want to increase latency)
7687 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007688 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007689 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007690 front &= recordThread->mRsmpInFramesP2 - 1;
7691 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007692 if (part1 > (size_t) filled) {
7693 part1 = filled;
7694 }
7695 size_t ask = buffer->frameCount;
7696 ALOG_ASSERT(ask > 0);
7697 if (part1 > ask) {
7698 part1 = ask;
7699 }
7700 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007701 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007702 buffer->raw = NULL;
7703 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007704 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007705 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007706 }
7707
Andy Hung57446612015-04-19 23:56:46 -07007708 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007709 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007710 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007711 return NO_ERROR;
7712}
7713
7714// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007715void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7716 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007717{
Glenn Kasten85948432013-08-19 12:09:05 -07007718 size_t stepCount = buffer->frameCount;
7719 if (stepCount == 0) {
7720 return;
7721 }
Andy Hung73c02e42015-03-29 01:13:58 -07007722 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7723 mRsmpInUnrel -= stepCount;
7724 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007725 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007726 buffer->frameCount = 0;
7727}
7728
Eric Laurentd8365c52017-07-16 15:27:05 -07007729void AudioFlinger::RecordThread::checkBtNrec()
7730{
7731 Mutex::Autolock _l(mLock);
7732 checkBtNrec_l();
7733}
7734
7735void AudioFlinger::RecordThread::checkBtNrec_l()
7736{
7737 // disable AEC and NS if the device is a BT SCO headset supporting those
7738 // pre processings
7739 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7740 mAudioFlinger->btNrecIsOff();
7741 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7742 for (size_t i = 0; i < mEffectChains.size(); i++) {
7743 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7744 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7745 }
7746 }
7747}
7748
Andy Hung97a893e2015-03-29 01:03:07 -07007749
Eric Laurent10351942014-05-08 18:49:52 -07007750bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7751 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007752{
7753 bool reconfig = false;
7754
Eric Laurent10351942014-05-08 18:49:52 -07007755 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007756
Eric Laurent10351942014-05-08 18:49:52 -07007757 audio_format_t reqFormat = mFormat;
7758 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007759 // 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 -07007760 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7761
7762 AudioParameter param = AudioParameter(keyValuePair);
7763 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007764
7765 // scope for AutoPark extends to end of method
7766 AutoPark<FastCapture> park(mFastCapture);
7767
Eric Laurent10351942014-05-08 18:49:52 -07007768 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7769 // channel count change can be requested. Do we mandate the first client defines the
7770 // HAL sampling rate and channel count or do we allow changes on the fly?
7771 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7772 samplingRate = value;
7773 reconfig = true;
7774 }
7775 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007776 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007777 status = BAD_VALUE;
7778 } else {
7779 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007780 reconfig = true;
7781 }
Eric Laurent10351942014-05-08 18:49:52 -07007782 }
7783 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7784 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007785 if (!audio_is_input_channel(mask) ||
7786 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007787 status = BAD_VALUE;
7788 } else {
7789 channelMask = mask;
7790 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007791 }
Eric Laurent10351942014-05-08 18:49:52 -07007792 }
7793 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7794 // do not accept frame count changes if tracks are open as the track buffer
7795 // size depends on frame count and correct behavior would not be guaranteed
7796 // if frame count is changed after track creation
7797 if (mActiveTracks.size() > 0) {
7798 status = INVALID_OPERATION;
7799 } else {
7800 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007801 }
Eric Laurent10351942014-05-08 18:49:52 -07007802 }
7803 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7804 // forward device change to effects that have requested to be
7805 // aware of attached audio device.
7806 for (size_t i = 0; i < mEffectChains.size(); i++) {
7807 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007808 }
Eric Laurent81784c32012-11-19 14:55:58 -08007809
Eric Laurent10351942014-05-08 18:49:52 -07007810 // store input device and output device but do not forward output device to audio HAL.
7811 // Note that status is ignored by the caller for output device
7812 // (see AudioFlinger::setParameters()
7813 if (audio_is_output_devices(value)) {
7814 mOutDevice = value;
7815 status = BAD_VALUE;
7816 } else {
7817 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007818 if (value != AUDIO_DEVICE_NONE) {
7819 mPrevInDevice = value;
7820 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007821 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007822 }
Eric Laurent10351942014-05-08 18:49:52 -07007823 }
7824 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7825 mAudioSource != (audio_source_t)value) {
7826 // forward device change to effects that have requested to be
7827 // aware of attached audio device.
7828 for (size_t i = 0; i < mEffectChains.size(); i++) {
7829 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007830 }
Eric Laurent10351942014-05-08 18:49:52 -07007831 mAudioSource = (audio_source_t)value;
7832 }
Glenn Kastene198c362013-08-13 09:13:36 -07007833
Eric Laurent10351942014-05-08 18:49:52 -07007834 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007835 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007836 if (status == INVALID_OPERATION) {
7837 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007838 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007839 }
7840 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007841 if (status == BAD_VALUE) {
7842 uint32_t sRate;
7843 audio_channel_mask_t channelMask;
7844 audio_format_t format;
7845 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7846 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7847 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7848 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7849 status = NO_ERROR;
7850 }
Eric Laurent81784c32012-11-19 14:55:58 -08007851 }
Eric Laurent10351942014-05-08 18:49:52 -07007852 if (status == NO_ERROR) {
7853 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007854 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007855 }
7856 }
Eric Laurent81784c32012-11-19 14:55:58 -08007857 }
Eric Laurent10351942014-05-08 18:49:52 -07007858
Eric Laurent81784c32012-11-19 14:55:58 -08007859 return reconfig;
7860}
7861
7862String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7863{
Eric Laurent81784c32012-11-19 14:55:58 -08007864 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007865 if (initCheck() == NO_ERROR) {
7866 String8 out_s8;
7867 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7868 return out_s8;
7869 }
Eric Laurent81784c32012-11-19 14:55:58 -08007870 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007871 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007872}
7873
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007874void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007875 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7876
7877 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007878
7879 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007880 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007881 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007882 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007883 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007884 desc->mChannelMask = mChannelMask;
7885 desc->mSamplingRate = mSampleRate;
7886 desc->mFormat = mFormat;
7887 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007888 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007889 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007890 break;
7891
Eric Laurent73e26b62015-04-27 16:55:58 -07007892 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007893 default:
7894 break;
7895 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007896 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007897}
7898
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007899void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007900{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007901 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7902 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07007903 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007904 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7905 if (audio_is_linear_pcm(mFormat)) {
7906 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
7907 mChannelCount, FCC_8);
7908 } else {
7909 // Can have more that FCC_8 channels in encoded streams.
7910 ALOGI("HAL format %#x is not linear pcm", mFormat);
7911 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007912 result = mInput->stream->getFrameSize(&mFrameSize);
7913 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7914 result = mInput->stream->getBufferSize(&mBufferSize);
7915 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007916 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007917 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7918 "mBufferSize=%lld, mFrameCount=%lld",
7919 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7920 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007921 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007922 // 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 -07007923 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007924 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007925 // A larger value should allow more old data to be read after a track calls start(),
7926 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007927 //
7928 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007929 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007930 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007931 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007932 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007933
7934 // TODO optimize audio capture buffer sizes ...
7935 // Here we calculate the size of the sliding buffer used as a source
7936 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7937 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7938 // be better to have it derived from the pipe depth in the long term.
7939 // The current value is higher than necessary. However it should not add to latency.
7940
Glenn Kasten85948432013-08-19 12:09:05 -07007941 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007942 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7943 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007944 // if posix_memalign fails, will segv here.
7945 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007946
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007947 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7948 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007949}
7950
Glenn Kasten5f972c02014-01-13 09:59:31 -08007951uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007952{
7953 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007954 uint32_t result;
7955 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7956 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007957 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007958 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007959}
7960
Eric Laurent4c415062016-06-17 16:14:16 -07007961// hasAudioSession_l() must be called with ThreadBase::mLock held
7962uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007963{
Eric Laurent81784c32012-11-19 14:55:58 -08007964 uint32_t result = 0;
7965 if (getEffectChain_l(sessionId) != 0) {
7966 result = EFFECT_SESSION;
7967 }
7968
7969 for (size_t i = 0; i < mTracks.size(); ++i) {
7970 if (sessionId == mTracks[i]->sessionId()) {
7971 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007972 if (mTracks[i]->isFastTrack()) {
7973 result |= FAST_SESSION;
7974 }
Eric Laurent81784c32012-11-19 14:55:58 -08007975 break;
7976 }
7977 }
7978
7979 return result;
7980}
7981
Glenn Kastend848eb42016-03-08 13:42:11 -08007982KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007983{
Glenn Kastend848eb42016-03-08 13:42:11 -08007984 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007985 Mutex::Autolock _l(mLock);
7986 for (size_t j = 0; j < mTracks.size(); ++j) {
7987 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007988 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007989 if (ids.indexOfKey(sessionId) < 0) {
7990 ids.add(sessionId, true);
7991 }
7992 }
7993 return ids;
7994}
7995
7996AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7997{
7998 Mutex::Autolock _l(mLock);
7999 AudioStreamIn *input = mInput;
8000 mInput = NULL;
8001 return input;
8002}
8003
8004// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008005sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008006{
8007 if (mInput == NULL) {
8008 return NULL;
8009 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008010 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008011}
8012
8013status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8014{
8015 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008016 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008017 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008018 return INVALID_OPERATION;
8019 }
8020 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008021 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008022 chain->setInBuffer(NULL);
8023 chain->setOutBuffer(NULL);
8024
8025 checkSuspendOnAddEffectChain_l(chain);
8026
Eric Laurent1b928682014-10-02 19:41:47 -07008027 // make sure enabled pre processing effects state is communicated to the HAL as we
8028 // just moved them to a new input stream.
8029 chain->syncHalEffectsState();
8030
Eric Laurent81784c32012-11-19 14:55:58 -08008031 mEffectChains.add(chain);
8032
8033 return NO_ERROR;
8034}
8035
8036size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8037{
8038 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8039 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008040 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008041 chain.get(), mEffectChains.size(), this);
8042 if (mEffectChains.size() == 1) {
8043 mEffectChains.removeAt(0);
8044 }
8045 return 0;
8046}
8047
Eric Laurent1c333e22014-05-20 10:48:17 -07008048status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8049 audio_patch_handle_t *handle)
8050{
8051 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008052
8053 // store new device and send to effects
8054 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07008055 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008056 for (size_t i = 0; i < mEffectChains.size(); i++) {
8057 mEffectChains[i]->setDevice_l(mInDevice);
8058 }
8059
Eric Laurentd8365c52017-07-16 15:27:05 -07008060 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008061
8062 // store new source and send to effects
8063 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8064 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008065 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008066 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008067 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008068 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008069
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008070 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008071 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8072 status = hwDevice->createAudioPatch(patch->num_sources,
8073 patch->sources,
8074 patch->num_sinks,
8075 patch->sinks,
8076 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008077 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008078 char *address;
8079 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8080 address = audio_device_address_to_parameter(
8081 patch->sources[0].ext.device.type,
8082 patch->sources[0].ext.device.address);
8083 } else {
8084 address = (char *)calloc(1, 1);
8085 }
8086 AudioParameter param = AudioParameter(String8(address));
8087 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008088 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008089 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008090 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008091 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008092 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008093 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008094 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008095
Eric Laurente8726fe2015-06-26 09:39:24 -07008096 if (mInDevice != mPrevInDevice) {
8097 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8098 mPrevInDevice = mInDevice;
8099 }
Eric Laurent296fb132015-05-01 11:38:42 -07008100
Eric Laurent1c333e22014-05-20 10:48:17 -07008101 return status;
8102}
8103
8104status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8105{
8106 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008107
8108 mInDevice = AUDIO_DEVICE_NONE;
8109
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008110 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008111 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8112 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008113 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008114 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008115 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008116 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008117 }
8118 return status;
8119}
8120
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008121void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008122{
8123 Mutex::Autolock _l(mLock);
8124 mTracks.add(record);
8125}
8126
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008127void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008128{
8129 Mutex::Autolock _l(mLock);
8130 destroyTrack_l(record);
8131}
8132
Mikhail Naganovdc769682018-05-04 15:34:08 -07008133void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008134{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008135 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008136 config->role = AUDIO_PORT_ROLE_SINK;
8137 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8138 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008139 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8140 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8141 config->flags.input = mInput->flags;
8142 }
Eric Laurent83b88082014-06-20 18:31:16 -07008143}
Eric Laurent1c333e22014-05-20 10:48:17 -07008144
Eric Laurent6acd1d42017-01-04 14:23:29 -08008145// ----------------------------------------------------------------------------
8146// Mmap
8147// ----------------------------------------------------------------------------
8148
8149AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8150 : mThread(thread)
8151{
Phil Burk9fabbf82017-08-03 12:02:00 -07008152 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008153}
8154
8155AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8156{
Phil Burk9fabbf82017-08-03 12:02:00 -07008157 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008158}
8159
8160status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8161 struct audio_mmap_buffer_info *info)
8162{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008163 return mThread->createMmapBuffer(minSizeFrames, info);
8164}
8165
8166status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8167{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008168 return mThread->getMmapPosition(position);
8169}
8170
Eric Laurenta54f1282017-07-01 19:39:32 -07008171status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008172 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008173
8174{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008175 return mThread->start(client, handle);
8176}
8177
8178status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8179{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008180 return mThread->stop(handle);
8181}
8182
Eric Laurent18b57012017-02-13 16:23:52 -08008183status_t AudioFlinger::MmapThreadHandle::standby()
8184{
Eric Laurent18b57012017-02-13 16:23:52 -08008185 return mThread->standby();
8186}
8187
Eric Laurent6acd1d42017-01-04 14:23:29 -08008188
8189AudioFlinger::MmapThread::MmapThread(
8190 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8191 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8192 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8193 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008194 mSessionId(AUDIO_SESSION_NONE),
8195 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008196 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008197 mActiveTracks(&this->mLocalLog),
8198 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8199 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008200{
Eric Laurent18b57012017-02-13 16:23:52 -08008201 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008202 readHalParameters_l();
8203}
8204
8205AudioFlinger::MmapThread::~MmapThread()
8206{
Eric Laurent18b57012017-02-13 16:23:52 -08008207 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008208}
8209
8210void AudioFlinger::MmapThread::onFirstRef()
8211{
8212 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8213}
8214
8215void AudioFlinger::MmapThread::disconnect()
8216{
Eric Laurent331679c2018-04-16 17:03:16 -07008217 ActiveTracks<MmapTrack> activeTracks;
8218 {
8219 Mutex::Autolock _l(mLock);
8220 for (const sp<MmapTrack> &t : mActiveTracks) {
8221 activeTracks.add(t);
8222 }
8223 }
8224 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008225 stop(t->portId());
8226 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008227 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008228 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008229 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008230 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008231 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008232 }
8233}
8234
8235
8236void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8237 audio_stream_type_t streamType __unused,
8238 audio_session_t sessionId,
8239 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008240 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008241 audio_port_handle_t portId)
8242{
8243 mAttr = *attr;
8244 mSessionId = sessionId;
8245 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008246 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008247 mPortId = portId;
8248}
8249
8250status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8251 struct audio_mmap_buffer_info *info)
8252{
8253 if (mHalStream == 0) {
8254 return NO_INIT;
8255 }
Eric Laurent18b57012017-02-13 16:23:52 -08008256 mStandby = true;
8257 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008258 return mHalStream->createMmapBuffer(minSizeFrames, info);
8259}
8260
8261status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8262{
8263 if (mHalStream == 0) {
8264 return NO_INIT;
8265 }
8266 return mHalStream->getMmapPosition(position);
8267}
8268
Eric Laurent331679c2018-04-16 17:03:16 -07008269status_t AudioFlinger::MmapThread::exitStandby()
8270{
8271 status_t ret = mHalStream->start();
8272 if (ret != NO_ERROR) {
8273 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8274 return ret;
8275 }
8276 mStandby = false;
8277 return NO_ERROR;
8278}
8279
Eric Laurenta54f1282017-07-01 19:39:32 -07008280status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008281 audio_port_handle_t *handle)
8282{
Eric Laurenta54f1282017-07-01 19:39:32 -07008283 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8284 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008285 if (mHalStream == 0) {
8286 return NO_INIT;
8287 }
8288
8289 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008290
Eric Laurenta54f1282017-07-01 19:39:32 -07008291 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008292 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008293 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008294 }
8295
8296 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8297
8298 audio_io_handle_t io = mId;
8299 if (isOutput()) {
8300 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8301 config.sample_rate = mSampleRate;
8302 config.channel_mask = mChannelMask;
8303 config.format = mFormat;
8304 audio_stream_type_t stream = streamType();
8305 audio_output_flags_t flags =
8306 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008307 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008308 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8309 mSessionId,
8310 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008311 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008312 client.clientUid,
8313 &config,
8314 flags,
8315 &deviceId,
8316 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008317 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008318 audio_config_base_t config;
8319 config.sample_rate = mSampleRate;
8320 config.channel_mask = mChannelMask;
8321 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008322 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008323 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8324 mSessionId,
8325 client.clientPid,
8326 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008327 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008328 &config,
8329 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8330 &deviceId,
8331 &portId);
8332 }
8333 // APM should not chose a different input or output stream for the same set of attributes
8334 // and audo configuration
8335 if (ret != NO_ERROR || io != mId) {
8336 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8337 __FUNCTION__, ret, io, mId);
8338 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008339 }
8340
Eric Laurent331679c2018-04-16 17:03:16 -07008341 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008342 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008343 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008344 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008345 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008346 }
8347
Eric Laurent331679c2018-04-16 17:03:16 -07008348 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008349 // abort if start is rejected by audio policy manager
8350 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008351 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008352 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008353 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008354 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008355 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008356 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008357 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008358 }
Eric Laurent331679c2018-04-16 17:03:16 -07008359 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008360 } else {
8361 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008362 }
8363 return PERMISSION_DENIED;
8364 }
8365
Eric Laurent67f97292018-04-20 18:05:41 -07008366 if (isOutput()) {
8367 // force volume update when a new track is added
8368 mHalVolFloat = -1.0f;
8369 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008370 for (const sp<MmapTrack> &track : mActiveTracks) {
8371 if (track->isSilenced_l() && track->uid() != client.clientUid)
8372 track->invalidate();
8373 }
8374 }
8375
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008376 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8377 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008378 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008379
Eric Laurent331679c2018-04-16 17:03:16 -07008380 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008381 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008382 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008383 if (chain != 0) {
8384 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8385 chain->incTrackCnt();
8386 chain->incActiveTrackCnt();
8387 }
8388
8389 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008390 broadcast_l();
8391
Eric Laurenta54f1282017-07-01 19:39:32 -07008392 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008393
8394 return NO_ERROR;
8395}
8396
8397status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8398{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008399 ALOGV("%s handle %d", __FUNCTION__, handle);
8400
8401 if (mHalStream == 0) {
8402 return NO_INIT;
8403 }
8404
Eric Laurenta54f1282017-07-01 19:39:32 -07008405 if (handle == mPortId) {
8406 mHalStream->stop();
8407 return NO_ERROR;
8408 }
8409
Eric Laurent331679c2018-04-16 17:03:16 -07008410 Mutex::Autolock _l(mLock);
8411
Eric Laurent6acd1d42017-01-04 14:23:29 -08008412 sp<MmapTrack> track;
8413 for (const sp<MmapTrack> &t : mActiveTracks) {
8414 if (handle == t->portId()) {
8415 track = t;
8416 break;
8417 }
8418 }
8419 if (track == 0) {
8420 return BAD_VALUE;
8421 }
8422
8423 mActiveTracks.remove(track);
8424
Eric Laurent331679c2018-04-16 17:03:16 -07008425 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008426 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008427 AudioSystem::stopOutput(track->portId());
8428 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008429 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008430 AudioSystem::stopInput(track->portId());
8431 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008432 }
Eric Laurent331679c2018-04-16 17:03:16 -07008433 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008434
8435 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8436 if (chain != 0) {
8437 chain->decActiveTrackCnt();
8438 chain->decTrackCnt();
8439 }
8440
8441 broadcast_l();
8442
Eric Laurent6acd1d42017-01-04 14:23:29 -08008443 return NO_ERROR;
8444}
8445
Eric Laurent18b57012017-02-13 16:23:52 -08008446status_t AudioFlinger::MmapThread::standby()
8447{
8448 ALOGV("%s", __FUNCTION__);
8449
8450 if (mHalStream == 0) {
8451 return NO_INIT;
8452 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008453 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008454 return INVALID_OPERATION;
8455 }
8456 mHalStream->standby();
8457 mStandby = true;
8458 releaseWakeLock();
8459 return NO_ERROR;
8460}
8461
Eric Laurent6acd1d42017-01-04 14:23:29 -08008462
8463void AudioFlinger::MmapThread::readHalParameters_l()
8464{
8465 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8466 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8467 mFormat = mHALFormat;
8468 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8469 result = mHalStream->getFrameSize(&mFrameSize);
8470 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8471 result = mHalStream->getBufferSize(&mBufferSize);
8472 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8473 mFrameCount = mBufferSize / mFrameSize;
8474}
8475
8476bool AudioFlinger::MmapThread::threadLoop()
8477{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008478 checkSilentMode_l();
8479
8480 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8481
8482 while (!exitPending())
8483 {
8484 Mutex::Autolock _l(mLock);
8485 Vector< sp<EffectChain> > effectChains;
8486
8487 if (mSignalPending) {
8488 // A signal was raised while we were unlocked
8489 mSignalPending = false;
8490 } else {
8491 if (mConfigEvents.isEmpty()) {
8492 // we're about to wait, flush the binder command buffer
8493 IPCThreadState::self()->flushCommands();
8494
8495 if (exitPending()) {
8496 break;
8497 }
8498
Eric Laurent6acd1d42017-01-04 14:23:29 -08008499 // wait until we have something to do...
8500 ALOGV("%s going to sleep", myName.string());
8501 mWaitWorkCV.wait(mLock);
8502 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008503
8504 checkSilentMode_l();
8505
8506 continue;
8507 }
8508 }
8509
8510 processConfigEvents_l();
8511
8512 processVolume_l();
8513
8514 checkInvalidTracks_l();
8515
8516 mActiveTracks.updatePowerState(this);
8517
Kevin Rocard069c2712018-03-29 19:09:14 -07008518 updateMetadata_l();
8519
Eric Laurent6acd1d42017-01-04 14:23:29 -08008520 lockEffectChains_l(effectChains);
8521 for (size_t i = 0; i < effectChains.size(); i ++) {
8522 effectChains[i]->process_l();
8523 }
8524 // enable changes in effect chain
8525 unlockEffectChains(effectChains);
8526 // Effect chains will be actually deleted here if they were removed from
8527 // mEffectChains list during mixing or effects processing
8528 }
8529
8530 threadLoop_exit();
8531
8532 if (!mStandby) {
8533 threadLoop_standby();
8534 mStandby = true;
8535 }
8536
Eric Laurent6acd1d42017-01-04 14:23:29 -08008537 ALOGV("Thread %p type %d exiting", this, mType);
8538 return false;
8539}
8540
8541// checkForNewParameter_l() must be called with ThreadBase::mLock held
8542bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8543 status_t& status)
8544{
8545 AudioParameter param = AudioParameter(keyValuePair);
8546 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008547 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008548 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008549 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008550 // forward device change to effects that have requested to be
8551 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008552 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008553 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008554 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008555 }
8556 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008557 if (audio_is_output_devices(device)) {
8558 mOutDevice = device;
8559 if (!isOutput()) {
8560 sendToHal = false;
8561 }
8562 } else {
8563 mInDevice = device;
8564 if (device != AUDIO_DEVICE_NONE) {
8565 mPrevInDevice = value;
8566 }
8567 // TODO: implement and call checkBtNrec_l();
8568 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008569 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008570 if (sendToHal) {
8571 status = mHalStream->setParameters(keyValuePair);
8572 } else {
8573 status = NO_ERROR;
8574 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008575
8576 return false;
8577}
8578
8579String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8580{
8581 Mutex::Autolock _l(mLock);
8582 String8 out_s8;
8583 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8584 return out_s8;
8585 }
8586 return String8();
8587}
8588
8589void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8590 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8591
8592 desc->mIoHandle = mId;
8593
8594 switch (event) {
8595 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008596 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008597 case AUDIO_INPUT_CONFIG_CHANGED:
8598 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008599 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008600 case AUDIO_OUTPUT_CONFIG_CHANGED:
8601 desc->mPatch = mPatch;
8602 desc->mChannelMask = mChannelMask;
8603 desc->mSamplingRate = mSampleRate;
8604 desc->mFormat = mFormat;
8605 desc->mFrameCount = mFrameCount;
8606 desc->mFrameCountHAL = mFrameCount;
8607 desc->mLatency = 0;
8608 break;
8609
8610 case AUDIO_INPUT_CLOSED:
8611 case AUDIO_OUTPUT_CLOSED:
8612 default:
8613 break;
8614 }
8615 mAudioFlinger->ioConfigChanged(event, desc, pid);
8616}
8617
8618status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8619 audio_patch_handle_t *handle)
8620{
8621 status_t status = NO_ERROR;
8622
8623 // store new device and send to effects
8624 audio_devices_t type = AUDIO_DEVICE_NONE;
8625 audio_port_handle_t deviceId;
8626 if (isOutput()) {
8627 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8628 type |= patch->sinks[i].ext.device.type;
8629 }
8630 deviceId = patch->sinks[0].id;
8631 } else {
8632 type = patch->sources[0].ext.device.type;
8633 deviceId = patch->sources[0].id;
8634 }
8635
8636 for (size_t i = 0; i < mEffectChains.size(); i++) {
8637 mEffectChains[i]->setDevice_l(type);
8638 }
8639
8640 if (isOutput()) {
8641 mOutDevice = type;
8642 } else {
8643 mInDevice = type;
8644 // store new source and send to effects
8645 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8646 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8647 for (size_t i = 0; i < mEffectChains.size(); i++) {
8648 mEffectChains[i]->setAudioSource_l(mAudioSource);
8649 }
8650 }
8651 }
8652
8653 if (mAudioHwDev->supportsAudioPatches()) {
8654 status = mHalDevice->createAudioPatch(patch->num_sources,
8655 patch->sources,
8656 patch->num_sinks,
8657 patch->sinks,
8658 handle);
8659 } else {
8660 char *address;
8661 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8662 //FIXME: we only support address on first sink with HAL version < 3.0
8663 address = audio_device_address_to_parameter(
8664 patch->sinks[0].ext.device.type,
8665 patch->sinks[0].ext.device.address);
8666 } else {
8667 address = (char *)calloc(1, 1);
8668 }
8669 AudioParameter param = AudioParameter(String8(address));
8670 free(address);
8671 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8672 if (!isOutput()) {
8673 param.addInt(String8(AudioParameter::keyInputSource),
8674 (int)patch->sinks[0].ext.mix.usecase.source);
8675 }
8676 status = mHalStream->setParameters(param.toString());
8677 *handle = AUDIO_PATCH_HANDLE_NONE;
8678 }
8679
8680 if (isOutput() && mPrevOutDevice != mOutDevice) {
8681 mPrevOutDevice = type;
8682 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008683 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008684 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008685 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008686 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008687 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008688 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008689 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008690 }
8691 if (!isOutput() && mPrevInDevice != mInDevice) {
8692 mPrevInDevice = type;
8693 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008694 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008695 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008696 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008697 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008698 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008699 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008700 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008701 }
8702 return status;
8703}
8704
8705status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8706{
8707 status_t status = NO_ERROR;
8708
8709 mInDevice = AUDIO_DEVICE_NONE;
8710
8711 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8712 supportsAudioPatches : false;
8713
8714 if (supportsAudioPatches) {
8715 status = mHalDevice->releaseAudioPatch(handle);
8716 } else {
8717 AudioParameter param;
8718 param.addInt(String8(AudioParameter::keyRouting), 0);
8719 status = mHalStream->setParameters(param.toString());
8720 }
8721 return status;
8722}
8723
Mikhail Naganovdc769682018-05-04 15:34:08 -07008724void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008725{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008726 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008727 if (isOutput()) {
8728 config->role = AUDIO_PORT_ROLE_SOURCE;
8729 config->ext.mix.hw_module = mAudioHwDev->handle();
8730 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8731 } else {
8732 config->role = AUDIO_PORT_ROLE_SINK;
8733 config->ext.mix.hw_module = mAudioHwDev->handle();
8734 config->ext.mix.usecase.source = mAudioSource;
8735 }
8736}
8737
8738status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8739{
8740 audio_session_t session = chain->sessionId();
8741
8742 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8743 // Attach all tracks with same session ID to this chain.
8744 // indicate all active tracks in the chain
8745 for (const sp<MmapTrack> &track : mActiveTracks) {
8746 if (session == track->sessionId()) {
8747 chain->incTrackCnt();
8748 chain->incActiveTrackCnt();
8749 }
8750 }
8751
8752 chain->setThread(this);
8753 chain->setInBuffer(nullptr);
8754 chain->setOutBuffer(nullptr);
8755 chain->syncHalEffectsState();
8756
8757 mEffectChains.add(chain);
8758 checkSuspendOnAddEffectChain_l(chain);
8759 return NO_ERROR;
8760}
8761
8762size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8763{
8764 audio_session_t session = chain->sessionId();
8765
8766 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8767
8768 for (size_t i = 0; i < mEffectChains.size(); i++) {
8769 if (chain == mEffectChains[i]) {
8770 mEffectChains.removeAt(i);
8771 // detach all active tracks from the chain
8772 // detach all tracks with same session ID from this chain
8773 for (const sp<MmapTrack> &track : mActiveTracks) {
8774 if (session == track->sessionId()) {
8775 chain->decActiveTrackCnt();
8776 chain->decTrackCnt();
8777 }
8778 }
8779 break;
8780 }
8781 }
8782 return mEffectChains.size();
8783}
8784
8785// hasAudioSession_l() must be called with ThreadBase::mLock held
8786uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8787{
8788 uint32_t result = 0;
8789 if (getEffectChain_l(sessionId) != 0) {
8790 result = EFFECT_SESSION;
8791 }
8792
8793 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8794 sp<MmapTrack> track = mActiveTracks[i];
8795 if (sessionId == track->sessionId()) {
8796 result |= TRACK_SESSION;
8797 if (track->isFastTrack()) {
8798 result |= FAST_SESSION;
8799 }
8800 break;
8801 }
8802 }
8803
8804 return result;
8805}
8806
8807void AudioFlinger::MmapThread::threadLoop_standby()
8808{
8809 mHalStream->standby();
8810}
8811
8812void AudioFlinger::MmapThread::threadLoop_exit()
8813{
Phil Burk7dce7282017-09-27 13:51:41 -07008814 // Do not call callback->onTearDown() because it is redundant for thread exit
8815 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008816}
8817
8818status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8819{
8820 return BAD_VALUE;
8821}
8822
8823bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8824{
8825 return false;
8826}
8827
8828status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8829 const effect_descriptor_t *desc, audio_session_t sessionId)
8830{
8831 // No global effect sessions on mmap threads
8832 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8833 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8834 desc->name, mThreadName);
8835 return BAD_VALUE;
8836 }
8837
8838 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8839 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8840 desc->name);
8841 return BAD_VALUE;
8842 }
8843 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008844 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8845 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008846 return BAD_VALUE;
8847 }
8848
8849 // Only allow effects without processing load or latency
8850 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8851 return BAD_VALUE;
8852 }
8853
8854 return NO_ERROR;
8855
8856}
8857
8858void AudioFlinger::MmapThread::checkInvalidTracks_l()
8859{
8860 for (const sp<MmapTrack> &track : mActiveTracks) {
8861 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008862 sp<MmapStreamCallback> callback = mCallback.promote();
8863 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008864 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008865 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008866 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008867 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8868 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8869 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008870 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008871 }
8872 }
8873}
8874
8875void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8876{
8877 dumpInternals(fd, args);
8878 dumpTracks(fd, args);
8879 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008880 dprintf(fd, " Local log:\n");
8881 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008882}
8883
8884void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8885{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008886 dumpBase(fd, args);
8887
8888 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8889 mAttr.content_type, mAttr.usage, mAttr.source);
8890 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07008891 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008892 dprintf(fd, " No active clients\n");
8893 }
8894}
8895
8896void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8897{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008898 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008899 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008900 dprintf(fd, " %zu Tracks\n", numtracks);
8901 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008902 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008903 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008904 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008905 for (size_t i = 0; i < numtracks ; ++i) {
8906 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008907 result.append(prefix);
8908 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008909 }
8910 } else {
8911 dprintf(fd, "\n");
8912 }
8913 write(fd, result.string(), result.size());
8914}
8915
8916AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8917 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8918 AudioHwDevice *hwDev, AudioStreamOut *output,
8919 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8920 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8921 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008922 mStreamVolume(1.0),
8923 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008924 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008925{
8926 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8927 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8928 mMasterVolume = audioFlinger->masterVolume_l();
8929 mMasterMute = audioFlinger->masterMute_l();
8930 if (mAudioHwDev) {
8931 if (mAudioHwDev->canSetMasterVolume()) {
8932 mMasterVolume = 1.0;
8933 }
8934
8935 if (mAudioHwDev->canSetMasterMute()) {
8936 mMasterMute = false;
8937 }
8938 }
8939}
8940
8941void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8942 audio_stream_type_t streamType,
8943 audio_session_t sessionId,
8944 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008945 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008946 audio_port_handle_t portId)
8947{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008948 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008949 mStreamType = streamType;
8950}
8951
8952AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8953{
8954 Mutex::Autolock _l(mLock);
8955 AudioStreamOut *output = mOutput;
8956 mOutput = NULL;
8957 return output;
8958}
8959
8960void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8961{
8962 Mutex::Autolock _l(mLock);
8963 // Don't apply master volume in SW if our HAL can do it for us.
8964 if (mAudioHwDev &&
8965 mAudioHwDev->canSetMasterVolume()) {
8966 mMasterVolume = 1.0;
8967 } else {
8968 mMasterVolume = value;
8969 }
8970}
8971
8972void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8973{
8974 Mutex::Autolock _l(mLock);
8975 // Don't apply master mute in SW if our HAL can do it for us.
8976 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8977 mMasterMute = false;
8978 } else {
8979 mMasterMute = muted;
8980 }
8981}
8982
8983void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8984{
8985 Mutex::Autolock _l(mLock);
8986 if (stream == mStreamType) {
8987 mStreamVolume = value;
8988 broadcast_l();
8989 }
8990}
8991
8992float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8993{
8994 Mutex::Autolock _l(mLock);
8995 if (stream == mStreamType) {
8996 return mStreamVolume;
8997 }
8998 return 0.0f;
8999}
9000
9001void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9002{
9003 Mutex::Autolock _l(mLock);
9004 if (stream == mStreamType) {
9005 mStreamMute= muted;
9006 broadcast_l();
9007 }
9008}
9009
9010void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9011{
9012 Mutex::Autolock _l(mLock);
9013 if (streamType == mStreamType) {
9014 for (const sp<MmapTrack> &track : mActiveTracks) {
9015 track->invalidate();
9016 }
9017 broadcast_l();
9018 }
9019}
9020
9021void AudioFlinger::MmapPlaybackThread::processVolume_l()
9022{
9023 float volume;
9024
9025 if (mMasterMute || mStreamMute) {
9026 volume = 0;
9027 } else {
9028 volume = mMasterVolume * mStreamVolume;
9029 }
9030
9031 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009032
9033 // Convert volumes from float to 8.24
9034 uint32_t vol = (uint32_t)(volume * (1 << 24));
9035
9036 // Delegate volume control to effect in track effect chain if needed
9037 // only one effect chain can be present on DirectOutputThread, so if
9038 // there is one, the track is connected to it
9039 if (!mEffectChains.isEmpty()) {
9040 mEffectChains[0]->setVolume_l(&vol, &vol);
9041 volume = (float)vol / (1 << 24);
9042 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009043 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009044 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9045 mHalVolFloat = volume; // HW volume control worked, so update value.
9046 mNoCallbackWarningCount = 0;
9047 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009048 sp<MmapStreamCallback> callback = mCallback.promote();
9049 if (callback != 0) {
9050 int channelCount;
9051 if (isOutput()) {
9052 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9053 } else {
9054 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9055 }
9056 Vector<float> values;
9057 for (int i = 0; i < channelCount; i++) {
9058 values.add(volume);
9059 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009060 mHalVolFloat = volume; // SW volume control worked, so update value.
9061 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009062 mLock.unlock();
9063 callback->onVolumeChanged(mChannelMask, values);
9064 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009065 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009066 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9067 ALOGW("Could not set MMAP stream volume: no volume callback!");
9068 mNoCallbackWarningCount++;
9069 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009070 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009071 }
9072 }
9073}
9074
Kevin Rocard069c2712018-03-29 19:09:14 -07009075void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9076{
9077 if (mOutput == nullptr || mOutput->stream == nullptr ||
9078 !mActiveTracks.readAndClearHasChanged()) {
9079 return;
9080 }
9081 StreamOutHalInterface::SourceMetadata metadata;
9082 for (const sp<MmapTrack> &track : mActiveTracks) {
9083 // No track is invalid as this is called after prepareTrack_l in the same critical section
9084 metadata.tracks.push_back({
9085 .usage = track->attributes().usage,
9086 .content_type = track->attributes().content_type,
9087 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9088 });
9089 }
9090 mOutput->stream->updateSourceMetadata(metadata);
9091}
9092
Eric Laurent6acd1d42017-01-04 14:23:29 -08009093void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9094{
9095 if (!mMasterMute) {
9096 char value[PROPERTY_VALUE_MAX];
9097 if (property_get("ro.audio.silent", value, "0") > 0) {
9098 char *endptr;
9099 unsigned long ul = strtoul(value, &endptr, 0);
9100 if (*endptr == '\0' && ul != 0) {
9101 ALOGD("Silence is golden");
9102 // The setprop command will not allow a property to be changed after
9103 // the first time it is set, so we don't have to worry about un-muting.
9104 setMasterMute_l(true);
9105 }
9106 }
9107 }
9108}
9109
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009110void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9111{
9112 MmapThread::toAudioPortConfig(config);
9113 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9114 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9115 config->flags.output = mOutput->flags;
9116 }
9117}
9118
Eric Laurent6acd1d42017-01-04 14:23:29 -08009119void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9120{
9121 MmapThread::dumpInternals(fd, args);
9122
Glenn Kastend3bb6452016-12-05 18:14:37 -08009123 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9124 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009125 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9126}
9127
9128AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9129 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9130 AudioHwDevice *hwDev, AudioStreamIn *input,
9131 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9132 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9133 mInput(input)
9134{
9135 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9136 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9137}
9138
Eric Laurent331679c2018-04-16 17:03:16 -07009139status_t AudioFlinger::MmapCaptureThread::exitStandby()
9140{
9141 mInput->stream->setGain(1.0f);
9142 return MmapThread::exitStandby();
9143}
9144
Eric Laurent6acd1d42017-01-04 14:23:29 -08009145AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9146{
9147 Mutex::Autolock _l(mLock);
9148 AudioStreamIn *input = mInput;
9149 mInput = NULL;
9150 return input;
9151}
Kevin Rocard069c2712018-03-29 19:09:14 -07009152
Eric Laurent331679c2018-04-16 17:03:16 -07009153
9154void AudioFlinger::MmapCaptureThread::processVolume_l()
9155{
9156 bool changed = false;
9157 bool silenced = false;
9158
9159 sp<MmapStreamCallback> callback = mCallback.promote();
9160 if (callback == 0) {
9161 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9162 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9163 mNoCallbackWarningCount++;
9164 }
9165 }
9166
9167 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9168 // track is silenced and unmute otherwise
9169 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9170 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9171 changed = true;
9172 silenced = mActiveTracks[i]->isSilenced_l();
9173 }
9174 }
9175
9176 if (changed) {
9177 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9178 }
9179}
9180
Kevin Rocard069c2712018-03-29 19:09:14 -07009181void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9182{
9183 if (mInput == nullptr || mInput->stream == nullptr ||
9184 !mActiveTracks.readAndClearHasChanged()) {
9185 return;
9186 }
9187 StreamInHalInterface::SinkMetadata metadata;
9188 for (const sp<MmapTrack> &track : mActiveTracks) {
9189 // No track is invalid as this is called after prepareTrack_l in the same critical section
9190 metadata.tracks.push_back({
9191 .source = track->attributes().source,
9192 .gain = 1, // capture tracks do not have volumes
9193 });
9194 }
9195 mInput->stream->updateSinkMetadata(metadata);
9196}
9197
Eric Laurent331679c2018-04-16 17:03:16 -07009198void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9199{
9200 Mutex::Autolock _l(mLock);
9201 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9202 if (mActiveTracks[i]->uid() == uid) {
9203 mActiveTracks[i]->setSilenced_l(silenced);
9204 broadcast_l();
9205 }
9206 }
9207}
9208
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009209void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9210{
9211 MmapThread::toAudioPortConfig(config);
9212 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9213 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9214 config->flags.input = mInput->flags;
9215 }
9216}
9217
Glenn Kasten63238ef2015-03-02 15:50:29 -08009218} // namespace android