blob: cd585f5574cb58dd5a3dd56b840e29a8512be564 [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());
866 }
867
Eric Laurent81784c32012-11-19 14:55:58 -0800868 if (locked) {
869 mLock.unlock();
870 }
871}
872
873void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
874{
875 const size_t SIZE = 256;
876 char buffer[SIZE];
877 String8 result;
878
Marco Nelissenb2208842014-02-07 14:00:50 -0800879 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000880 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800881 write(fd, buffer, strlen(buffer));
882
Marco Nelissenb2208842014-02-07 14:00:50 -0800883 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800884 sp<EffectChain> chain = mEffectChains[i];
885 if (chain != 0) {
886 chain->dump(fd, args);
887 }
888 }
889}
890
Andy Hungdae27702016-10-31 14:01:16 -0700891void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800892{
893 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700894 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800895}
896
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100897String16 AudioFlinger::ThreadBase::getWakeLockTag()
898{
899 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800900 case MIXER:
901 return String16("AudioMix");
902 case DIRECT:
903 return String16("AudioDirectOut");
904 case DUPLICATING:
905 return String16("AudioDup");
906 case RECORD:
907 return String16("AudioIn");
908 case OFFLOAD:
909 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800910 case MMAP:
911 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800912 default:
913 ALOG_ASSERT(false);
914 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100915 }
916}
917
Andy Hungdae27702016-10-31 14:01:16 -0700918void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800919{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800920 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800921 if (mPowerManager != 0) {
922 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700923 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
924 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700925 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100926 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700927 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700928 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 if (status == NO_ERROR) {
930 mWakeLockToken = binder;
931 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800932 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800933 }
Wei Jia3f273d12015-11-24 09:06:49 -0800934
Andy Hung3f0c9022016-01-15 17:49:46 -0800935 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800936 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
937 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800938}
939
940void AudioFlinger::ThreadBase::releaseWakeLock()
941{
942 Mutex::Autolock _l(mLock);
943 releaseWakeLock_l();
944}
945
946void AudioFlinger::ThreadBase::releaseWakeLock_l()
947{
Andy Hung3f0c9022016-01-15 17:49:46 -0800948 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800949 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800950 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800951 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700952 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
953 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800954 }
955 mWakeLockToken.clear();
956 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957}
958
959void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700960 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800961 // use checkService() to avoid blocking if power service is not up yet
962 sp<IBinder> binder =
963 defaultServiceManager()->checkService(String16("power"));
964 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800965 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800966 } else {
967 mPowerManager = interface_cast<IPowerManager>(binder);
968 binder->linkToDeath(mDeathRecipient);
969 }
970 }
971}
972
Andy Hungd01b0f12016-11-07 16:10:30 -0800973void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800974 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700975
976#if !LOG_NDEBUG
977 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800978 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700979 s << uid << " ";
980 }
981 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
982#endif
983
Andy Hung438e7572015-12-14 15:51:17 -0800984 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
985 if (mSystemReady) {
986 ALOGE("no wake lock to update, but system ready!");
987 } else {
988 ALOGW("no wake lock to update, system not ready yet");
989 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800990 return;
991 }
992 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800993 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
994 status_t status = mPowerManager->updateWakeLockUids(
995 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
996 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800997 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800998 }
999}
1000
Eric Laurent81784c32012-11-19 14:55:58 -08001001void AudioFlinger::ThreadBase::clearPowerManager()
1002{
1003 Mutex::Autolock _l(mLock);
1004 releaseWakeLock_l();
1005 mPowerManager.clear();
1006}
1007
Glenn Kasten0f11b512014-01-31 16:18:54 -08001008void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001009{
1010 sp<ThreadBase> thread = mThread.promote();
1011 if (thread != 0) {
1012 thread->clearPowerManager();
1013 }
1014 ALOGW("power manager service died !!!");
1015}
1016
Eric Laurent81784c32012-11-19 14:55:58 -08001017void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001018 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001019{
1020 sp<EffectChain> chain = getEffectChain_l(sessionId);
1021 if (chain != 0) {
1022 if (type != NULL) {
1023 chain->setEffectSuspended_l(type, suspend);
1024 } else {
1025 chain->setEffectSuspendedAll_l(suspend);
1026 }
1027 }
1028
1029 updateSuspendedSessions_l(type, suspend, sessionId);
1030}
1031
1032void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1033{
1034 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1035 if (index < 0) {
1036 return;
1037 }
1038
1039 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1040 mSuspendedSessions.valueAt(index);
1041
1042 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001043 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001044 for (int j = 0; j < desc->mRefCount; j++) {
1045 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1046 chain->setEffectSuspendedAll_l(true);
1047 } else {
1048 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1049 desc->mType.timeLow);
1050 chain->setEffectSuspended_l(&desc->mType, true);
1051 }
1052 }
1053 }
1054}
1055
1056void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1057 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001058 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001059{
1060 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1061
1062 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1063
1064 if (suspend) {
1065 if (index >= 0) {
1066 sessionEffects = mSuspendedSessions.valueAt(index);
1067 } else {
1068 mSuspendedSessions.add(sessionId, sessionEffects);
1069 }
1070 } else {
1071 if (index < 0) {
1072 return;
1073 }
1074 sessionEffects = mSuspendedSessions.valueAt(index);
1075 }
1076
1077
1078 int key = EffectChain::kKeyForSuspendAll;
1079 if (type != NULL) {
1080 key = type->timeLow;
1081 }
1082 index = sessionEffects.indexOfKey(key);
1083
1084 sp<SuspendedSessionDesc> desc;
1085 if (suspend) {
1086 if (index >= 0) {
1087 desc = sessionEffects.valueAt(index);
1088 } else {
1089 desc = new SuspendedSessionDesc();
1090 if (type != NULL) {
1091 desc->mType = *type;
1092 }
1093 sessionEffects.add(key, desc);
1094 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1095 }
1096 desc->mRefCount++;
1097 } else {
1098 if (index < 0) {
1099 return;
1100 }
1101 desc = sessionEffects.valueAt(index);
1102 if (--desc->mRefCount == 0) {
1103 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1104 sessionEffects.removeItemsAt(index);
1105 if (sessionEffects.isEmpty()) {
1106 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1107 sessionId);
1108 mSuspendedSessions.removeItem(sessionId);
1109 }
1110 }
1111 }
1112 if (!sessionEffects.isEmpty()) {
1113 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1114 }
1115}
1116
1117void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1118 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001119 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001120{
1121 Mutex::Autolock _l(mLock);
1122 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1123}
1124
1125void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1126 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001127 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001128{
1129 if (mType != RECORD) {
1130 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1131 // another session. This gives the priority to well behaved effect control panels
1132 // and applications not using global effects.
1133 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1134 // global effects
1135 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1136 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1137 }
1138 }
1139
1140 sp<EffectChain> chain = getEffectChain_l(sessionId);
1141 if (chain != 0) {
1142 chain->checkSuspendOnEffectEnabled(effect, enabled);
1143 }
1144}
1145
Eric Laurent4c415062016-06-17 16:14:16 -07001146// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1147status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1148 const effect_descriptor_t *desc, audio_session_t sessionId)
1149{
1150 // No global effect sessions on record threads
1151 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1152 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1153 desc->name, mThreadName);
1154 return BAD_VALUE;
1155 }
1156 // only pre processing effects on record thread
1157 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1158 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1159 desc->name, mThreadName);
1160 return BAD_VALUE;
1161 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001162
1163 // always allow effects without processing load or latency
1164 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1165 return NO_ERROR;
1166 }
1167
Eric Laurent4c415062016-06-17 16:14:16 -07001168 audio_input_flags_t flags = mInput->flags;
1169 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1170 if (flags & AUDIO_INPUT_FLAG_RAW) {
1171 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1172 desc->name, mThreadName);
1173 return BAD_VALUE;
1174 }
1175 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1176 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1177 desc->name, mThreadName);
1178 return BAD_VALUE;
1179 }
1180 }
1181 return NO_ERROR;
1182}
1183
1184// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1185status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1186 const effect_descriptor_t *desc, audio_session_t sessionId)
1187{
1188 // no preprocessing on playback threads
1189 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1190 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1191 " thread %s", desc->name, mThreadName);
1192 return BAD_VALUE;
1193 }
1194
Eric Laurent3e4de772017-07-16 16:55:08 -07001195 // always allow effects without processing load or latency
1196 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1197 return NO_ERROR;
1198 }
1199
Eric Laurent4c415062016-06-17 16:14:16 -07001200 switch (mType) {
1201 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001202#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001203 // Reject any effect on mixer multichannel sinks.
1204 // TODO: fix both format and multichannel issues with effects.
1205 if (mChannelCount != FCC_2) {
1206 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1207 " thread %s", desc->name, mChannelCount, mThreadName);
1208 return BAD_VALUE;
1209 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001210#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001211 audio_output_flags_t flags = mOutput->flags;
1212 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1213 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1214 // global effects are applied only to non fast tracks if they are SW
1215 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1216 break;
1217 }
1218 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1219 // only post processing on output stage session
1220 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1221 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1222 " on output stage session", desc->name);
1223 return BAD_VALUE;
1224 }
1225 } else {
1226 // no restriction on effects applied on non fast tracks
1227 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1228 break;
1229 }
1230 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001231
Eric Laurent4c415062016-06-17 16:14:16 -07001232 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1233 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1234 desc->name);
1235 return BAD_VALUE;
1236 }
1237 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1238 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1239 " in fast mode", desc->name);
1240 return BAD_VALUE;
1241 }
1242 }
1243 } break;
1244 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001245 // nothing actionable on offload threads, if the effect:
1246 // - is offloadable: the effect can be created
1247 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1248 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001249 break;
1250 case DIRECT:
1251 // Reject any effect on Direct output threads for now, since the format of
1252 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1253 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1254 desc->name, mThreadName);
1255 return BAD_VALUE;
1256 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001257#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001258 // Reject any effect on mixer multichannel sinks.
1259 // TODO: fix both format and multichannel issues with effects.
1260 if (mChannelCount != FCC_2) {
1261 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1262 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1263 return BAD_VALUE;
1264 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001265#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001266 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1267 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1268 " thread %s", desc->name, mThreadName);
1269 return BAD_VALUE;
1270 }
1271 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1272 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1273 " DUPLICATING thread %s", desc->name, mThreadName);
1274 return BAD_VALUE;
1275 }
1276 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1277 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1278 " DUPLICATING thread %s", desc->name, mThreadName);
1279 return BAD_VALUE;
1280 }
1281 break;
1282 default:
1283 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1284 }
1285
1286 return NO_ERROR;
1287}
1288
Eric Laurent81784c32012-11-19 14:55:58 -08001289// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1290sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1291 const sp<AudioFlinger::Client>& client,
1292 const sp<IEffectClient>& effectClient,
1293 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001294 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001295 effect_descriptor_t *desc,
1296 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001297 status_t *status,
1298 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001299{
1300 sp<EffectModule> effect;
1301 sp<EffectHandle> handle;
1302 status_t lStatus;
1303 sp<EffectChain> chain;
1304 bool chainCreated = false;
1305 bool effectCreated = false;
1306 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001307 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001308
1309 lStatus = initCheck();
1310 if (lStatus != NO_ERROR) {
1311 ALOGW("createEffect_l() Audio driver not initialized.");
1312 goto Exit;
1313 }
1314
Eric Laurent81784c32012-11-19 14:55:58 -08001315 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1316
1317 { // scope for mLock
1318 Mutex::Autolock _l(mLock);
1319
Eric Laurent4c415062016-06-17 16:14:16 -07001320 lStatus = checkEffectCompatibility_l(desc, sessionId);
1321 if (lStatus != NO_ERROR) {
1322 goto Exit;
1323 }
1324
Eric Laurent81784c32012-11-19 14:55:58 -08001325 // check for existing effect chain with the requested audio session
1326 chain = getEffectChain_l(sessionId);
1327 if (chain == 0) {
1328 // create a new chain for this session
1329 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1330 chain = new EffectChain(this, sessionId);
1331 addEffectChain_l(chain);
1332 chain->setStrategy(getStrategyForSession_l(sessionId));
1333 chainCreated = true;
1334 } else {
1335 effect = chain->getEffectFromDesc_l(desc);
1336 }
1337
1338 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1339
1340 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001341 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001342 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001343 lStatus = AudioSystem::registerEffect(
1344 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001345 if (lStatus != NO_ERROR) {
1346 goto Exit;
1347 }
1348 effectRegistered = true;
1349 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001350 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001351 if (lStatus != NO_ERROR) {
1352 goto Exit;
1353 }
1354 effectCreated = true;
1355
1356 effect->setDevice(mOutDevice);
1357 effect->setDevice(mInDevice);
1358 effect->setMode(mAudioFlinger->getMode());
1359 effect->setAudioSource(mAudioSource);
1360 }
1361 // create effect handle and connect it to effect module
1362 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001363 lStatus = handle->initCheck();
1364 if (lStatus == OK) {
1365 lStatus = effect->addHandle(handle.get());
1366 }
Eric Laurent81784c32012-11-19 14:55:58 -08001367 if (enabled != NULL) {
1368 *enabled = (int)effect->isEnabled();
1369 }
1370 }
1371
1372Exit:
1373 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1374 Mutex::Autolock _l(mLock);
1375 if (effectCreated) {
1376 chain->removeEffect_l(effect);
1377 }
1378 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001379 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001380 }
1381 if (chainCreated) {
1382 removeEffectChain_l(chain);
1383 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001384 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001385 }
1386
Glenn Kasten9156ef32013-08-06 15:39:08 -07001387 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001388 return handle;
1389}
1390
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001391void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1392 bool unpinIfLast)
1393{
1394 bool remove = false;
1395 sp<EffectModule> effect;
1396 {
1397 Mutex::Autolock _l(mLock);
1398
1399 effect = handle->effect().promote();
1400 if (effect == 0) {
1401 return;
1402 }
1403 // restore suspended effects if the disconnected handle was enabled and the last one.
1404 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1405 if (remove) {
1406 removeEffect_l(effect, true);
1407 }
1408 }
1409 if (remove) {
1410 mAudioFlinger->updateOrphanEffectChains(effect);
1411 AudioSystem::unregisterEffect(effect->id());
1412 if (handle->enabled()) {
1413 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1414 }
1415 }
1416}
1417
Glenn Kastend848eb42016-03-08 13:42:11 -08001418sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1419 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001420{
1421 Mutex::Autolock _l(mLock);
1422 return getEffect_l(sessionId, effectId);
1423}
1424
Glenn Kastend848eb42016-03-08 13:42:11 -08001425sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1426 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001427{
1428 sp<EffectChain> chain = getEffectChain_l(sessionId);
1429 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1430}
1431
1432// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1433// PlaybackThread::mLock held
1434status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1435{
1436 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001437 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001438 sp<EffectChain> chain = getEffectChain_l(sessionId);
1439 bool chainCreated = false;
1440
Eric Laurent5baf2af2013-09-12 17:37:00 -07001441 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001442 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001443 this, effect->desc().name, effect->desc().flags);
1444
Eric Laurent81784c32012-11-19 14:55:58 -08001445 if (chain == 0) {
1446 // create a new chain for this session
1447 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1448 chain = new EffectChain(this, sessionId);
1449 addEffectChain_l(chain);
1450 chain->setStrategy(getStrategyForSession_l(sessionId));
1451 chainCreated = true;
1452 }
1453 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1454
1455 if (chain->getEffectFromId_l(effect->id()) != 0) {
1456 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1457 this, effect->desc().name, chain.get());
1458 return BAD_VALUE;
1459 }
1460
Eric Laurent5baf2af2013-09-12 17:37:00 -07001461 effect->setOffloaded(mType == OFFLOAD, mId);
1462
Eric Laurent81784c32012-11-19 14:55:58 -08001463 status_t status = chain->addEffect_l(effect);
1464 if (status != NO_ERROR) {
1465 if (chainCreated) {
1466 removeEffectChain_l(chain);
1467 }
1468 return status;
1469 }
1470
1471 effect->setDevice(mOutDevice);
1472 effect->setDevice(mInDevice);
1473 effect->setMode(mAudioFlinger->getMode());
1474 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001475
Eric Laurent81784c32012-11-19 14:55:58 -08001476 return NO_ERROR;
1477}
1478
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001479void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001480
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001481 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001482 effect_descriptor_t desc = effect->desc();
1483 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1484 detachAuxEffect_l(effect->id());
1485 }
1486
1487 sp<EffectChain> chain = effect->chain().promote();
1488 if (chain != 0) {
1489 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001490 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001491 removeEffectChain_l(chain);
1492 }
1493 } else {
1494 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1495 }
1496}
1497
1498void AudioFlinger::ThreadBase::lockEffectChains_l(
1499 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1500{
1501 effectChains = mEffectChains;
1502 for (size_t i = 0; i < mEffectChains.size(); i++) {
1503 mEffectChains[i]->lock();
1504 }
1505}
1506
1507void AudioFlinger::ThreadBase::unlockEffectChains(
1508 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1509{
1510 for (size_t i = 0; i < effectChains.size(); i++) {
1511 effectChains[i]->unlock();
1512 }
1513}
1514
Glenn Kastend848eb42016-03-08 13:42:11 -08001515sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001516{
1517 Mutex::Autolock _l(mLock);
1518 return getEffectChain_l(sessionId);
1519}
1520
Glenn Kastend848eb42016-03-08 13:42:11 -08001521sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1522 const
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 size_t size = mEffectChains.size();
1525 for (size_t i = 0; i < size; i++) {
1526 if (mEffectChains[i]->sessionId() == sessionId) {
1527 return mEffectChains[i];
1528 }
1529 }
1530 return 0;
1531}
1532
1533void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1534{
1535 Mutex::Autolock _l(mLock);
1536 size_t size = mEffectChains.size();
1537 for (size_t i = 0; i < size; i++) {
1538 mEffectChains[i]->setMode_l(mode);
1539 }
1540}
1541
Mikhail Naganovdc769682018-05-04 15:34:08 -07001542void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001543{
1544 config->type = AUDIO_PORT_TYPE_MIX;
1545 config->ext.mix.handle = mId;
1546 config->sample_rate = mSampleRate;
1547 config->format = mFormat;
1548 config->channel_mask = mChannelMask;
1549 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1550 AUDIO_PORT_CONFIG_FORMAT;
1551}
1552
Eric Laurent72e3f392015-05-20 14:43:50 -07001553void AudioFlinger::ThreadBase::systemReady()
1554{
1555 Mutex::Autolock _l(mLock);
1556 if (mSystemReady) {
1557 return;
1558 }
1559 mSystemReady = true;
1560
1561 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1562 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1563 }
1564 mPendingConfigEvents.clear();
1565}
1566
Andy Hungdae27702016-10-31 14:01:16 -07001567template <typename T>
1568ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1569 ssize_t index = mActiveTracks.indexOf(track);
1570 if (index >= 0) {
1571 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1572 return index;
1573 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001574 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001575 mActiveTracksGeneration++;
1576 mLatestActiveTrack = track;
1577 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001578 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001579 return mActiveTracks.add(track);
1580}
1581
1582template <typename T>
1583ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1584 ssize_t index = mActiveTracks.remove(track);
1585 if (index < 0) {
1586 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1587 return index;
1588 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001589 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001590 mActiveTracksGeneration++;
1591 --mBatteryCounter[track->uid()].second;
1592 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001593 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001594#ifdef TEE_SINK
1595 track->dumpTee(-1 /* fd */, "_REMOVE");
1596#endif
Andy Hungdae27702016-10-31 14:01:16 -07001597 return index;
1598}
1599
1600template <typename T>
1601void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1602 for (const sp<T> &track : mActiveTracks) {
1603 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001604 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001605 }
1606 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001607 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001608 mActiveTracks.clear();
1609 mLatestActiveTrack.clear();
1610 mBatteryCounter.clear();
1611}
1612
1613template <typename T>
1614void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1615 sp<ThreadBase> thread, bool force) {
1616 // Updates ActiveTracks client uids to the thread wakelock.
1617 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1618 thread->updateWakeLockUids_l(getWakeLockUids());
1619 mLastActiveTracksGeneration = mActiveTracksGeneration;
1620 }
1621
1622 // Updates BatteryNotifier uids
1623 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1624 const uid_t uid = it->first;
1625 ssize_t &previous = it->second.first;
1626 ssize_t &current = it->second.second;
1627 if (current > 0) {
1628 if (previous == 0) {
1629 BatteryNotifier::getInstance().noteStartAudio(uid);
1630 }
1631 previous = current;
1632 ++it;
1633 } else if (current == 0) {
1634 if (previous > 0) {
1635 BatteryNotifier::getInstance().noteStopAudio(uid);
1636 }
1637 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1638 } else /* (current < 0) */ {
1639 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1640 }
1641 }
1642}
Eric Laurent83b88082014-06-20 18:31:16 -07001643
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001644template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001645bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1646 const bool hasChanged = mHasChanged;
1647 mHasChanged = false;
1648 return hasChanged;
1649}
1650
1651template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001652void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1653 const char *funcName, const sp<T> &track) const {
1654 if (mLocalLog != nullptr) {
1655 String8 result;
1656 track->appendDump(result, false /* active */);
1657 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1658 }
1659}
1660
Eric Laurent6acd1d42017-01-04 14:23:29 -08001661void AudioFlinger::ThreadBase::broadcast_l()
1662{
1663 // Thread could be blocked waiting for async
1664 // so signal it to handle state changes immediately
1665 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1666 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1667 mSignalPending = true;
1668 mWaitWorkCV.broadcast();
1669}
1670
Eric Laurent81784c32012-11-19 14:55:58 -08001671// ----------------------------------------------------------------------------
1672// Playback
1673// ----------------------------------------------------------------------------
1674
1675AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1676 AudioStreamOut* output,
1677 audio_io_handle_t id,
1678 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001679 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001680 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001681 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001682 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001683 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001684 mMixerBuffer(NULL),
1685 mMixerBufferSize(0),
1686 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1687 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001688 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001689 mEffectBuffer(NULL),
1690 mEffectBufferSize(0),
1691 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1692 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001693 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001694 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001695 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001696 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001697 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001698 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001699 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001700 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001701 mMixerStatus(MIXER_IDLE),
1702 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001703 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001704 mBytesRemaining(0),
1705 mCurrentWriteLength(0),
1706 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001707 mWriteAckSequence(0),
1708 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001709 mScreenState(AudioFlinger::mScreenState),
1710 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001711 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001712 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1713 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001714{
Glenn Kastend7dca052015-03-05 16:05:54 -08001715 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1716 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001717
1718 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1719 // it would be safer to explicitly pass initial masterVolume/masterMute as
1720 // parameter.
1721 //
1722 // If the HAL we are using has support for master volume or master mute,
1723 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1724 // and the mute set to false).
1725 mMasterVolume = audioFlinger->masterVolume_l();
1726 mMasterMute = audioFlinger->masterMute_l();
1727 if (mOutput && mOutput->audioHwDev) {
1728 if (mOutput->audioHwDev->canSetMasterVolume()) {
1729 mMasterVolume = 1.0;
1730 }
1731
1732 if (mOutput->audioHwDev->canSetMasterMute()) {
1733 mMasterMute = false;
1734 }
1735 }
1736
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001737 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001738
Eric Laurent223fd5c2014-11-11 13:43:36 -08001739 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001740 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001741 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001742 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001743 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1744 }
Eric Laurent98e38192018-02-15 18:31:53 -08001745 // Audio patch volume is always max
1746 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1747 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001748}
1749
1750AudioFlinger::PlaybackThread::~PlaybackThread()
1751{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001752 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001753 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001754 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001755 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001756}
1757
1758void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1759{
1760 dumpInternals(fd, args);
1761 dumpTracks(fd, args);
1762 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001763 dprintf(fd, " Local log:\n");
1764 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001765}
1766
Eric Tan1882f162018-08-02 18:05:39 -07001767Json::Value AudioFlinger::PlaybackThread::getJsonDump() const
Eric Tan7b651152018-07-13 10:17:19 -07001768{
Eric Tan1882f162018-08-02 18:05:39 -07001769 return Json::Value(Json::objectValue);
Eric Tan7b651152018-07-13 10:17:19 -07001770}
1771
Glenn Kasten0f11b512014-01-31 16:18:54 -08001772void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001773{
Eric Laurent81784c32012-11-19 14:55:58 -08001774 String8 result;
1775
Marco Nelissenb2208842014-02-07 14:00:50 -08001776 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001777 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1778 const stream_type_t *st = &mStreamTypes[i];
1779 if (i > 0) {
1780 result.appendFormat(", ");
1781 }
1782 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1783 if (st->mute) {
1784 result.append("M");
1785 }
1786 }
1787 result.append("\n");
1788 write(fd, result.string(), result.length());
1789 result.clear();
1790
Eric Laurent81784c32012-11-19 14:55:58 -08001791 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1792 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001793 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001794 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001795
1796 size_t numtracks = mTracks.size();
1797 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001798 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001799 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001800 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001801 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001802 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001803 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001804 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001805 for (size_t i = 0; i < numtracks; ++i) {
1806 sp<Track> track = mTracks[i];
1807 if (track != 0) {
1808 bool active = mActiveTracks.indexOf(track) >= 0;
1809 if (active) {
1810 numactiveseen++;
1811 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001812 result.append(prefix);
1813 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001814 }
1815 }
1816 } else {
1817 result.append("\n");
1818 }
1819 if (numactiveseen != numactive) {
1820 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001821 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001822 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001823 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001824 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001825 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001826 sp<Track> track = mActiveTracks[i];
1827 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001828 result.append(prefix);
1829 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001830 }
1831 }
1832 }
1833
1834 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001835}
1836
1837void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1838{
Glenn Kasten44182c22015-03-05 17:12:23 -08001839 dumpBase(fd, args);
1840
Elliott Hughes87cebad2014-05-22 10:14:43 -07001841 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001842 dprintf(fd, " Last write occurred (msecs): %llu\n",
1843 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001844 dprintf(fd, " Total writes: %d\n", mNumWrites);
1845 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1846 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1847 dprintf(fd, " Suspend count: %d\n", mSuspended);
1848 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1849 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1850 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1851 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001852 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001853 AudioStreamOut *output = mOutput;
1854 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001855 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1856 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001857 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1858 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1859 if (mPipeSink.get() != nullptr) {
1860 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1861 }
1862 if (output != nullptr) {
1863 dprintf(fd, " Hal stream dump:\n");
1864 (void)output->stream->dump(fd);
1865 }
Eric Laurent81784c32012-11-19 14:55:58 -08001866}
1867
1868// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001869
1870void AudioFlinger::PlaybackThread::onFirstRef()
1871{
Glenn Kastend7dca052015-03-05 16:05:54 -08001872 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001873}
1874
1875// ThreadBase virtuals
1876void AudioFlinger::PlaybackThread::preExit()
1877{
1878 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001879 // FIXME this is using hard-coded strings but in the future, this functionality will be
1880 // converted to use audio HAL extensions required to support tunneling
1881 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1882 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001883}
1884
1885// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1886sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1887 const sp<AudioFlinger::Client>& client,
1888 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001889 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001890 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001891 audio_format_t format,
1892 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001893 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001894 size_t *pNotificationFrameCount,
1895 uint32_t notificationsPerBuffer,
1896 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001897 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001898 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001899 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001900 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001901 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001902 status_t *status,
1903 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001904{
Glenn Kasten74935e42013-12-19 08:56:45 -08001905 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001906 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001907 sp<Track> track;
1908 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001909 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001910 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001911 uint32_t sampleRate;
1912
1913 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1914 lStatus = BAD_VALUE;
1915 goto Exit;
1916 }
Eric Laurent21da6472017-11-09 16:29:26 -08001917
1918 if (*pSampleRate == 0) {
1919 *pSampleRate = mSampleRate;
1920 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001921 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001922
1923 // special case for FAST flag considered OK if fast mixer is present
1924 if (hasFastMixer()) {
1925 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1926 }
1927
1928 // Check if requested flags are compatible with output stream flags
1929 if ((*flags & outputFlags) != *flags) {
1930 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1931 *flags, outputFlags);
1932 *flags = (audio_output_flags_t)(*flags & outputFlags);
1933 }
Eric Laurent81784c32012-11-19 14:55:58 -08001934
Eric Laurent81784c32012-11-19 14:55:58 -08001935 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001936 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001937 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001938 // PCM data
1939 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001940 // TODO: extract as a data library function that checks that a computationally
1941 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001942 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001943 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1944 (channelMask == AUDIO_CHANNEL_OUT_MONO
1945 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001946 // hardware sample rate
1947 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001948 // normal mixer has an associated fast mixer
1949 hasFastMixer() &&
1950 // there are sufficient fast track slots available
1951 (mFastTrackAvailMask != 0)
1952 // FIXME test that MixerThread for this fast track has a capable output HAL
1953 // FIXME add a permission test also?
1954 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001955 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1956 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001957 // read the fast track multiplier property the first time it is needed
1958 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1959 if (ok != 0) {
1960 ALOGE("%s pthread_once failed: %d", __func__, ok);
1961 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001962 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001963 }
Eric Laurent4c415062016-06-17 16:14:16 -07001964
1965 // check compatibility with audio effects.
1966 { // scope for mLock
1967 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001968 for (audio_session_t session : {
1969 AUDIO_SESSION_OUTPUT_STAGE,
1970 AUDIO_SESSION_OUTPUT_MIX,
1971 sessionId,
1972 }) {
1973 sp<EffectChain> chain = getEffectChain_l(session);
1974 if (chain.get() != nullptr) {
1975 audio_output_flags_t old = *flags;
1976 chain->checkOutputFlagCompatibility(flags);
1977 if (old != *flags) {
1978 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1979 (int)session, (int)old, (int)*flags);
1980 }
Eric Laurent4c415062016-06-17 16:14:16 -07001981 }
1982 }
1983 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001984 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001985 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1986 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001987 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001988 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1989 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001990 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001991 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001992 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001993 audio_is_linear_pcm(format),
1994 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001995 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001996 }
1997 }
Eric Laurent21da6472017-11-09 16:29:26 -08001998
1999 if (!audio_has_proportional_frames(format)) {
2000 if (sharedBuffer != 0) {
2001 // Same comment as below about ignoring frameCount parameter for set()
2002 frameCount = sharedBuffer->size();
2003 } else if (frameCount == 0) {
2004 frameCount = mNormalFrameCount;
2005 }
2006 if (notificationFrameCount != frameCount) {
2007 notificationFrameCount = frameCount;
2008 }
2009 } else if (sharedBuffer != 0) {
2010 // FIXME: Ensure client side memory buffers need
2011 // not have additional alignment beyond sample
2012 // (e.g. 16 bit stereo accessed as 32 bit frame).
2013 size_t alignment = audio_bytes_per_sample(format);
2014 if (alignment & 1) {
2015 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2016 alignment = 1;
2017 }
2018 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2019 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2020 if (channelCount > 1) {
2021 // More than 2 channels does not require stronger alignment than stereo
2022 alignment <<= 1;
2023 }
2024 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2025 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2026 sharedBuffer->pointer(), channelCount);
2027 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002028 goto Exit;
2029 }
Eric Laurent21da6472017-11-09 16:29:26 -08002030
2031 // When initializing a shared buffer AudioTrack via constructors,
2032 // there's no frameCount parameter.
2033 // But when initializing a shared buffer AudioTrack via set(),
2034 // there _is_ a frameCount parameter. We silently ignore it.
2035 frameCount = sharedBuffer->size() / frameSize;
2036 } else {
2037 size_t minFrameCount = 0;
2038 // For fast tracks we try to respect the application's request for notifications per buffer.
2039 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2040 if (notificationsPerBuffer > 0) {
2041 // Avoid possible arithmetic overflow during multiplication.
2042 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2043 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2044 notificationsPerBuffer, mFrameCount);
2045 } else {
2046 minFrameCount = mFrameCount * notificationsPerBuffer;
2047 }
2048 }
2049 } else {
2050 // For normal PCM streaming tracks, update minimum frame count.
2051 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2052 // cover audio hardware latency.
2053 // This is probably too conservative, but legacy application code may depend on it.
2054 // If you change this calculation, also review the start threshold which is related.
2055 uint32_t latencyMs = latency_l();
2056 if (latencyMs == 0) {
2057 ALOGE("Error when retrieving output stream latency");
2058 lStatus = UNKNOWN_ERROR;
2059 goto Exit;
2060 }
2061
2062 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2063 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2064
Eric Laurent81784c32012-11-19 14:55:58 -08002065 }
Eric Laurent21da6472017-11-09 16:29:26 -08002066 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002067 frameCount = minFrameCount;
2068 }
Eric Laurent81784c32012-11-19 14:55:58 -08002069 }
Eric Laurent21da6472017-11-09 16:29:26 -08002070
2071 // Make sure that application is notified with sufficient margin before underrun.
2072 // The client can divide the AudioTrack buffer into sub-buffers,
2073 // and expresses its desire to server as the notification frame count.
2074 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2075 size_t maxNotificationFrames;
2076 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2077 // notify every HAL buffer, regardless of the size of the track buffer
2078 maxNotificationFrames = mFrameCount;
2079 } else {
2080 // For normal tracks, use at least double-buffering if no sample rate conversion,
2081 // or at least triple-buffering if there is sample rate conversion
2082 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2083 maxNotificationFrames = frameCount / nBuffering;
2084 // If client requested a fast track but this was denied, then use the smaller maximum.
2085 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2086 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2087 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2088 maxNotificationFrames = maxNotificationFramesFastDenied;
2089 }
2090 }
2091 }
2092 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2093 if (notificationFrameCount == 0) {
2094 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2095 maxNotificationFrames, frameCount);
2096 } else {
2097 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2098 notificationFrameCount, maxNotificationFrames, frameCount);
2099 }
2100 notificationFrameCount = maxNotificationFrames;
2101 }
2102 }
2103
Glenn Kasten74935e42013-12-19 08:56:45 -08002104 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002105 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002106
Glenn Kastenc3df8382014-03-13 15:05:25 -07002107 switch (mType) {
2108
2109 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002110 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002111 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002112 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2113 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002114 sampleRate, format, channelMask, mOutput, mFormat);
2115 lStatus = BAD_VALUE;
2116 goto Exit;
2117 }
2118 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002119 break;
2120
2121 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002122 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002123 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2124 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002125 sampleRate, format, channelMask, mOutput, mFormat);
2126 lStatus = BAD_VALUE;
2127 goto Exit;
2128 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002129 break;
2130
2131 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002132 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002133 ALOGE("createTrack_l() Bad parameter: format %#x \""
2134 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 format, mOutput, mFormat);
2136 lStatus = BAD_VALUE;
2137 goto Exit;
2138 }
Andy Hungcd044842014-08-07 11:04:34 -07002139 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002140 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2141 lStatus = BAD_VALUE;
2142 goto Exit;
2143 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002144 break;
2145
Eric Laurent81784c32012-11-19 14:55:58 -08002146 }
2147
2148 lStatus = initCheck();
2149 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002150 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002151 goto Exit;
2152 }
2153
2154 { // scope for mLock
2155 Mutex::Autolock _l(mLock);
2156
2157 // all tracks in same audio session must share the same routing strategy otherwise
2158 // conflicts will happen when tracks are moved from one output to another by audio policy
2159 // manager
2160 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2161 for (size_t i = 0; i < mTracks.size(); ++i) {
2162 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002163 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002164 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2165 if (sessionId == t->sessionId() && strategy != actual) {
2166 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2167 strategy, actual);
2168 lStatus = BAD_VALUE;
2169 goto Exit;
2170 }
2171 }
2172 }
2173
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002174 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002175 channelMask, frameCount,
2176 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002177 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002178
Glenn Kasten03003332013-08-06 15:40:54 -07002179 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2180 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002181 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002182 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002183 goto Exit;
2184 }
2185 mTracks.add(track);
2186
2187 sp<EffectChain> chain = getEffectChain_l(sessionId);
2188 if (chain != 0) {
2189 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2190 track->setMainBuffer(chain->inBuffer());
2191 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2192 chain->incTrackCnt();
2193 }
2194
Eric Laurent05067782016-06-01 18:27:28 -07002195 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002196 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2197 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2198 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002199 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002200 }
2201 }
2202
2203 lStatus = NO_ERROR;
2204
2205Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002206 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002207 return track;
2208}
2209
Andy Hung1bc088a2018-02-09 15:57:31 -08002210template<typename T>
2211ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2212{
2213 const ssize_t index = mTracks.add(track);
2214 if (index >= 0) {
2215 // set name for track when adding.
2216 int name;
2217 if (mUnusedTrackNames.empty()) {
2218 name = mTracks.size() - 1; // new name {0 ... size-1}.
2219 } else {
2220 // reuse smallest name for deleted track.
2221 auto it = mUnusedTrackNames.begin();
2222 name = *it;
2223 (void)mUnusedTrackNames.erase(it);
2224 }
2225 track->setName(name);
2226 } else {
2227 LOG_ALWAYS_FATAL("cannot add track");
2228 }
2229 return index;
2230}
2231
2232template<typename T>
2233ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2234{
2235 const int name = track->name();
2236 const ssize_t index = mTracks.remove(track);
2237 if (index >= 0) {
2238 // invalidate name when removing from mTracks.
2239 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2240
2241 if (mSaveDeletedTrackNames) {
2242 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2243 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2244 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2245 mDeletedTrackNames.emplace(name);
2246 }
2247
2248 mUnusedTrackNames.emplace(name);
2249 track->setName(T::TRACK_NAME_PENDING);
2250 } else {
2251 LOG_ALWAYS_FATAL_IF(name >= 0,
2252 "valid name %d for track not in mTracks (returned %zd)", name, index);
2253 }
2254 return index;
2255}
2256
Eric Laurent81784c32012-11-19 14:55:58 -08002257uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2258{
2259 return latency;
2260}
2261
2262uint32_t AudioFlinger::PlaybackThread::latency() const
2263{
2264 Mutex::Autolock _l(mLock);
2265 return latency_l();
2266}
2267uint32_t AudioFlinger::PlaybackThread::latency_l() const
2268{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002269 uint32_t latency;
2270 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2271 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002272 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002273 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002274}
2275
2276void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2277{
2278 Mutex::Autolock _l(mLock);
2279 // Don't apply master volume in SW if our HAL can do it for us.
2280 if (mOutput && mOutput->audioHwDev &&
2281 mOutput->audioHwDev->canSetMasterVolume()) {
2282 mMasterVolume = 1.0;
2283 } else {
2284 mMasterVolume = value;
2285 }
2286}
2287
2288void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2289{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002290 if (isDuplicating()) {
2291 return;
2292 }
Eric Laurent81784c32012-11-19 14:55:58 -08002293 Mutex::Autolock _l(mLock);
2294 // Don't apply master mute in SW if our HAL can do it for us.
2295 if (mOutput && mOutput->audioHwDev &&
2296 mOutput->audioHwDev->canSetMasterMute()) {
2297 mMasterMute = false;
2298 } else {
2299 mMasterMute = muted;
2300 }
2301}
2302
2303void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2304{
2305 Mutex::Autolock _l(mLock);
2306 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002307 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002308}
2309
2310void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2311{
2312 Mutex::Autolock _l(mLock);
2313 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002314 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002315}
2316
2317float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2318{
2319 Mutex::Autolock _l(mLock);
2320 return mStreamTypes[stream].volume;
2321}
2322
2323// addTrack_l() must be called with ThreadBase::mLock held
2324status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2325{
2326 status_t status = ALREADY_EXISTS;
2327
Eric Laurent81784c32012-11-19 14:55:58 -08002328 if (mActiveTracks.indexOf(track) < 0) {
2329 // the track is newly added, make sure it fills up all its
2330 // buffers before playing. This is to ensure the client will
2331 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002332 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333 TrackBase::track_state state = track->mState;
2334 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002335 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002336 mLock.lock();
2337 // abort track was stopped/paused while we released the lock
2338 if (state != track->mState) {
2339 if (status == NO_ERROR) {
2340 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002341 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002342 mLock.lock();
2343 }
2344 return INVALID_OPERATION;
2345 }
2346 // abort if start is rejected by audio policy manager
2347 if (status != NO_ERROR) {
2348 return PERMISSION_DENIED;
2349 }
2350#ifdef ADD_BATTERY_DATA
2351 // to track the speaker usage
2352 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2353#endif
2354 }
2355
Eric Laurent51716182016-02-29 18:00:56 -08002356 // set retry count for buffer fill
2357 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002358 if (track->isStopping_1()) {
2359 track->mRetryCount = kMaxTrackStopRetriesOffload;
2360 } else {
2361 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2362 }
2363 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002364 } else {
2365 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002366 track->mFillingUpStatus =
2367 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002368 }
2369
Eric Laurent81784c32012-11-19 14:55:58 -08002370 track->mResetDone = false;
2371 track->mPresentationCompleteFrames = 0;
2372 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002373 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2374 if (chain != 0) {
2375 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2376 track->sessionId());
2377 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002378 }
2379
2380 status = NO_ERROR;
2381 }
2382
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002383 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002384 return status;
2385}
2386
Eric Laurentbfb1b832013-01-07 09:53:42 -08002387bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002388{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002390 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002391 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2392 track->mState = TrackBase::STOPPED;
2393 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002394 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002395 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002396 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002397 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002398
2399 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002400}
2401
2402void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2403{
2404 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002405
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002406 String8 result;
2407 track->appendDump(result, false /* active */);
2408 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002409
Eric Laurent81784c32012-11-19 14:55:58 -08002410 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002411 if (track->isFastTrack()) {
2412 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002413 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002414 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2415 mFastTrackAvailMask |= 1 << index;
2416 // redundant as track is about to be destroyed, for dumpsys only
2417 track->mFastIndex = -1;
2418 }
2419 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2420 if (chain != 0) {
2421 chain->decTrackCnt();
2422 }
2423}
2424
2425String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2426{
Eric Laurent81784c32012-11-19 14:55:58 -08002427 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002428 String8 out_s8;
2429 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2430 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002431 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002432 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002433}
2434
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002435void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002436 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2437 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002438
Eric Laurent73e26b62015-04-27 16:55:58 -07002439 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002440
2441 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002442 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002443 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002444 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002445 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002446 desc->mChannelMask = mChannelMask;
2447 desc->mSamplingRate = mSampleRate;
2448 desc->mFormat = mFormat;
2449 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002451 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002452 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002453 break;
2454
Eric Laurent73e26b62015-04-27 16:55:58 -07002455 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002456 default:
2457 break;
2458 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002459 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002460}
2461
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002462void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002464 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002465}
2466
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002467void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002468{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002469 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002470}
2471
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002472void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002473{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002474 mCallbackThread->setAsyncError();
2475}
2476
Eric Laurent3b4529e2013-09-05 18:09:19 -07002477void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002478{
2479 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002480 // reject out of sequence requests
2481 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2482 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002483 mWaitWorkCV.signal();
2484 }
2485}
2486
Eric Laurent3b4529e2013-09-05 18:09:19 -07002487void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002488{
2489 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002490 // reject out of sequence requests
2491 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002492 // Register discontinuity when HW drain is completed because that can cause
2493 // the timestamp frame position to reset to 0 for direct and offload threads.
2494 // (Out of sequence requests are ignored, since the discontinuity would be handled
2495 // elsewhere, e.g. in flush).
2496 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002497 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002498 mWaitWorkCV.signal();
2499 }
2500}
2501
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002502void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002503{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002504 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002505 mSampleRate = mOutput->getSampleRate();
2506 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002507 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002508 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002509 }
Andy Hung9a592762014-07-21 21:56:01 -07002510 if ((mType == MIXER || mType == DUPLICATING)
2511 && !isValidPcmSinkChannelMask(mChannelMask)) {
2512 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2513 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002514 }
Andy Hunge5412692014-05-16 11:25:07 -07002515 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002516
2517 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002518 status_t result = mOutput->stream->getFormat(&mHALFormat);
2519 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002520 // Get format from the shim, which will be different than the HAL format
2521 // if playing compressed audio over HDMI passthrough.
2522 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002523 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002524 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002525 }
Andy Hung6146c082014-03-18 11:56:15 -07002526 if ((mType == MIXER || mType == DUPLICATING)
2527 && !isValidPcmSinkFormat(mFormat)) {
2528 LOG_FATAL("HAL format %#x not supported for mixed output",
2529 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002530 }
Phil Burk062e67a2015-02-11 13:40:50 -08002531 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002532 result = mOutput->stream->getBufferSize(&mBufferSize);
2533 LOG_ALWAYS_FATAL_IF(result != OK,
2534 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002535 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002536 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002537 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002538 mFrameCount);
2539 }
2540
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002541 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2542 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002543 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002544 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002545 }
2546 }
2547
Eric Laurentd1f69b02014-12-15 14:33:13 -08002548 mHwSupportsPause = false;
2549 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002550 bool supportsPause = false, supportsResume = false;
2551 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2552 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002553 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002554 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002555 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002556 } else if (supportsResume) {
2557 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002558 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002559 }
2560 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002561 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2562 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2563 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002564
Andy Hungfbfc3952015-01-15 13:33:51 -08002565 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2566 // For best precision, we use float instead of the associated output
2567 // device format (typically PCM 16 bit).
2568
2569 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2570 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2571 mBufferSize = mFrameSize * mFrameCount;
2572
2573 // TODO: We currently use the associated output device channel mask and sample rate.
2574 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2575 // (if a valid mask) to avoid premature downmix.
2576 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2577 // instead of the output device sample rate to avoid loss of high frequency information.
2578 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2579 }
2580
Andy Hung09a50072014-02-27 14:30:47 -08002581 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002582 double multiplier = 1.0;
2583 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2584 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002585 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2586 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002587
Eric Laurent81784c32012-11-19 14:55:58 -08002588 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2589 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2590 maxNormalFrameCount = maxNormalFrameCount & ~15;
2591 if (maxNormalFrameCount < minNormalFrameCount) {
2592 maxNormalFrameCount = minNormalFrameCount;
2593 }
2594 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2595 if (multiplier <= 1.0) {
2596 multiplier = 1.0;
2597 } else if (multiplier <= 2.0) {
2598 if (2 * mFrameCount <= maxNormalFrameCount) {
2599 multiplier = 2.0;
2600 } else {
2601 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2602 }
2603 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002604 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002605 }
2606 }
2607 mNormalFrameCount = multiplier * mFrameCount;
2608 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002609 if (mType == MIXER || mType == DUPLICATING) {
2610 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2611 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002612 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002613 mNormalFrameCount);
2614
Andy Hung08fb1742015-05-31 23:22:10 -07002615 // Check if we want to throttle the processing to no more than 2x normal rate
2616 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002617 mThreadThrottleTimeMs = 0;
2618 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002619 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2620
Andy Hung010a1a12014-03-13 13:57:33 -07002621 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2622 // Originally this was int16_t[] array, need to remove legacy implications.
2623 free(mSinkBuffer);
2624 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002625 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2626 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2627 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002628 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002629
Andy Hung69aed5f2014-02-25 17:24:40 -08002630 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2631 // drives the output.
2632 free(mMixerBuffer);
2633 mMixerBuffer = NULL;
2634 if (mMixerBufferEnabled) {
2635 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2636 mMixerBufferSize = mNormalFrameCount * mChannelCount
2637 * audio_bytes_per_sample(mMixerBufferFormat);
2638 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2639 }
Andy Hung98ef9782014-03-04 14:46:50 -08002640 free(mEffectBuffer);
2641 mEffectBuffer = NULL;
2642 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002643 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002644 mEffectBufferSize = mNormalFrameCount * mChannelCount
2645 * audio_bytes_per_sample(mEffectBufferFormat);
2646 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2647 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002648
Eric Laurent81784c32012-11-19 14:55:58 -08002649 // force reconfiguration of effect chains and engines to take new buffer size and audio
2650 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002651 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002652 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2653 // matter.
2654 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2655 Vector< sp<EffectChain> > effectChains = mEffectChains;
2656 for (size_t i = 0; i < effectChains.size(); i ++) {
2657 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2658 }
2659}
2660
Kevin Rocard069c2712018-03-29 19:09:14 -07002661void AudioFlinger::PlaybackThread::updateMetadata_l()
2662{
Kevin Rocard12381092018-04-11 09:19:59 -07002663 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2664 return; // That should not happen
2665 }
2666 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2667 for (const sp<Track> &track : mActiveTracks) {
2668 // Do not short-circuit as all hasChanged states must be reset
2669 // as all the metadata are going to be sent
2670 hasChanged |= track->readAndClearHasChanged();
2671 }
2672 if (!hasChanged) {
2673 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002674 }
2675 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002676 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002677 for (const sp<Track> &track : mActiveTracks) {
2678 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002679 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002680 }
Kevin Rocard12381092018-04-11 09:19:59 -07002681 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002682}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002683
Kevin Rocard12381092018-04-11 09:19:59 -07002684void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2685 const StreamOutHalInterface::SourceMetadata& metadata)
2686{
2687 mOutput->stream->updateSourceMetadata(metadata);
2688};
2689
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002690status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002691{
2692 if (halFrames == NULL || dspFrames == NULL) {
2693 return BAD_VALUE;
2694 }
2695 Mutex::Autolock _l(mLock);
2696 if (initCheck() != NO_ERROR) {
2697 return INVALID_OPERATION;
2698 }
Andy Hung818e7a32016-02-16 18:08:07 -08002699 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002700 *halFrames = framesWritten;
2701
2702 if (isSuspended()) {
2703 // return an estimation of rendered frames when the output is suspended
2704 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002705 *dspFrames = (uint32_t)
2706 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002707 return NO_ERROR;
2708 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002709 status_t status;
2710 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002711 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002712 *dspFrames = (size_t)frames;
2713 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002714 }
2715}
2716
Eric Laurent4c415062016-06-17 16:14:16 -07002717// hasAudioSession_l() must be called with ThreadBase::mLock held
2718uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002719{
Eric Laurent81784c32012-11-19 14:55:58 -08002720 uint32_t result = 0;
2721 if (getEffectChain_l(sessionId) != 0) {
2722 result = EFFECT_SESSION;
2723 }
2724
2725 for (size_t i = 0; i < mTracks.size(); ++i) {
2726 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002727 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002728 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002729 if (track->isFastTrack()) {
2730 result |= FAST_SESSION;
2731 }
Eric Laurent81784c32012-11-19 14:55:58 -08002732 break;
2733 }
2734 }
2735
2736 return result;
2737}
2738
Glenn Kastend848eb42016-03-08 13:42:11 -08002739uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002740{
2741 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2742 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2743 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2744 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2745 }
2746 for (size_t i = 0; i < mTracks.size(); i++) {
2747 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002748 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002749 return AudioSystem::getStrategyForStream(track->streamType());
2750 }
2751 }
2752 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2753}
2754
2755
Phil Burk062e67a2015-02-11 13:40:50 -08002756AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002757{
2758 Mutex::Autolock _l(mLock);
2759 return mOutput;
2760}
2761
Phil Burk062e67a2015-02-11 13:40:50 -08002762AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002763{
2764 Mutex::Autolock _l(mLock);
2765 AudioStreamOut *output = mOutput;
2766 mOutput = NULL;
2767 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2768 // must push a NULL and wait for ack
2769 mOutputSink.clear();
2770 mPipeSink.clear();
2771 mNormalSink.clear();
2772 return output;
2773}
2774
2775// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002776sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002777{
2778 if (mOutput == NULL) {
2779 return NULL;
2780 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002781 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002782}
2783
2784uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2785{
2786 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2787}
2788
2789status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2790{
2791 if (!isValidSyncEvent(event)) {
2792 return BAD_VALUE;
2793 }
2794
2795 Mutex::Autolock _l(mLock);
2796
2797 for (size_t i = 0; i < mTracks.size(); ++i) {
2798 sp<Track> track = mTracks[i];
2799 if (event->triggerSession() == track->sessionId()) {
2800 (void) track->setSyncEvent(event);
2801 return NO_ERROR;
2802 }
2803 }
2804
2805 return NAME_NOT_FOUND;
2806}
2807
2808bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2809{
2810 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2811}
2812
2813void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2814 const Vector< sp<Track> >& tracksToRemove)
2815{
2816 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002817 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002818 for (size_t i = 0 ; i < count ; i++) {
2819 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002820 if (track->isExternalTrack()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002821 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002822#ifdef ADD_BATTERY_DATA
2823 // to track the speaker usage
2824 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2825#endif
2826 if (track->isTerminated()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002827 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002828 }
Eric Laurent81784c32012-11-19 14:55:58 -08002829 }
2830 }
2831 }
Eric Laurent81784c32012-11-19 14:55:58 -08002832}
2833
2834void AudioFlinger::PlaybackThread::checkSilentMode_l()
2835{
2836 if (!mMasterMute) {
2837 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002838 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2839 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2840 return;
2841 }
Eric Laurent81784c32012-11-19 14:55:58 -08002842 if (property_get("ro.audio.silent", value, "0") > 0) {
2843 char *endptr;
2844 unsigned long ul = strtoul(value, &endptr, 0);
2845 if (*endptr == '\0' && ul != 0) {
2846 ALOGD("Silence is golden");
2847 // The setprop command will not allow a property to be changed after
2848 // the first time it is set, so we don't have to worry about un-muting.
2849 setMasterMute_l(true);
2850 }
2851 }
2852 }
2853}
2854
2855// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002857{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002858 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002859 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002861 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002862
2863 // If an NBAIO sink is present, use it to write the normal mixer's submix
2864 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002865
Andy Hung010a1a12014-03-13 13:57:33 -07002866 const size_t count = mBytesRemaining / mFrameSize;
2867
Simon Wilson2d590962012-11-29 15:18:50 -08002868 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002869 // update the setpoint when AudioFlinger::mScreenState changes
2870 uint32_t screenState = AudioFlinger::mScreenState;
2871 if (screenState != mScreenState) {
2872 mScreenState = screenState;
2873 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2874 if (pipe != NULL) {
2875 pipe->setAvgFrames((mScreenState & 1) ?
2876 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2877 }
2878 }
Andy Hung010a1a12014-03-13 13:57:33 -07002879 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002880 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002881 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002882 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002883#ifdef TEE_SINK
2884 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2885#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002886 } else {
2887 bytesWritten = framesWritten;
2888 }
2889 // otherwise use the HAL / AudioStreamOut directly
2890 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002892
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002894 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2895 mWriteAckSequence += 2;
2896 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002898 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002900 // FIXME We should have an implementation of timestamps for direct output threads.
2901 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002902 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002903
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 if (mUseAsyncWrite &&
2905 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2906 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002907 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002909 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910 }
Eric Laurent81784c32012-11-19 14:55:58 -08002911 }
2912
Eric Laurent81784c32012-11-19 14:55:58 -08002913 mNumWrites++;
2914 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002915 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002916 return bytesWritten;
2917}
2918
2919void AudioFlinger::PlaybackThread::threadLoop_drain()
2920{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002921 bool supportsDrain = false;
2922 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2924 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002925 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2926 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002927 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002928 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002929 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002930 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002931 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002932 }
2933}
2934
2935void AudioFlinger::PlaybackThread::threadLoop_exit()
2936{
Eric Laurent275e8e92014-11-30 15:14:47 -08002937 {
2938 Mutex::Autolock _l(mLock);
2939 for (size_t i = 0; i < mTracks.size(); i++) {
2940 sp<Track> track = mTracks[i];
2941 track->invalidate();
2942 }
Andy Hungdae27702016-10-31 14:01:16 -07002943 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2944 // After we exit there are no more track changes sent to BatteryNotifier
2945 // because that requires an active threadLoop.
2946 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2947 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002948 }
Eric Laurent81784c32012-11-19 14:55:58 -08002949}
2950
2951/*
2952The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002953 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002954 - mActiveSleepTimeUs from activeSleepTimeUs()
2955 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002956 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2957 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002958 - maxPeriod from frame count and sample rate (MIXER only)
2959
2960The parameters that affect these derived values are:
2961 - frame count
2962 - frame size
2963 - sample rate
2964 - device type: A2DP or not
2965 - device latency
2966 - format: PCM or not
2967 - active sleep time
2968 - idle sleep time
2969*/
2970
2971void AudioFlinger::PlaybackThread::cacheParameters_l()
2972{
Andy Hung25c2dac2014-02-27 14:56:00 -08002973 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002974 mActiveSleepTimeUs = activeSleepTimeUs();
2975 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002976
2977 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2978 // truncating audio when going to standby.
2979 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2980 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2981 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2982 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2983 }
2984 }
Eric Laurent81784c32012-11-19 14:55:58 -08002985}
2986
Eric Laurent13084622016-05-17 10:51:49 -07002987bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002988{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002989 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002990 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002991 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002992 size_t size = mTracks.size();
2993 for (size_t i = 0; i < size; i++) {
2994 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002995 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002996 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002997 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002998 }
2999 }
Eric Laurent13084622016-05-17 10:51:49 -07003000 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003001}
3002
Haynes Mathew George05317d22016-05-03 16:34:26 -07003003void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3004{
3005 Mutex::Autolock _l(mLock);
3006 invalidateTracks_l(streamType);
3007}
3008
Eric Laurent81784c32012-11-19 14:55:58 -08003009status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3010{
Glenn Kastend848eb42016-03-08 13:42:11 -08003011 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003012 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003013 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003014 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3015 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3016 &halInBuffer);
3017 if (result != OK) return result;
3018 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003019 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003020 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003021 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003022 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003023 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003024 if (mType != DIRECT) {
3025 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003026 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003027 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003028 &halInBuffer);
3029 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003030#ifdef FLOAT_EFFECT_CHAIN
3031 buffer = halInBuffer->audioBuffer()->f32;
3032#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003033 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003034#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003035 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3036 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003037 }
3038
3039 // Attach all tracks with same session ID to this chain.
3040 for (size_t i = 0; i < mTracks.size(); ++i) {
3041 sp<Track> track = mTracks[i];
3042 if (session == track->sessionId()) {
3043 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3044 buffer);
3045 track->setMainBuffer(buffer);
3046 chain->incTrackCnt();
3047 }
3048 }
3049
3050 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003051 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003052 if (session == track->sessionId()) {
3053 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3054 chain->incActiveTrackCnt();
3055 }
3056 }
3057 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003058 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003059 chain->setInBuffer(halInBuffer);
3060 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003061 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003062 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003063 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3064 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003065 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003066 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003067 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003068 // Effect chain for other sessions are inserted at beginning of effect
3069 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003070 // sessions is not important.
3071 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3072 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3073 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003074 size_t size = mEffectChains.size();
3075 size_t i = 0;
3076 for (i = 0; i < size; i++) {
3077 if (mEffectChains[i]->sessionId() < session) {
3078 break;
3079 }
3080 }
3081 mEffectChains.insertAt(chain, i);
3082 checkSuspendOnAddEffectChain_l(chain);
3083
3084 return NO_ERROR;
3085}
3086
3087size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3088{
Glenn Kastend848eb42016-03-08 13:42:11 -08003089 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003090
3091 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3092
3093 for (size_t i = 0; i < mEffectChains.size(); i++) {
3094 if (chain == mEffectChains[i]) {
3095 mEffectChains.removeAt(i);
3096 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003097 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003098 if (session == track->sessionId()) {
3099 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3100 chain.get(), session);
3101 chain->decActiveTrackCnt();
3102 }
3103 }
3104
3105 // detach all tracks with same session ID from this chain
3106 for (size_t i = 0; i < mTracks.size(); ++i) {
3107 sp<Track> track = mTracks[i];
3108 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003109 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003110 chain->decTrackCnt();
3111 }
3112 }
3113 break;
3114 }
3115 }
3116 return mEffectChains.size();
3117}
3118
3119status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003120 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003121{
3122 Mutex::Autolock _l(mLock);
3123 return attachAuxEffect_l(track, EffectId);
3124}
3125
3126status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003127 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003128{
3129 status_t status = NO_ERROR;
3130
3131 if (EffectId == 0) {
3132 track->setAuxBuffer(0, NULL);
3133 } else {
3134 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3135 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3136 if (effect != 0) {
3137 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3138 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3139 } else {
3140 status = INVALID_OPERATION;
3141 }
3142 } else {
3143 status = BAD_VALUE;
3144 }
3145 }
3146 return status;
3147}
3148
3149void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3150{
3151 for (size_t i = 0; i < mTracks.size(); ++i) {
3152 sp<Track> track = mTracks[i];
3153 if (track->auxEffectId() == effectId) {
3154 attachAuxEffect_l(track, 0);
3155 }
3156 }
3157}
3158
3159bool AudioFlinger::PlaybackThread::threadLoop()
3160{
Glenn Kasten388d5712017-04-07 14:38:41 -07003161 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003162
Eric Laurent81784c32012-11-19 14:55:58 -08003163 Vector< sp<Track> > tracksToRemove;
3164
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003165 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003166 nsecs_t lastWriteFinished = -1; // time last server write completed
3167 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003168
3169 // MIXER
3170 nsecs_t lastWarning = 0;
3171
3172 // DUPLICATING
3173 // FIXME could this be made local to while loop?
3174 writeFrames = 0;
3175
3176 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003177 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003178
3179 if (mType == MIXER) {
3180 sleepTimeShift = 0;
3181 }
3182
3183 CpuStats cpuStats;
3184 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3185
3186 acquireWakeLock();
3187
Glenn Kasteneef598c2017-04-03 14:41:13 -07003188 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3189 // thread associated with this PlaybackThread.
3190 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3191 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003192 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3193 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003194 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003195 const char *logString = NULL;
3196
rago1bb90822017-05-02 18:31:48 -07003197 // Estimated time for next buffer to be written to hal. This is used only on
3198 // suspended mode (for now) to help schedule the wait time until next iteration.
3199 nsecs_t timeLoopNextNs = 0;
3200
Eric Laurent664539d2013-09-23 18:24:31 -07003201 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003202
Andy Hungf3234512018-07-03 14:51:47 -07003203 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3204 // TODO: add confirmation checks:
3205 // 1) DIRECT threads and linear PCM format really resets to 0?
3206 // 2) Is frame count really valid if not linear pcm?
3207 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3208 if (mType == OFFLOAD || mType == DIRECT) {
3209 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3210 }
3211
Eric Laurent81784c32012-11-19 14:55:58 -08003212 while (!exitPending())
3213 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003214 // Log merge requests are performed during AudioFlinger binder transactions, but
3215 // that does not cover audio playback. It's requested here for that reason.
3216 mAudioFlinger->requestLogMerge();
3217
Eric Laurent81784c32012-11-19 14:55:58 -08003218 cpuStats.sample(myName);
3219
3220 Vector< sp<EffectChain> > effectChains;
3221
Eric Laurent81784c32012-11-19 14:55:58 -08003222 { // scope for mLock
3223
3224 Mutex::Autolock _l(mLock);
3225
Eric Laurent021cf962014-05-13 10:18:14 -07003226 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003227
Glenn Kasteneef598c2017-04-03 14:41:13 -07003228 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003229 if (logString != NULL) {
3230 mNBLogWriter->logTimestamp();
3231 mNBLogWriter->log(logString);
3232 logString = NULL;
3233 }
3234
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003235 // Collect timestamp statistics for the Playback Thread types that support it.
3236 if (mType == MIXER
3237 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003238 || mType == DIRECT
3239 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003240 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003241 // and associate with the sink frames written out. We need
3242 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003243 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003244 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003245 if (mStandby) {
3246 mTimestampVerifier.discontinuity();
3247 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3248 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3249 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3250 mSampleRate);
Andy Hung818e7a32016-02-16 18:08:07 -08003251 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003252 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003253
3254 // We keep track of the last valid kernel position in case we are in underrun
3255 // and the normal mixer period is the same as the fast mixer period, or there
3256 // is some error from the HAL.
3257 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3258 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3259 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3260 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3261 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3262
3263 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3264 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3265 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3266 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003267 }
3268
3269 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3270 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003271 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003272 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003273 }
3274
Andy Hung818e7a32016-02-16 18:08:07 -08003275 // copy over kernel info
3276 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003277 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3278 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003279 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3280 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003281 } else {
3282 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003283 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003284
Andy Hungc54b1ff2016-02-23 14:07:07 -08003285 // mFramesWritten for non-offloaded tracks are contiguous
3286 // even after standby() is called. This is useful for the track frame
3287 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003288 bool serverLocationUpdate = false;
3289 if (mFramesWritten != lastFramesWritten) {
3290 serverLocationUpdate = true;
3291 lastFramesWritten = mFramesWritten;
3292 }
3293 // Only update timestamps if there is a meaningful change.
3294 // Either the kernel timestamp must be valid or we have written something.
3295 if (kernelLocationUpdate || serverLocationUpdate) {
3296 if (serverLocationUpdate) {
3297 // use the time before we called the HAL write - it is a bit more accurate
3298 // to when the server last read data than the current time here.
3299 //
3300 // If we haven't written anything, mLastWriteTime will be -1
3301 // and we use systemTime().
3302 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3303 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3304 ? systemTime() : mLastWriteTime;
3305 }
Andy Hungdae27702016-10-31 14:01:16 -07003306
3307 for (const sp<Track> &t : mActiveTracks) {
3308 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003309 t->updateTrackFrameInfo(
3310 t->mAudioTrackServerProxy->framesReleased(),
3311 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003312 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003313 mTimestamp);
3314 }
Andy Hunge10393e2015-06-12 13:59:33 -07003315 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003316 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003317 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003318#if 0
3319 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003320 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003321 timespec ts;
3322 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003323 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003324 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003325 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003326 }
3327 ++z;
3328#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003329 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003330 if (mSignalPending) {
3331 // A signal was raised while we were unlocked
3332 mSignalPending = false;
3333 } else if (waitingAsyncCallback_l()) {
3334 if (exitPending()) {
3335 break;
3336 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003337 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003338 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003339 releaseWakeLock_l();
3340 released = true;
3341 }
Andy Hung10cbff12017-02-21 17:30:14 -08003342
3343 const int64_t waitNs = computeWaitTimeNs_l();
3344 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3345 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3346 if (status == TIMED_OUT) {
3347 mSignalPending = true; // if timeout recheck everything
3348 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003349 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003350 if (released) {
3351 acquireWakeLock_l();
3352 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003353 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3354 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003355
3356 continue;
3357 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003358 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003359 isSuspended()) {
3360 // put audio hardware into standby after short delay
3361 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003362
3363 threadLoop_standby();
3364
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003365 // This is where we go into standby
3366 if (!mStandby) {
3367 LOG_AUDIO_STATE();
3368 }
Eric Laurent81784c32012-11-19 14:55:58 -08003369 mStandby = true;
3370 }
3371
Eric Tan39ec8d62018-07-24 09:49:29 -07003372 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003373 // we're about to wait, flush the binder command buffer
3374 IPCThreadState::self()->flushCommands();
3375
3376 clearOutputTracks();
3377
3378 if (exitPending()) {
3379 break;
3380 }
3381
3382 releaseWakeLock_l();
3383 // wait until we have something to do...
3384 ALOGV("%s going to sleep", myName.string());
3385 mWaitWorkCV.wait(mLock);
3386 ALOGV("%s waking up", myName.string());
3387 acquireWakeLock_l();
3388
3389 mMixerStatus = MIXER_IDLE;
3390 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3391 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003392 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003393 checkSilentMode_l();
3394
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003395 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3396 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003397 if (mType == MIXER) {
3398 sleepTimeShift = 0;
3399 }
3400
3401 continue;
3402 }
3403 }
Eric Laurent81784c32012-11-19 14:55:58 -08003404 // mMixerStatusIgnoringFastTracks is also updated internally
3405 mMixerStatus = prepareTracks_l(&tracksToRemove);
3406
Andy Hungdae27702016-10-31 14:01:16 -07003407 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003408
Kevin Rocard069c2712018-03-29 19:09:14 -07003409 updateMetadata_l();
3410
Eric Laurent81784c32012-11-19 14:55:58 -08003411 // prevent any changes in effect chain list and in each effect chain
3412 // during mixing and effect process as the audio buffers could be deleted
3413 // or modified if an effect is created or deleted
3414 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003415 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003416
Eric Laurentbfb1b832013-01-07 09:53:42 -08003417 if (mBytesRemaining == 0) {
3418 mCurrentWriteLength = 0;
3419 if (mMixerStatus == MIXER_TRACKS_READY) {
3420 // threadLoop_mix() sets mCurrentWriteLength
3421 threadLoop_mix();
3422 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3423 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003424 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003425 // must be written to HAL
3426 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003427 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003428 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003429 }
3430 }
Andy Hung98ef9782014-03-04 14:46:50 -08003431 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003432 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003433 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3434 // or mSinkBuffer (if there are no effects).
3435 //
3436 // This is done pre-effects computation; if effects change to
3437 // support higher precision, this needs to move.
3438 //
3439 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003440 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003441 if (mMixerBufferValid) {
3442 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3443 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3444
Andy Hung2ddee192015-12-18 17:34:44 -08003445 // mono blend occurs for mixer threads only (not direct or offloaded)
3446 // and is handled here if we're going directly to the sink.
3447 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003448 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3449 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003450 }
3451
Andy Hung98ef9782014-03-04 14:46:50 -08003452 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3453 mNormalFrameCount * mChannelCount);
3454 }
3455
Eric Laurentbfb1b832013-01-07 09:53:42 -08003456 mBytesRemaining = mCurrentWriteLength;
3457 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003458 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3459 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3460 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3461 mBytesWritten += mBytesRemaining;
3462 mFramesWritten += framesRemaining;
3463 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003464 mBytesRemaining = 0;
3465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466
Eric Laurentbfb1b832013-01-07 09:53:42 -08003467 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003468 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003469 for (size_t i = 0; i < effectChains.size(); i ++) {
3470 effectChains[i]->process_l();
3471 }
Eric Laurent81784c32012-11-19 14:55:58 -08003472 }
3473 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003474 // Process effect chains for offloaded thread even if no audio
3475 // was read from audio track: process only updates effect state
3476 // and thus does have to be synchronized with audio writes but may have
3477 // to be called while waiting for async write callback
3478 if (mType == OFFLOAD) {
3479 for (size_t i = 0; i < effectChains.size(); i ++) {
3480 effectChains[i]->process_l();
3481 }
3482 }
Eric Laurent81784c32012-11-19 14:55:58 -08003483
Andy Hung98ef9782014-03-04 14:46:50 -08003484 // Only if the Effects buffer is enabled and there is data in the
3485 // Effects buffer (buffer valid), we need to
3486 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003487 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003488 if (mEffectBufferValid) {
3489 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003490
3491 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003492 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3493 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003494 }
3495
Andy Hung98ef9782014-03-04 14:46:50 -08003496 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3497 mNormalFrameCount * mChannelCount);
3498 }
3499
Eric Laurent81784c32012-11-19 14:55:58 -08003500 // enable changes in effect chain
3501 unlockEffectChains(effectChains);
3502
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003504 // mSleepTimeUs == 0 means we must write to audio hardware
3505 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003506 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003507 // We save lastWriteFinished here, as previousLastWriteFinished,
3508 // for throttling. On thread start, previousLastWriteFinished will be
3509 // set to -1, which properly results in no throttling after the first write.
3510 nsecs_t previousLastWriteFinished = lastWriteFinished;
3511 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003513 // FIXME rewrite to reduce number of system calls
3514 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003515 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003516 lastWriteFinished = systemTime();
3517 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518 if (ret < 0) {
3519 mBytesRemaining = 0;
3520 } else {
3521 mBytesWritten += ret;
3522 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003523 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003524 }
3525 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3526 (mMixerStatus == MIXER_DRAIN_ALL)) {
3527 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003528 }
Andy Hung08fb1742015-05-31 23:22:10 -07003529 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003530 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003531 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003532 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003533 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003534 ATRACE_NAME("underrun");
3535 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003536 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003537 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003538 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003539 }
Andy Hung08fb1742015-05-31 23:22:10 -07003540
3541 if (mThreadThrottle
3542 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3543 && ret > 0) { // we wrote something
3544 // Limit MixerThread data processing to no more than twice the
3545 // expected processing rate.
3546 //
3547 // This helps prevent underruns with NuPlayer and other applications
3548 // which may set up buffers that are close to the minimum size, or use
3549 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3550 //
3551 // The throttle smooths out sudden large data drains from the device,
3552 // e.g. when it comes out of standby, which often causes problems with
3553 // (1) mixer threads without a fast mixer (which has its own warm-up)
3554 // (2) minimum buffer sized tracks (even if the track is full,
3555 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003556 //
3557 // Total time spent in last processing cycle equals time spent in
3558 // 1. threadLoop_write, as well as time spent in
3559 // 2. threadLoop_mix (significant for heavy mixing, especially
3560 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003561
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003562 // it's OK if deltaMs (and deltaNs) is an overestimate.
3563 nsecs_t deltaNs;
3564 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3565 __builtin_sub_overflow(
3566 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3567 const int32_t deltaMs = deltaNs / 1000000;
3568
Ivan Lozanoea04d392017-11-07 14:37:07 -08003569 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003570 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3571 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003572 // notify of throttle start on verbose log
3573 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3574 "mixer(%p) throttle begin:"
3575 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003576 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003577 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003578 // Throttle must be attributed to the previous mixer loop's write time
3579 // to allow back-to-back throttling.
3580 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003581 } else {
3582 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3583 if (diff > 0) {
3584 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003585 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003586 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3587 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003588 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003589 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3590 }
Andy Hung08fb1742015-05-31 23:22:10 -07003591 }
3592 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003593 }
Eric Laurent81784c32012-11-19 14:55:58 -08003594
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003596 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003597 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003598 // suspended requires accurate metering of sleep time.
3599 if (isSuspended()) {
3600 // advance by expected sleepTime
3601 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3602 const nsecs_t nowNs = systemTime();
3603
3604 // compute expected next time vs current time.
3605 // (negative deltas are treated as delays).
3606 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3607 if (deltaNs < -kMaxNextBufferDelayNs) {
3608 // Delays longer than the max allowed trigger a reset.
3609 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3610 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3611 timeLoopNextNs = nowNs + deltaNs;
3612 } else if (deltaNs < 0) {
3613 // Delays within the max delay allowed: zero the delta/sleepTime
3614 // to help the system catch up in the next iteration(s)
3615 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3616 deltaNs = 0;
3617 }
3618 // update sleep time (which is >= 0)
3619 mSleepTimeUs = deltaNs / 1000;
3620 }
Eric Laurente93cc032016-05-05 10:15:10 -07003621 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3622 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003623 }
Glenn Kastene7754022014-10-31 12:11:26 -07003624 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003625 }
Eric Laurent81784c32012-11-19 14:55:58 -08003626 }
3627
3628 // Finally let go of removed track(s), without the lock held
3629 // since we can't guarantee the destructors won't acquire that
3630 // same lock. This will also mutate and push a new fast mixer state.
3631 threadLoop_removeTracks(tracksToRemove);
3632 tracksToRemove.clear();
3633
3634 // FIXME I don't understand the need for this here;
3635 // it was in the original code but maybe the
3636 // assignment in saveOutputTracks() makes this unnecessary?
3637 clearOutputTracks();
3638
3639 // Effect chains will be actually deleted here if they were removed from
3640 // mEffectChains list during mixing or effects processing
3641 effectChains.clear();
3642
3643 // FIXME Note that the above .clear() is no longer necessary since effectChains
3644 // is now local to this block, but will keep it for now (at least until merge done).
3645 }
3646
Eric Laurentbfb1b832013-01-07 09:53:42 -08003647 threadLoop_exit();
3648
Eric Laurentcf817a22014-08-04 20:36:31 -07003649 if (!mStandby) {
3650 threadLoop_standby();
3651 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003652 }
3653
3654 releaseWakeLock();
3655
3656 ALOGV("Thread %p type %d exiting", this, mType);
3657 return false;
3658}
3659
Eric Laurentbfb1b832013-01-07 09:53:42 -08003660// removeTracks_l() must be called with ThreadBase::mLock held
3661void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3662{
3663 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003664 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003665 for (size_t i=0 ; i<count ; i++) {
3666 const sp<Track>& track = tracksToRemove.itemAt(i);
3667 mActiveTracks.remove(track);
3668 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3669 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3670 if (chain != 0) {
3671 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3672 track->sessionId());
3673 chain->decActiveTrackCnt();
3674 }
3675 if (track->isTerminated()) {
3676 removeTrack_l(track);
3677 }
3678 }
3679 }
3680
3681}
Eric Laurent81784c32012-11-19 14:55:58 -08003682
Eric Laurentaccc1472013-09-20 09:36:34 -07003683status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3684{
3685 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003686 ExtendedTimestamp ets;
3687 status_t status = mNormalSink->getTimestamp(ets);
3688 if (status == NO_ERROR) {
3689 status = ets.getBestTimestamp(&timestamp);
3690 }
3691 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003692 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003693 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003694 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003695 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003696 timestamp.mPosition = (uint32_t)position64;
3697 return NO_ERROR;
3698 }
3699 }
3700 return INVALID_OPERATION;
3701}
Eric Laurent1c333e22014-05-20 10:48:17 -07003702
Eric Laurent054d9d32015-04-24 08:48:48 -07003703status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3704 audio_patch_handle_t *handle)
3705{
Andy Hungf60abce2016-08-26 11:37:54 -07003706 status_t status;
3707 if (property_get_bool("af.patch_park", false /* default_value */)) {
3708 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3709 // or if HAL does not properly lock against access.
3710 AutoPark<FastMixer> park(mFastMixer);
3711 status = PlaybackThread::createAudioPatch_l(patch, handle);
3712 } else {
3713 status = PlaybackThread::createAudioPatch_l(patch, handle);
3714 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003715 return status;
3716}
3717
Eric Laurent1c333e22014-05-20 10:48:17 -07003718status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3719 audio_patch_handle_t *handle)
3720{
3721 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003722
3723 // store new device and send to effects
3724 audio_devices_t type = AUDIO_DEVICE_NONE;
3725 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3726 type |= patch->sinks[i].ext.device.type;
3727 }
3728
3729#ifdef ADD_BATTERY_DATA
3730 // when changing the audio output device, call addBatteryData to notify
3731 // the change
3732 if (mOutDevice != type) {
3733 uint32_t params = 0;
3734 // check whether speaker is on
3735 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3736 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003737 }
3738
Eric Laurent054d9d32015-04-24 08:48:48 -07003739 audio_devices_t deviceWithoutSpeaker
3740 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3741 // check if any other device (except speaker) is on
3742 if (type & deviceWithoutSpeaker) {
3743 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3744 }
3745
3746 if (params != 0) {
3747 addBatteryData(params);
3748 }
3749 }
3750#endif
3751
3752 for (size_t i = 0; i < mEffectChains.size(); i++) {
3753 mEffectChains[i]->setDevice_l(type);
3754 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003755
3756 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3757 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3758 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003759 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003760 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003761
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003762 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003763 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3764 status = hwDevice->createAudioPatch(patch->num_sources,
3765 patch->sources,
3766 patch->num_sinks,
3767 patch->sinks,
3768 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003769 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003770 char *address;
3771 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3772 //FIXME: we only support address on first sink with HAL version < 3.0
3773 address = audio_device_address_to_parameter(
3774 patch->sinks[0].ext.device.type,
3775 patch->sinks[0].ext.device.address);
3776 } else {
3777 address = (char *)calloc(1, 1);
3778 }
3779 AudioParameter param = AudioParameter(String8(address));
3780 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003781 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003782 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003783 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003784 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003785 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003786 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003787 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3788 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003789 return status;
3790}
3791
Eric Laurent054d9d32015-04-24 08:48:48 -07003792status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3793{
Andy Hungf60abce2016-08-26 11:37:54 -07003794 status_t status;
3795 if (property_get_bool("af.patch_park", false /* default_value */)) {
3796 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3797 // or if HAL does not properly lock against access.
3798 AutoPark<FastMixer> park(mFastMixer);
3799 status = PlaybackThread::releaseAudioPatch_l(handle);
3800 } else {
3801 status = PlaybackThread::releaseAudioPatch_l(handle);
3802 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003803 return status;
3804}
3805
Eric Laurent1c333e22014-05-20 10:48:17 -07003806status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3807{
3808 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003809
3810 mOutDevice = AUDIO_DEVICE_NONE;
3811
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003812 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003813 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3814 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003815 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003816 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003817 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003818 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003819 }
3820 return status;
3821}
3822
Eric Laurent83b88082014-06-20 18:31:16 -07003823void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3824{
3825 Mutex::Autolock _l(mLock);
3826 mTracks.add(track);
3827}
3828
3829void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3830{
3831 Mutex::Autolock _l(mLock);
3832 destroyTrack_l(track);
3833}
3834
Mikhail Naganovdc769682018-05-04 15:34:08 -07003835void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003836{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003837 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003838 config->role = AUDIO_PORT_ROLE_SOURCE;
3839 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3840 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003841 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3842 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3843 config->flags.output = mOutput->flags;
3844 }
Eric Laurent83b88082014-06-20 18:31:16 -07003845}
3846
Eric Laurent81784c32012-11-19 14:55:58 -08003847// ----------------------------------------------------------------------------
3848
3849AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003850 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3851 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003852 // mAudioMixer below
3853 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003854 mFastMixerFutex(0),
3855 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003856 // mOutputSink below
3857 // mPipeSink below
3858 // mNormalSink below
3859{
3860 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003861 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003862 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003863 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3864 mNormalFrameCount);
3865 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3866
Andy Hungfbfc3952015-01-15 13:33:51 -08003867 if (type == DUPLICATING) {
3868 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3869 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3870 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3871 return;
3872 }
Eric Laurent81784c32012-11-19 14:55:58 -08003873 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003874 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003876 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003877#if !LOG_NDEBUG
3878 ssize_t index =
3879#else
3880 (void)
3881#endif
3882 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003883 ALOG_ASSERT(index == 0);
3884
3885 // initialize fast mixer depending on configuration
3886 bool initFastMixer;
3887 switch (kUseFastMixer) {
3888 case FastMixer_Never:
3889 initFastMixer = false;
3890 break;
3891 case FastMixer_Always:
3892 initFastMixer = true;
3893 break;
3894 case FastMixer_Static:
3895 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003896 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3897 // where the period is less than an experimentally determined threshold that can be
3898 // scheduled reliably with CFS. However, the BT A2DP HAL is
3899 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3900 initFastMixer = mFrameCount < mNormalFrameCount
3901 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003902 break;
3903 }
Andy Hungfda69402017-02-15 14:33:12 -08003904 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3905 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3906 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003907 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003908 audio_format_t fastMixerFormat;
3909 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3910 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3911 } else {
3912 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3913 }
3914 if (mFormat != fastMixerFormat) {
3915 // change our Sink format to accept our intermediate precision
3916 mFormat = fastMixerFormat;
3917 free(mSinkBuffer);
3918 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3919 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3920 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3921 }
Eric Laurent81784c32012-11-19 14:55:58 -08003922
3923 // create a MonoPipe to connect our submix to FastMixer
3924 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003925
Andy Hung1258c1a2014-05-23 21:22:17 -07003926 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003927 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003928 format.mFormat = fastMixerFormat;
3929 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3930
Eric Laurent81784c32012-11-19 14:55:58 -08003931 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3932 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3933 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3934 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3935 const NBAIO_Format offers[1] = {format};
3936 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003937#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003938 ssize_t index =
3939#else
3940 (void)
3941#endif
3942 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003943 ALOG_ASSERT(index == 0);
3944 monoPipe->setAvgFrames((mScreenState & 1) ?
3945 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3946 mPipeSink = monoPipe;
3947
Eric Laurent81784c32012-11-19 14:55:58 -08003948 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07003949 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003950 FastMixerStateQueue *sq = mFastMixer->sq();
3951#ifdef STATE_QUEUE_DUMP
3952 sq->setObserverDump(&mStateQueueObserverDump);
3953 sq->setMutatorDump(&mStateQueueMutatorDump);
3954#endif
3955 FastMixerState *state = sq->begin();
3956 FastTrack *fastTrack = &state->mFastTracks[0];
3957 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3958 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3959 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003960 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3961 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003962 fastTrack->mGeneration++;
3963 state->mFastTracksGen++;
3964 state->mTrackMask = 1;
3965 // fast mixer will use the HAL output sink
3966 state->mOutputSink = mOutputSink.get();
3967 state->mOutputSinkGen++;
3968 state->mFrameCount = mFrameCount;
3969 state->mCommand = FastMixerState::COLD_IDLE;
3970 // already done in constructor initialization list
3971 //mFastMixerFutex = 0;
3972 state->mColdFutexAddr = &mFastMixerFutex;
3973 state->mColdGen++;
3974 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08003975 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3976 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003977 sq->end();
3978 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3979
3980 // start the fast mixer
3981 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3982 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003983 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003984 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003985
3986#ifdef AUDIO_WATCHDOG
3987 // create and start the watchdog
3988 mAudioWatchdog = new AudioWatchdog();
3989 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3990 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3991 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003992 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003993#endif
Andy Hung8946a282018-04-19 20:04:56 -07003994 } else {
3995#ifdef TEE_SINK
3996 // Only use the MixerThread tee if there is no FastMixer.
3997 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
3998 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
3999#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004000 }
4001
4002 switch (kUseFastMixer) {
4003 case FastMixer_Never:
4004 case FastMixer_Dynamic:
4005 mNormalSink = mOutputSink;
4006 break;
4007 case FastMixer_Always:
4008 mNormalSink = mPipeSink;
4009 break;
4010 case FastMixer_Static:
4011 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4012 break;
4013 }
4014}
4015
4016AudioFlinger::MixerThread::~MixerThread()
4017{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004018 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004019 FastMixerStateQueue *sq = mFastMixer->sq();
4020 FastMixerState *state = sq->begin();
4021 if (state->mCommand == FastMixerState::COLD_IDLE) {
4022 int32_t old = android_atomic_inc(&mFastMixerFutex);
4023 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004024 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004025 }
4026 }
4027 state->mCommand = FastMixerState::EXIT;
4028 sq->end();
4029 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4030 mFastMixer->join();
4031 // Though the fast mixer thread has exited, it's state queue is still valid.
4032 // We'll use that extract the final state which contains one remaining fast track
4033 // corresponding to our sub-mix.
4034 state = sq->begin();
4035 ALOG_ASSERT(state->mTrackMask == 1);
4036 FastTrack *fastTrack = &state->mFastTracks[0];
4037 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4038 delete fastTrack->mBufferProvider;
4039 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004040 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004041#ifdef AUDIO_WATCHDOG
4042 if (mAudioWatchdog != 0) {
4043 mAudioWatchdog->requestExit();
4044 mAudioWatchdog->requestExitAndWait();
4045 mAudioWatchdog.clear();
4046 }
4047#endif
4048 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004049 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004050 delete mAudioMixer;
4051}
4052
4053
4054uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4055{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004056 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004057 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4058 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4059 }
4060 return latency;
4061}
4062
4063
4064void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4065{
4066 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4067}
4068
Eric Laurentbfb1b832013-01-07 09:53:42 -08004069ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004070{
4071 // FIXME we should only do one push per cycle; confirm this is true
4072 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004073 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004074 FastMixerStateQueue *sq = mFastMixer->sq();
4075 FastMixerState *state = sq->begin();
4076 if (state->mCommand != FastMixerState::MIX_WRITE &&
4077 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4078 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004079
4080 // FIXME workaround for first HAL write being CPU bound on some devices
4081 ATRACE_BEGIN("write");
4082 mOutput->write((char *)mSinkBuffer, 0);
4083 ATRACE_END();
4084
Eric Laurent81784c32012-11-19 14:55:58 -08004085 int32_t old = android_atomic_inc(&mFastMixerFutex);
4086 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004087 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004088 }
4089#ifdef AUDIO_WATCHDOG
4090 if (mAudioWatchdog != 0) {
4091 mAudioWatchdog->resume();
4092 }
4093#endif
4094 }
4095 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004096#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004097 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004098 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004099#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004100 sq->end();
4101 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4102 if (kUseFastMixer == FastMixer_Dynamic) {
4103 mNormalSink = mPipeSink;
4104 }
4105 } else {
4106 sq->end(false /*didModify*/);
4107 }
4108 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004109 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004110}
4111
4112void AudioFlinger::MixerThread::threadLoop_standby()
4113{
4114 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004115 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004116 FastMixerStateQueue *sq = mFastMixer->sq();
4117 FastMixerState *state = sq->begin();
4118 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004119 // Report any frames trapped in the Monopipe
4120 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4121 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4122 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4123 "monoPipeWritten:%lld monoPipeLeft:%lld",
4124 (long long)mFramesWritten, (long long)mSuspendedFrames,
4125 (long long)mPipeSink->framesWritten(), pipeFrames);
4126 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4127
Eric Laurent81784c32012-11-19 14:55:58 -08004128 state->mCommand = FastMixerState::COLD_IDLE;
4129 state->mColdFutexAddr = &mFastMixerFutex;
4130 state->mColdGen++;
4131 mFastMixerFutex = 0;
4132 sq->end();
4133 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4134 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4135 if (kUseFastMixer == FastMixer_Dynamic) {
4136 mNormalSink = mOutputSink;
4137 }
4138#ifdef AUDIO_WATCHDOG
4139 if (mAudioWatchdog != 0) {
4140 mAudioWatchdog->pause();
4141 }
4142#endif
4143 } else {
4144 sq->end(false /*didModify*/);
4145 }
4146 }
4147 PlaybackThread::threadLoop_standby();
4148}
4149
Eric Laurentbfb1b832013-01-07 09:53:42 -08004150bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4151{
4152 return false;
4153}
4154
4155bool AudioFlinger::PlaybackThread::shouldStandby_l()
4156{
4157 return !mStandby;
4158}
4159
4160bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4161{
4162 Mutex::Autolock _l(mLock);
4163 return waitingAsyncCallback_l();
4164}
4165
Eric Laurent81784c32012-11-19 14:55:58 -08004166// shared by MIXER and DIRECT, overridden by DUPLICATING
4167void AudioFlinger::PlaybackThread::threadLoop_standby()
4168{
4169 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004170 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004172 // discard any pending drain or write ack by incrementing sequence
4173 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4174 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004175 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004176 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4177 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004178 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004179 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004180}
4181
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004182void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4183{
4184 ALOGV("signal playback thread");
4185 broadcast_l();
4186}
4187
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004188void AudioFlinger::PlaybackThread::onAsyncError()
4189{
4190 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4191 invalidateTracks((audio_stream_type_t)i);
4192 }
4193}
4194
Eric Laurent81784c32012-11-19 14:55:58 -08004195void AudioFlinger::MixerThread::threadLoop_mix()
4196{
Eric Laurent81784c32012-11-19 14:55:58 -08004197 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004198 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004199 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004200 // increase sleep time progressively when application underrun condition clears.
4201 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4202 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4203 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004204 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004205 sleepTimeShift--;
4206 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004207 mSleepTimeUs = 0;
4208 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004209 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004210
Eric Laurent81784c32012-11-19 14:55:58 -08004211}
4212
4213void AudioFlinger::MixerThread::threadLoop_sleepTime()
4214{
4215 // If no tracks are ready, sleep once for the duration of an output
4216 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004217 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004218 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004219 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4220 // Using the Monopipe availableToWrite, we estimate the
4221 // sleep time to retry for more data (before we underrun).
4222 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4223 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4224 const size_t pipeFrames = monoPipe->maxFrames();
4225 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4226 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4227 const size_t framesDelay = std::min(
4228 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4229 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4230 pipeFrames, framesLeft, framesDelay);
4231 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4232 } else {
4233 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4234 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4235 mSleepTimeUs = kMinThreadSleepTimeUs;
4236 }
4237 // reduce sleep time in case of consecutive application underruns to avoid
4238 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4239 // duration we would end up writing less data than needed by the audio HAL if
4240 // the condition persists.
4241 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4242 sleepTimeShift++;
4243 }
Eric Laurent81784c32012-11-19 14:55:58 -08004244 }
4245 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004246 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004247 }
4248 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004249 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4250 // before effects processing or output.
4251 if (mMixerBufferValid) {
4252 memset(mMixerBuffer, 0, mMixerBufferSize);
4253 } else {
4254 memset(mSinkBuffer, 0, mSinkBufferSize);
4255 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004256 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004257 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4258 "anticipated start");
4259 }
4260 // TODO add standby time extension fct of effect tail
4261}
4262
4263// prepareTracks_l() must be called with ThreadBase::mLock held
4264AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4265 Vector< sp<Track> > *tracksToRemove)
4266{
Andy Hung1bc088a2018-02-09 15:57:31 -08004267 // clean up deleted track names in AudioMixer before allocating new tracks
4268 (void)mTracks.processDeletedTrackNames([this](int name) {
4269 // for each name, destroy it in the AudioMixer
4270 if (mAudioMixer->exists(name)) {
4271 mAudioMixer->destroy(name);
4272 }
4273 });
4274 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004275
4276 mixer_state mixerStatus = MIXER_IDLE;
4277 // find out which tracks need to be processed
4278 size_t count = mActiveTracks.size();
4279 size_t mixedTracks = 0;
4280 size_t tracksWithEffect = 0;
4281 // counts only _active_ fast tracks
4282 size_t fastTracks = 0;
4283 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4284
4285 float masterVolume = mMasterVolume;
4286 bool masterMute = mMasterMute;
4287
4288 if (masterMute) {
4289 masterVolume = 0;
4290 }
4291 // Delegate master volume control to effect in output mix effect chain if needed
4292 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4293 if (chain != 0) {
4294 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4295 chain->setVolume_l(&v, &v);
4296 masterVolume = (float)((v + (1 << 23)) >> 24);
4297 chain.clear();
4298 }
4299
4300 // prepare a new state to push
4301 FastMixerStateQueue *sq = NULL;
4302 FastMixerState *state = NULL;
4303 bool didModify = false;
4304 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004305 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004306 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004307 sq = mFastMixer->sq();
4308 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004309 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004310 }
4311
Andy Hung69aed5f2014-02-25 17:24:40 -08004312 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004313 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004314
Andy Hungbd3b2b02018-05-21 10:53:11 -07004315 // DeferredOperations handles statistics after setting mixerStatus.
4316 class DeferredOperations {
4317 public:
4318 DeferredOperations(mixer_state *mixerStatus)
4319 : mMixerStatus(mixerStatus) { }
4320
4321 // when leaving scope, tally frames properly.
4322 ~DeferredOperations() {
4323 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4324 // because that is when the underrun occurs.
4325 // We do not distinguish between FastTracks and NormalTracks here.
4326 if (*mMixerStatus == MIXER_TRACKS_READY) {
4327 for (const auto &underrun : mUnderrunFrames) {
4328 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4329 underrun.second);
4330 }
4331 }
4332 }
4333
4334 // tallyUnderrunFrames() is called to update the track counters
4335 // with the number of underrun frames for a particular mixer period.
4336 // We defer tallying until we know the final mixer status.
4337 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4338 mUnderrunFrames.emplace_back(track, underrunFrames);
4339 }
4340
4341 private:
4342 const mixer_state * const mMixerStatus;
4343 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4344 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4345
Eric Laurent81784c32012-11-19 14:55:58 -08004346 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004347 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004348
4349 // this const just means the local variable doesn't change
4350 Track* const track = t.get();
4351
4352 // process fast tracks
4353 if (track->isFastTrack()) {
4354
4355 // It's theoretically possible (though unlikely) for a fast track to be created
4356 // and then removed within the same normal mix cycle. This is not a problem, as
4357 // the track never becomes active so it's fast mixer slot is never touched.
4358 // The converse, of removing an (active) track and then creating a new track
4359 // at the identical fast mixer slot within the same normal mix cycle,
4360 // is impossible because the slot isn't marked available until the end of each cycle.
4361 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004362 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004363 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4364 FastTrack *fastTrack = &state->mFastTracks[j];
4365
4366 // Determine whether the track is currently in underrun condition,
4367 // and whether it had a recent underrun.
4368 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4369 FastTrackUnderruns underruns = ftDump->mUnderruns;
4370 uint32_t recentFull = (underruns.mBitFields.mFull -
4371 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4372 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4373 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4374 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4375 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4376 uint32_t recentUnderruns = recentPartial + recentEmpty;
4377 track->mObservedUnderruns = underruns;
4378 // don't count underruns that occur while stopping or pausing
4379 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004380 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004381 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4382 recentUnderruns > 0) {
4383 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004384 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004385 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004386 // Immediately account for FastTrack underruns.
4387 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004388
4389 // This is similar to the state machine for normal tracks,
4390 // with a few modifications for fast tracks.
4391 bool isActive = true;
4392 switch (track->mState) {
4393 case TrackBase::STOPPING_1:
4394 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004395 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004396 track->mState = TrackBase::STOPPING_2;
4397 }
4398 break;
4399 case TrackBase::PAUSING:
4400 // ramp down is not yet implemented
4401 track->setPaused();
4402 break;
4403 case TrackBase::RESUMING:
4404 // ramp up is not yet implemented
4405 track->mState = TrackBase::ACTIVE;
4406 break;
4407 case TrackBase::ACTIVE:
4408 if (recentFull > 0 || recentPartial > 0) {
4409 // track has provided at least some frames recently: reset retry count
4410 track->mRetryCount = kMaxTrackRetries;
4411 }
4412 if (recentUnderruns == 0) {
4413 // no recent underruns: stay active
4414 break;
4415 }
4416 // there has recently been an underrun of some kind
4417 if (track->sharedBuffer() == 0) {
4418 // were any of the recent underruns "empty" (no frames available)?
4419 if (recentEmpty == 0) {
4420 // no, then ignore the partial underruns as they are allowed indefinitely
4421 break;
4422 }
4423 // there has recently been an "empty" underrun: decrement the retry counter
4424 if (--(track->mRetryCount) > 0) {
4425 break;
4426 }
4427 // indicate to client process that the track was disabled because of underrun;
4428 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004429 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004430 // remove from active list, but state remains ACTIVE [confusing but true]
4431 isActive = false;
4432 break;
4433 }
4434 // fall through
4435 case TrackBase::STOPPING_2:
4436 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004437 case TrackBase::STOPPED:
4438 case TrackBase::FLUSHED: // flush() while active
4439 // Check for presentation complete if track is inactive
4440 // We have consumed all the buffers of this track.
4441 // This would be incomplete if we auto-paused on underrun
4442 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004443 uint32_t latency = 0;
4444 status_t result = mOutput->stream->getLatency(&latency);
4445 ALOGE_IF(result != OK,
4446 "Error when retrieving output stream latency: %d", result);
4447 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004448 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004449 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4450 // track stays in active list until presentation is complete
4451 break;
4452 }
4453 }
4454 if (track->isStopping_2()) {
4455 track->mState = TrackBase::STOPPED;
4456 }
4457 if (track->isStopped()) {
4458 // Can't reset directly, as fast mixer is still polling this track
4459 // track->reset();
4460 // So instead mark this track as needing to be reset after push with ack
4461 resetMask |= 1 << i;
4462 }
4463 isActive = false;
4464 break;
4465 case TrackBase::IDLE:
4466 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004467 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004468 }
4469
4470 if (isActive) {
4471 // was it previously inactive?
4472 if (!(state->mTrackMask & (1 << j))) {
4473 ExtendedAudioBufferProvider *eabp = track;
4474 VolumeProvider *vp = track;
4475 fastTrack->mBufferProvider = eabp;
4476 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004477 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004478 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004479 fastTrack->mGeneration++;
4480 state->mTrackMask |= 1 << j;
4481 didModify = true;
4482 // no acknowledgement required for newly active tracks
4483 }
Kevin Rocard12381092018-04-11 09:19:59 -07004484 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004485 // cache the combined master volume and stream type volume for fast mixer; this
4486 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004487 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004488 proxy->framesReleased()).first;
4489 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004490 * mStreamTypes[track->streamType()].volume
4491 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004492 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004493 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4494 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4495 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4496 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004497 ++fastTracks;
4498 } else {
4499 // was it previously active?
4500 if (state->mTrackMask & (1 << j)) {
4501 fastTrack->mBufferProvider = NULL;
4502 fastTrack->mGeneration++;
4503 state->mTrackMask &= ~(1 << j);
4504 didModify = true;
4505 // If any fast tracks were removed, we must wait for acknowledgement
4506 // because we're about to decrement the last sp<> on those tracks.
4507 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4508 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004509 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4510 // AudioTrack may start (which may not be with a start() but with a write()
4511 // after underrun) and immediately paused or released. In that case the
4512 // FastTrack state hasn't had time to update.
4513 // TODO Remove the ALOGW when this theory is confirmed.
4514 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004515 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4516 j, track->mState, state->mTrackMask, recentUnderruns,
4517 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004518 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004519 }
4520 tracksToRemove->add(track);
4521 // Avoids a misleading display in dumpsys
4522 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4523 }
4524 continue;
4525 }
4526
4527 { // local variable scope to avoid goto warning
4528
4529 audio_track_cblk_t* cblk = track->cblk();
4530
4531 // The first time a track is added we wait
4532 // for all its buffers to be filled before processing it
4533 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004534
4535 // if an active track doesn't exist in the AudioMixer, create it.
4536 if (!mAudioMixer->exists(name)) {
4537 status_t status = mAudioMixer->create(
4538 name,
4539 track->mChannelMask,
4540 track->mFormat,
4541 track->mSessionId);
4542 if (status != OK) {
4543 ALOGW("%s: cannot create track name"
4544 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4545 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4546 tracksToRemove->add(track);
4547 track->invalidate(); // consider it dead.
4548 continue;
4549 }
4550 }
4551
Eric Laurent81784c32012-11-19 14:55:58 -08004552 // make sure that we have enough frames to mix one full buffer.
4553 // enforce this condition only once to enable draining the buffer in case the client
4554 // app does not call stop() and relies on underrun to stop:
4555 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4556 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004557 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004558 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004559 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004560
4561 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004562 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004563 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4564 // add frames already consumed but not yet released by the resampler
4565 // because mAudioTrackServerProxy->framesReady() will include these frames
4566 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4567
Eric Laurent81784c32012-11-19 14:55:58 -08004568 uint32_t minFrames = 1;
4569 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4570 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004571 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004572 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004573
4574 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004575 if (ATRACE_ENABLED()) {
4576 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004577 std::string traceName("nRdy");
4578 traceName += std::to_string(track->name());
4579 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004580 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004581 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004582 !track->isPaused() && !track->isTerminated())
4583 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004584 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004585
4586 mixedTracks++;
4587
Andy Hung69aed5f2014-02-25 17:24:40 -08004588 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4589 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004590 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004591 if (track->mainBuffer() != mSinkBuffer &&
4592 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004593 if (mEffectBufferEnabled) {
4594 mEffectBufferValid = true; // Later can set directly.
4595 }
Eric Laurent81784c32012-11-19 14:55:58 -08004596 chain = getEffectChain_l(track->sessionId());
4597 // Delegate volume control to effect in track effect chain if needed
4598 if (chain != 0) {
4599 tracksWithEffect++;
4600 } else {
4601 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4602 "session %d",
4603 name, track->sessionId());
4604 }
4605 }
4606
4607
4608 int param = AudioMixer::VOLUME;
4609 if (track->mFillingUpStatus == Track::FS_FILLED) {
4610 // no ramp for the first volume setting
4611 track->mFillingUpStatus = Track::FS_ACTIVE;
4612 if (track->mState == TrackBase::RESUMING) {
4613 track->mState = TrackBase::ACTIVE;
4614 param = AudioMixer::RAMP_VOLUME;
4615 }
4616 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004617 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004618 // FIXME should not make a decision based on mServer
4619 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004620 // If the track is stopped before the first frame was mixed,
4621 // do not apply ramp
4622 param = AudioMixer::RAMP_VOLUME;
4623 }
4624
4625 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004626 uint32_t vl, vr; // in U8.24 integer format
4627 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004628 // read original volumes with volume control
4629 float typeVolume = mStreamTypes[track->streamType()].volume;
4630 float v = masterVolume * typeVolume;
4631
Glenn Kastene4756fe2012-11-29 13:38:14 -08004632 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004633 vl = vr = 0;
4634 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004635 if (track->isPausing()) {
4636 track->setPaused();
4637 }
4638 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004639 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004640 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004641 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4642 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004643 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004644 if (vlf > GAIN_FLOAT_UNITY) {
4645 ALOGV("Track left volume out of range: %.3g", vlf);
4646 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004647 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004648 if (vrf > GAIN_FLOAT_UNITY) {
4649 ALOGV("Track right volume out of range: %.3g", vrf);
4650 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004651 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004652 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004653 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004654 // now apply the master volume and stream type volume and shaper volume
4655 vlf *= v * vh;
4656 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004657 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004658 // then derive vl and vr as U8.24 versions for the effect chain
4659 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4660 vl = (uint32_t) (scaleto8_24 * vlf);
4661 vr = (uint32_t) (scaleto8_24 * vrf);
4662 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004663 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004664 // send level comes from shared memory and so may be corrupt
4665 if (sendLevel > MAX_GAIN_INT) {
4666 ALOGV("Track send level out of range: %04X", sendLevel);
4667 sendLevel = MAX_GAIN_INT;
4668 }
Andy Hung6be49402014-05-30 10:42:03 -07004669 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4670 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004671 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004672
Kevin Rocard12381092018-04-11 09:19:59 -07004673 track->setFinalVolume((vrf + vlf) / 2.f);
4674
Eric Laurent81784c32012-11-19 14:55:58 -08004675 // Delegate volume control to effect in track effect chain if needed
4676 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4677 // Do not ramp volume if volume is controlled by effect
4678 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004679 // Update remaining floating point volume levels
4680 vlf = (float)vl / (1 << 24);
4681 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004682 track->mHasVolumeController = true;
4683 } else {
4684 // force no volume ramp when volume controller was just disabled or removed
4685 // from effect chain to avoid volume spike
4686 if (track->mHasVolumeController) {
4687 param = AudioMixer::VOLUME;
4688 }
4689 track->mHasVolumeController = false;
4690 }
4691
Eric Laurent7c29ec92017-09-20 17:54:22 -07004692 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4693 // still applied by the mixer.
4694 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4695 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4696 if (v != mLeftVolFloat) {
4697 status_t result = mOutput->stream->setVolume(v, v);
4698 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4699 if (result == OK) {
4700 mLeftVolFloat = v;
4701 }
4702 }
4703 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4704 // remove stream volume contribution from software volume.
4705 if (v != 0.0f && mLeftVolFloat == v) {
4706 vlf = min(1.0f, vlf / v);
4707 vrf = min(1.0f, vrf / v);
4708 vaf = min(1.0f, vaf / v);
4709 }
4710 }
Eric Laurent81784c32012-11-19 14:55:58 -08004711 // XXX: these things DON'T need to be done each time
4712 mAudioMixer->setBufferProvider(name, track);
4713 mAudioMixer->enable(name);
4714
Andy Hung6be49402014-05-30 10:42:03 -07004715 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4716 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4717 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004718 mAudioMixer->setParameter(
4719 name,
4720 AudioMixer::TRACK,
4721 AudioMixer::FORMAT, (void *)track->format());
4722 mAudioMixer->setParameter(
4723 name,
4724 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004725 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004726 mAudioMixer->setParameter(
4727 name,
4728 AudioMixer::TRACK,
4729 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004730 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004731 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004732 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004733 if (reqSampleRate == 0) {
4734 reqSampleRate = mSampleRate;
4735 } else if (reqSampleRate > maxSampleRate) {
4736 reqSampleRate = maxSampleRate;
4737 }
Eric Laurent81784c32012-11-19 14:55:58 -08004738 mAudioMixer->setParameter(
4739 name,
4740 AudioMixer::RESAMPLE,
4741 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004742 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004743
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004744 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004745 mAudioMixer->setParameter(
4746 name,
4747 AudioMixer::TIMESTRETCH,
4748 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004749 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004750
Andy Hung69aed5f2014-02-25 17:24:40 -08004751 /*
4752 * Select the appropriate output buffer for the track.
4753 *
Andy Hung98ef9782014-03-04 14:46:50 -08004754 * Tracks with effects go into their own effects chain buffer
4755 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004756 *
4757 * Other tracks can use mMixerBuffer for higher precision
4758 * channel accumulation. If this buffer is enabled
4759 * (mMixerBufferEnabled true), then selected tracks will accumulate
4760 * into it.
4761 *
4762 */
4763 if (mMixerBufferEnabled
4764 && (track->mainBuffer() == mSinkBuffer
4765 || track->mainBuffer() == mMixerBuffer)) {
4766 mAudioMixer->setParameter(
4767 name,
4768 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004769 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004770 mAudioMixer->setParameter(
4771 name,
4772 AudioMixer::TRACK,
4773 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4774 // TODO: override track->mainBuffer()?
4775 mMixerBufferValid = true;
4776 } else {
4777 mAudioMixer->setParameter(
4778 name,
4779 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004780 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004781 mAudioMixer->setParameter(
4782 name,
4783 AudioMixer::TRACK,
4784 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4785 }
Eric Laurent81784c32012-11-19 14:55:58 -08004786 mAudioMixer->setParameter(
4787 name,
4788 AudioMixer::TRACK,
4789 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4790
4791 // reset retry count
4792 track->mRetryCount = kMaxTrackRetries;
4793
4794 // If one track is ready, set the mixer ready if:
4795 // - the mixer was not ready during previous round OR
4796 // - no other track is not ready
4797 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4798 mixerStatus != MIXER_TRACKS_ENABLED) {
4799 mixerStatus = MIXER_TRACKS_READY;
4800 }
4801 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004802 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004803 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004804 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4805 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004806 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004807 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004808 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004809
Eric Laurent81784c32012-11-19 14:55:58 -08004810 // clear effect chain input buffer if an active track underruns to avoid sending
4811 // previous audio buffer again to effects
4812 chain = getEffectChain_l(track->sessionId());
4813 if (chain != 0) {
4814 chain->clearInputBuffer();
4815 }
4816
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004817 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004818 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4819 track->isStopped() || track->isPaused()) {
4820 // We have consumed all the buffers of this track.
4821 // Remove it from the list of active tracks.
4822 // TODO: use actual buffer filling status instead of latency when available from
4823 // audio HAL
4824 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004825 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004826 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4827 if (track->isStopped()) {
4828 track->reset();
4829 }
4830 tracksToRemove->add(track);
4831 }
4832 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004833 // No buffers for this track. Give it a few chances to
4834 // fill a buffer, then remove it from active list.
4835 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004836 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004837 tracksToRemove->add(track);
4838 // indicate to client process that the track was disabled because of underrun;
4839 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004840 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004841 // If one track is not ready, mark the mixer also not ready if:
4842 // - the mixer was ready during previous round OR
4843 // - no other track is ready
4844 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4845 mixerStatus != MIXER_TRACKS_READY) {
4846 mixerStatus = MIXER_TRACKS_ENABLED;
4847 }
4848 }
4849 mAudioMixer->disable(name);
4850 }
4851
4852 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004853
4854 }
4855
4856 // Push the new FastMixer state if necessary
4857 bool pauseAudioWatchdog = false;
4858 if (didModify) {
4859 state->mFastTracksGen++;
4860 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4861 if (kUseFastMixer == FastMixer_Dynamic &&
4862 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4863 state->mCommand = FastMixerState::COLD_IDLE;
4864 state->mColdFutexAddr = &mFastMixerFutex;
4865 state->mColdGen++;
4866 mFastMixerFutex = 0;
4867 if (kUseFastMixer == FastMixer_Dynamic) {
4868 mNormalSink = mOutputSink;
4869 }
4870 // If we go into cold idle, need to wait for acknowledgement
4871 // so that fast mixer stops doing I/O.
4872 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4873 pauseAudioWatchdog = true;
4874 }
Eric Laurent81784c32012-11-19 14:55:58 -08004875 }
4876 if (sq != NULL) {
4877 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004878 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4879 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4880 // when bringing the output sink into standby.)
4881 //
4882 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4883 //
4884 // This occurs with BT suspend when we idle the FastMixer with
4885 // active tracks, which may be added or removed.
4886 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004887 }
4888#ifdef AUDIO_WATCHDOG
4889 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4890 mAudioWatchdog->pause();
4891 }
4892#endif
4893
4894 // Now perform the deferred reset on fast tracks that have stopped
4895 while (resetMask != 0) {
4896 size_t i = __builtin_ctz(resetMask);
4897 ALOG_ASSERT(i < count);
4898 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004899 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004900 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4901 track->reset();
4902 }
4903
Andy Hung80d03d22018-04-10 10:32:11 -07004904 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4905 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4906 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4907 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4908 // See also the implementation of destroyTrack_l().
4909 for (const auto &track : *tracksToRemove) {
4910 const int name = track->name();
4911 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4912 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4913 }
4914 }
4915
Eric Laurent81784c32012-11-19 14:55:58 -08004916 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004917 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004918
Eric Laurent97d547d2014-09-02 14:45:53 -07004919 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4920 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004921 }
4922
4923 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004924 // as long as there are effects we should clear the effects buffer, to avoid
4925 // passing a non-clean buffer to the effect chain
4926 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004927 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004928 // sink or mix buffer must be cleared if all tracks are connected to an
4929 // effect chain as in this case the mixer will not write to the sink or mix buffer
4930 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4932 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004933 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004934 if (mMixerBufferValid) {
4935 memset(mMixerBuffer, 0, mMixerBufferSize);
4936 // TODO: In testing, mSinkBuffer below need not be cleared because
4937 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4938 // after mixing.
4939 //
4940 // To enforce this guarantee:
4941 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4942 // (mixedTracks == 0 && fastTracks > 0))
4943 // must imply MIXER_TRACKS_READY.
4944 // Later, we may clear buffers regardless, and skip much of this logic.
4945 }
Andy Hung98ef9782014-03-04 14:46:50 -08004946 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004947 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004948 }
4949
4950 // if any fast tracks, then status is ready
4951 mMixerStatusIgnoringFastTracks = mixerStatus;
4952 if (fastTracks > 0) {
4953 mixerStatus = MIXER_TRACKS_READY;
4954 }
4955 return mixerStatus;
4956}
4957
Eric Laurentad7dd962016-09-22 12:38:37 -07004958// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004959uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004960{
4961 uint32_t trackCount = 0;
4962 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004963 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004964 trackCount++;
4965 }
4966 }
4967 return trackCount;
4968}
4969
Andy Hung1bc088a2018-02-09 15:57:31 -08004970// isTrackAllowed_l() must be called with ThreadBase::mLock held
4971bool AudioFlinger::MixerThread::isTrackAllowed_l(
4972 audio_channel_mask_t channelMask, audio_format_t format,
4973 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004974{
Andy Hung1bc088a2018-02-09 15:57:31 -08004975 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4976 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004977 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004978 // Check validity as we don't call AudioMixer::create() here.
4979 if (!AudioMixer::isValidFormat(format)) {
4980 ALOGW("%s: invalid format: %#x", __func__, format);
4981 return false;
4982 }
4983 if (!AudioMixer::isValidChannelMask(channelMask)) {
4984 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4985 return false;
4986 }
4987 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004988}
4989
Eric Laurent10351942014-05-08 18:49:52 -07004990// checkForNewParameter_l() must be called with ThreadBase::mLock held
4991bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4992 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004993{
Eric Laurent81784c32012-11-19 14:55:58 -08004994 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004995 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004996
Eric Laurent10351942014-05-08 18:49:52 -07004997 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004998
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004999 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005000
Eric Laurent10351942014-05-08 18:49:52 -07005001 AudioParameter param = AudioParameter(keyValuePair);
5002 int value;
5003 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5004 reconfig = true;
5005 }
5006 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005007 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005008 status = BAD_VALUE;
5009 } else {
5010 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005011 reconfig = true;
5012 }
Eric Laurent10351942014-05-08 18:49:52 -07005013 }
5014 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005015 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005016 status = BAD_VALUE;
5017 } else {
5018 // no need to save value, since it's constant
5019 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005020 }
Eric Laurent10351942014-05-08 18:49:52 -07005021 }
5022 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5023 // do not accept frame count changes if tracks are open as the track buffer
5024 // size depends on frame count and correct behavior would not be guaranteed
5025 // if frame count is changed after track creation
5026 if (!mTracks.isEmpty()) {
5027 status = INVALID_OPERATION;
5028 } else {
5029 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005030 }
Eric Laurent10351942014-05-08 18:49:52 -07005031 }
5032 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005033#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005034 // when changing the audio output device, call addBatteryData to notify
5035 // the change
5036 if (mOutDevice != value) {
5037 uint32_t params = 0;
5038 // check whether speaker is on
5039 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5040 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005041 }
Eric Laurent10351942014-05-08 18:49:52 -07005042
5043 audio_devices_t deviceWithoutSpeaker
5044 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5045 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005046 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005047 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5048 }
5049
5050 if (params != 0) {
5051 addBatteryData(params);
5052 }
5053 }
Eric Laurent81784c32012-11-19 14:55:58 -08005054#endif
5055
Eric Laurent10351942014-05-08 18:49:52 -07005056 // forward device change to effects that have requested to be
5057 // aware of attached audio device.
5058 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005059 a2dpDeviceChanged =
5060 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005061 mOutDevice = value;
5062 for (size_t i = 0; i < mEffectChains.size(); i++) {
5063 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005064 }
5065 }
Eric Laurent10351942014-05-08 18:49:52 -07005066 }
Eric Laurent81784c32012-11-19 14:55:58 -08005067
Eric Laurent10351942014-05-08 18:49:52 -07005068 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005069 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005070 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005071 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005072 mStandby = true;
5073 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005074 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005075 }
Eric Laurent10351942014-05-08 18:49:52 -07005076 if (status == NO_ERROR && reconfig) {
5077 readOutputParameters_l();
5078 delete mAudioMixer;
5079 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005080 for (const auto &track : mTracks) {
5081 const int name = track->name();
5082 status_t status = mAudioMixer->create(
5083 name,
5084 track->mChannelMask,
5085 track->mFormat,
5086 track->mSessionId);
5087 ALOGW_IF(status != NO_ERROR,
5088 "%s: cannot create track name"
5089 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5090 __func__,
5091 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005092 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005093 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005094 }
Eric Laurent81784c32012-11-19 14:55:58 -08005095 }
5096
Eric Laurent42537be2016-01-08 17:16:42 -08005097 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005098}
5099
5100
5101void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5102{
Eric Laurent81784c32012-11-19 14:55:58 -08005103 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005104 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005105 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005106 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005107 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005108 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005109 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005110 } else {
5111 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005112 }
Eric Laurent81784c32012-11-19 14:55:58 -08005113
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005114 if (hasFastMixer()) {
5115 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5116
5117 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5118 // while we are dumping it. It may be inconsistent, but it won't mutate!
5119 // This is a large object so we place it on the heap.
5120 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07005121 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005122 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005123
5124#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005125 // Similar for state queue
5126 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5127 observerCopy.dump(fd);
5128 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5129 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005130#endif
5131
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005132#ifdef AUDIO_WATCHDOG
5133 if (mAudioWatchdog != 0) {
5134 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5135 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5136 wdCopy.dump(fd);
5137 }
5138#endif
5139
5140 } else {
5141 dprintf(fd, " No FastMixer\n");
5142 }
Eric Laurent81784c32012-11-19 14:55:58 -08005143}
5144
Eric Tan1882f162018-08-02 18:05:39 -07005145Json::Value AudioFlinger::MixerThread::getJsonDump() const
Eric Tan7b651152018-07-13 10:17:19 -07005146{
Eric Tan1882f162018-08-02 18:05:39 -07005147 Json::Value root;
5148 if (hasFastMixer()) {
5149 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5150 // while we are dumping it. It may be inconsistent, but it won't mutate!
5151 // This is a large object so we place it on the heap.
5152 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5153 const std::unique_ptr<FastMixerDumpState> copy(new FastMixerDumpState(mFastMixerDumpState));
5154 root["fastmixer_stats"] = copy->getJsonDump();
5155 } else {
5156 root["fastmixer_stats"] = "no_fastmixer";
5157 }
5158 return root;
Eric Tan7b651152018-07-13 10:17:19 -07005159}
5160
Eric Laurent81784c32012-11-19 14:55:58 -08005161uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5162{
5163 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5164}
5165
5166uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5167{
5168 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5169}
5170
5171void AudioFlinger::MixerThread::cacheParameters_l()
5172{
5173 PlaybackThread::cacheParameters_l();
5174
5175 // FIXME: Relaxed timing because of a certain device that can't meet latency
5176 // Should be reduced to 2x after the vendor fixes the driver issue
5177 // increase threshold again due to low power audio mode. The way this warning
5178 // threshold is calculated and its usefulness should be reconsidered anyway.
5179 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5180}
5181
5182// ----------------------------------------------------------------------------
5183
5184AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005185 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5186 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005187{
5188}
5189
Eric Laurentbfb1b832013-01-07 09:53:42 -08005190AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5191 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005192 ThreadBase::type_t type, bool systemReady)
5193 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005194 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005195{
5196}
5197
Eric Laurent81784c32012-11-19 14:55:58 -08005198AudioFlinger::DirectOutputThread::~DirectOutputThread()
5199{
5200}
5201
Eric Laurent5850c4c2016-11-10 13:04:31 -08005202void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005203{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204 float left, right;
5205
5206 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5207 left = right = 0;
5208 } else {
5209 float typeVolume = mStreamTypes[track->streamType()].volume;
5210 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005211 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005212
Andy Hung10cbff12017-02-21 17:30:14 -08005213 // Get volumeshaper scaling
5214 std::pair<float /* volume */, bool /* active */>
5215 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005216 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005217 v *= vh.first;
5218 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005219
Glenn Kastenc56f3422014-03-21 17:53:17 -07005220 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5221 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5222 if (left > GAIN_FLOAT_UNITY) {
5223 left = GAIN_FLOAT_UNITY;
5224 }
5225 left *= v;
5226 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5227 if (right > GAIN_FLOAT_UNITY) {
5228 right = GAIN_FLOAT_UNITY;
5229 }
5230 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005231 }
5232
5233 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005234 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005235 if (left != mLeftVolFloat || right != mRightVolFloat) {
5236 mLeftVolFloat = left;
5237 mRightVolFloat = right;
5238
5239 // Convert volumes from float to 8.24
5240 uint32_t vl = (uint32_t)(left * (1 << 24));
5241 uint32_t vr = (uint32_t)(right * (1 << 24));
5242
5243 // Delegate volume control to effect in track effect chain if needed
5244 // only one effect chain can be present on DirectOutputThread, so if
5245 // there is one, the track is connected to it
5246 if (!mEffectChains.isEmpty()) {
5247 mEffectChains[0]->setVolume_l(&vl, &vr);
5248 left = (float)vl / (1 << 24);
5249 right = (float)vr / (1 << 24);
5250 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005251 status_t result = mOutput->stream->setVolume(left, right);
5252 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005253 }
5254 }
5255}
5256
Phil Burk43b4dcc2015-06-09 16:53:44 -07005257void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5258{
5259 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005260 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005261
Eric Laurent0f0631e2015-07-06 18:01:25 -07005262 if (previousTrack != 0 && latestTrack != 0) {
5263 if (mType == DIRECT) {
5264 if (previousTrack.get() != latestTrack.get()) {
5265 mFlushPending = true;
5266 }
5267 } else /* mType == OFFLOAD */ {
5268 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5269 mFlushPending = true;
5270 }
5271 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005272 }
5273 PlaybackThread::onAddNewTrack_l();
5274}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005275
Eric Laurent81784c32012-11-19 14:55:58 -08005276AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5277 Vector< sp<Track> > *tracksToRemove
5278)
5279{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005280 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005281 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005282 bool doHwPause = false;
5283 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005284
5285 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005286 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005287 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005288 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005289 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005290 continue;
5291 }
5292
Eric Laurent5850c4c2016-11-10 13:04:31 -08005293 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005294#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005295 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005296#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005297 // Only consider last track started for volume and mixer state control.
5298 // In theory an older track could underrun and restart after the new one starts
5299 // but as we only care about the transition phase between two tracks on a
5300 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005301 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005302 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005303
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005304 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005305 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005306 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005307 doHwPause = true;
5308 mHwPaused = true;
5309 }
5310 tracksToRemove->add(track);
5311 } else if (track->isFlushPending()) {
5312 track->flushAck();
5313 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005314 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005315 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005316 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005317 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005318 if (last) {
5319 mLeftVolFloat = mRightVolFloat = -1.0;
5320 if (mHwPaused) {
5321 doHwResume = true;
5322 mHwPaused = false;
5323 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005324 }
5325 }
5326
Eric Laurent81784c32012-11-19 14:55:58 -08005327 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005328 // for all its buffers to be filled before processing it.
5329 // Allow draining the buffer in case the client
5330 // app does not call stop() and relies on underrun to stop:
5331 // hence the test on (track->mRetryCount > 1).
5332 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005333 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005334 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005335 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005336 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005337 minFrames = mNormalFrameCount;
5338 } else {
5339 minFrames = 1;
5340 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005341
Eric Laurentab5cdba2014-06-09 17:22:27 -07005342 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5343 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005344 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005345 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005346
5347 if (track->mFillingUpStatus == Track::FS_FILLED) {
5348 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005349 if (last) {
5350 // make sure processVolume_l() will apply new volume even if 0
5351 mLeftVolFloat = mRightVolFloat = -1.0;
5352 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005353 if (!mHwSupportsPause) {
5354 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005355 }
5356 }
5357
5358 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005359 processVolume_l(track, last);
5360 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005361 sp<Track> previousTrack = mPreviousTrack.promote();
5362 if (previousTrack != 0) {
5363 if (track != previousTrack.get()) {
5364 // Flush any data still being written from last track
5365 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005366 // Invalidate previous track to force a seek when resuming.
5367 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005368 }
5369 }
5370 mPreviousTrack = track;
5371
Eric Laurentd595b7c2013-04-03 17:27:56 -07005372 // reset retry count
5373 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005374 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005375 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005376 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005377 doHwResume = true;
5378 mHwPaused = false;
5379 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005380 }
Eric Laurent81784c32012-11-19 14:55:58 -08005381 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005382 // clear effect chain input buffer if the last active track started underruns
5383 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005384 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005385 mEffectChains[0]->clearInputBuffer();
5386 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005387 if (track->isStopping_1()) {
5388 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005389 if (last && mHwPaused) {
5390 doHwResume = true;
5391 mHwPaused = false;
5392 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005393 }
5394 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5395 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005396 // We have consumed all the buffers of this track.
5397 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005398 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005399 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005400 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5401 } else {
5402 audioHALFrames = 0;
5403 }
5404
Andy Hung818e7a32016-02-16 18:08:07 -08005405 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005406 if (mStandby || !last ||
5407 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005408 if (track->isStopping_2()) {
5409 track->mState = TrackBase::STOPPED;
5410 }
Eric Laurent81784c32012-11-19 14:55:58 -08005411 if (track->isStopped()) {
5412 track->reset();
5413 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005414 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005415 }
5416 } else {
5417 // No buffers for this track. Give it a few chances to
5418 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005419 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005420 if (--(track->mRetryCount) <= 0) {
5421 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005422 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005423 // indicate to client process that the track was disabled because of underrun;
5424 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005425 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005426 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005427 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5428 "minFrames = %u, mFormat = %#x",
5429 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005430 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005431 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005432 doHwPause = true;
5433 mHwPaused = true;
5434 }
Eric Laurent81784c32012-11-19 14:55:58 -08005435 }
5436 }
5437 }
5438 }
5439
Eric Laurentd1f69b02014-12-15 14:33:13 -08005440 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005441 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005442 for (size_t i = 0; i < mTracks.size(); i++) {
5443 if (mTracks[i]->isFlushPending()) {
5444 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005445 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005446 }
5447 }
5448 }
5449
5450 // make sure the pause/flush/resume sequence is executed in the right order.
5451 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5452 // before flush and then resume HW. This can happen in case of pause/flush/resume
5453 // if resume is received before pause is executed.
5454 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005455 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005456 status_t result = mOutput->stream->pause();
5457 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005458 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005459 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005460 flushHw_l();
5461 }
5462 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005463 status_t result = mOutput->stream->resume();
5464 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005465 }
Eric Laurent81784c32012-11-19 14:55:58 -08005466 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005468
5469 return mixerStatus;
5470}
5471
5472void AudioFlinger::DirectOutputThread::threadLoop_mix()
5473{
Eric Laurent81784c32012-11-19 14:55:58 -08005474 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005475 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005476 // output audio to hardware
5477 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005478 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005479 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005480 status_t status = mActiveTrack->getNextBuffer(&buffer);
5481 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005482 // no need to pad with 0 for compressed audio
5483 if (audio_has_proportional_frames(mFormat)) {
5484 memset(curBuf, 0, frameCount * mFrameSize);
5485 }
Eric Laurent81784c32012-11-19 14:55:58 -08005486 break;
5487 }
5488 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5489 frameCount -= buffer.frameCount;
5490 curBuf += buffer.frameCount * mFrameSize;
5491 mActiveTrack->releaseBuffer(&buffer);
5492 }
Andy Hung2098f272014-02-27 14:00:06 -08005493 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005494 mSleepTimeUs = 0;
5495 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005496 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005497}
5498
5499void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5500{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005501 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005502 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005503 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005504 return;
5505 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005506 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005507 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005508 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005509 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005510 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005511 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005512 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005513 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005514 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005515 }
5516}
5517
Eric Laurentd1f69b02014-12-15 14:33:13 -08005518void AudioFlinger::DirectOutputThread::threadLoop_exit()
5519{
5520 {
5521 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005522 for (size_t i = 0; i < mTracks.size(); i++) {
5523 if (mTracks[i]->isFlushPending()) {
5524 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005525 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005526 }
5527 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005528 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005529 flushHw_l();
5530 }
5531 }
5532 PlaybackThread::threadLoop_exit();
5533}
5534
5535// must be called with thread mutex locked
5536bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5537{
5538 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005539 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005540
vivek mehta9cd7ad12016-03-17 00:18:29 -07005541 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5542 return !mStandby;
5543 }
5544
Eric Laurentd1f69b02014-12-15 14:33:13 -08005545 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5546 // after a timeout and we will enter standby then.
5547 if (mTracks.size() > 0) {
5548 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005549 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5550 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005551 }
5552
Eric Laurent5cff4032015-05-26 13:49:58 -07005553 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005554}
5555
Eric Laurent10351942014-05-08 18:49:52 -07005556// checkForNewParameter_l() must be called with ThreadBase::mLock held
5557bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5558 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005559{
5560 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005561 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005562
Eric Laurent10351942014-05-08 18:49:52 -07005563 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005564
Eric Laurent10351942014-05-08 18:49:52 -07005565 AudioParameter param = AudioParameter(keyValuePair);
5566 int value;
5567 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5568 // forward device change to effects that have requested to be
5569 // aware of attached audio device.
5570 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005571 a2dpDeviceChanged =
5572 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005573 mOutDevice = value;
5574 for (size_t i = 0; i < mEffectChains.size(); i++) {
5575 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005576 }
5577 }
Eric Laurent81784c32012-11-19 14:55:58 -08005578 }
Eric Laurent10351942014-05-08 18:49:52 -07005579 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5580 // do not accept frame count changes if tracks are open as the track buffer
5581 // size depends on frame count and correct behavior would not be garantied
5582 // if frame count is changed after track creation
5583 if (!mTracks.isEmpty()) {
5584 status = INVALID_OPERATION;
5585 } else {
5586 reconfig = true;
5587 }
5588 }
5589 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005590 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005591 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005592 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005593 mStandby = true;
5594 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005595 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005596 }
5597 if (status == NO_ERROR && reconfig) {
5598 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005599 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005600 }
5601 }
5602
Eric Laurent42537be2016-01-08 17:16:42 -08005603 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005604}
5605
5606uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5607{
5608 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005609 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005610 time = PlaybackThread::activeSleepTimeUs();
5611 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005612 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005613 }
5614 return time;
5615}
5616
5617uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5618{
5619 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005620 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005621 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5622 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005623 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005624 }
5625 return time;
5626}
5627
5628uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5629{
5630 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005631 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005632 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5633 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005634 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005635 }
5636 return time;
5637}
5638
5639void AudioFlinger::DirectOutputThread::cacheParameters_l()
5640{
5641 PlaybackThread::cacheParameters_l();
5642
5643 // use shorter standby delay as on normal output to release
5644 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005645 // no delay on outputs with HW A/V sync
5646 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005647 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005648 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005649 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005650 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005651 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005652 }
Eric Laurent81784c32012-11-19 14:55:58 -08005653}
5654
Eric Laurente659ef42014-09-29 13:06:46 -07005655void AudioFlinger::DirectOutputThread::flushHw_l()
5656{
Phil Burk062e67a2015-02-11 13:40:50 -08005657 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005658 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005659 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005660 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005661}
5662
Andy Hung10cbff12017-02-21 17:30:14 -08005663int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5664 // If a VolumeShaper is active, we must wake up periodically to update volume.
5665 const int64_t NS_PER_MS = 1000000;
5666 return mVolumeShaperActive ?
5667 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5668}
5669
Eric Laurent81784c32012-11-19 14:55:58 -08005670// ----------------------------------------------------------------------------
5671
Eric Laurentbfb1b832013-01-07 09:53:42 -08005672AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005673 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005674 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005675 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005676 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005677 mDrainSequence(0),
5678 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005679{
5680}
5681
5682AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5683{
5684}
5685
5686void AudioFlinger::AsyncCallbackThread::onFirstRef()
5687{
5688 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5689}
5690
5691bool AudioFlinger::AsyncCallbackThread::threadLoop()
5692{
5693 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005694 uint32_t writeAckSequence;
5695 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005696 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005697
5698 {
5699 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005700 while (!((mWriteAckSequence & 1) ||
5701 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005702 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005703 exitPending())) {
5704 mWaitWorkCV.wait(mLock);
5705 }
5706
Eric Laurentbfb1b832013-01-07 09:53:42 -08005707 if (exitPending()) {
5708 break;
5709 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005710 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5711 mWriteAckSequence, mDrainSequence);
5712 writeAckSequence = mWriteAckSequence;
5713 mWriteAckSequence &= ~1;
5714 drainSequence = mDrainSequence;
5715 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005716 asyncError = mAsyncError;
5717 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005718 }
5719 {
Eric Laurent4de95592013-09-26 15:28:21 -07005720 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5721 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005722 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005723 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005724 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005725 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005726 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005727 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005728 if (asyncError) {
5729 playbackThread->onAsyncError();
5730 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005731 }
5732 }
5733 }
5734 return false;
5735}
5736
5737void AudioFlinger::AsyncCallbackThread::exit()
5738{
5739 ALOGV("AsyncCallbackThread::exit");
5740 Mutex::Autolock _l(mLock);
5741 requestExit();
5742 mWaitWorkCV.broadcast();
5743}
5744
Eric Laurent3b4529e2013-09-05 18:09:19 -07005745void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005746{
5747 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005748 // bit 0 is cleared
5749 mWriteAckSequence = sequence << 1;
5750}
5751
5752void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5753{
5754 Mutex::Autolock _l(mLock);
5755 // ignore unexpected callbacks
5756 if (mWriteAckSequence & 2) {
5757 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005758 mWaitWorkCV.signal();
5759 }
5760}
5761
Eric Laurent3b4529e2013-09-05 18:09:19 -07005762void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005763{
5764 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005765 // bit 0 is cleared
5766 mDrainSequence = sequence << 1;
5767}
5768
5769void AudioFlinger::AsyncCallbackThread::resetDraining()
5770{
5771 Mutex::Autolock _l(mLock);
5772 // ignore unexpected callbacks
5773 if (mDrainSequence & 2) {
5774 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005775 mWaitWorkCV.signal();
5776 }
5777}
5778
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005779void AudioFlinger::AsyncCallbackThread::setAsyncError()
5780{
5781 Mutex::Autolock _l(mLock);
5782 mAsyncError = true;
5783 mWaitWorkCV.signal();
5784}
5785
Eric Laurentbfb1b832013-01-07 09:53:42 -08005786
5787// ----------------------------------------------------------------------------
5788AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005789 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5790 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005791 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5792 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005793{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005794 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005795 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005796 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005797}
5798
Eric Laurentbfb1b832013-01-07 09:53:42 -08005799void AudioFlinger::OffloadThread::threadLoop_exit()
5800{
5801 if (mFlushPending || mHwPaused) {
5802 // If a flush is pending or track was paused, just discard buffered data
5803 flushHw_l();
5804 } else {
5805 mMixerStatus = MIXER_DRAIN_ALL;
5806 threadLoop_drain();
5807 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005808 if (mUseAsyncWrite) {
5809 ALOG_ASSERT(mCallbackThread != 0);
5810 mCallbackThread->exit();
5811 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812 PlaybackThread::threadLoop_exit();
5813}
5814
5815AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5816 Vector< sp<Track> > *tracksToRemove
5817)
5818{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005819 size_t count = mActiveTracks.size();
5820
5821 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005822 bool doHwPause = false;
5823 bool doHwResume = false;
5824
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005825 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005826
Eric Laurentbfb1b832013-01-07 09:53:42 -08005827 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005828 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005829 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005830#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005831 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005832#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005833 // Only consider last track started for volume and mixer state control.
5834 // In theory an older track could underrun and restart after the new one starts
5835 // but as we only care about the transition phase between two tracks on a
5836 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005837 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005838 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005839
Haynes Mathew George7844f672014-01-15 12:32:55 -08005840 if (track->isInvalid()) {
5841 ALOGW("An invalidated track shouldn't be in active list");
5842 tracksToRemove->add(track);
5843 continue;
5844 }
5845
5846 if (track->mState == TrackBase::IDLE) {
5847 ALOGW("An idle track shouldn't be in active list");
5848 continue;
5849 }
5850
Eric Laurentbfb1b832013-01-07 09:53:42 -08005851 if (track->isPausing()) {
5852 track->setPaused();
5853 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005854 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005855 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005856 mHwPaused = true;
5857 }
5858 // If we were part way through writing the mixbuffer to
5859 // the HAL we must save this until we resume
5860 // BUG - this will be wrong if a different track is made active,
5861 // in that case we want to discard the pending data in the
5862 // mixbuffer and tell the client to present it again when the
5863 // track is resumed
5864 mPausedWriteLength = mCurrentWriteLength;
5865 mPausedBytesRemaining = mBytesRemaining;
5866 mBytesRemaining = 0; // stop writing
5867 }
5868 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005869 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005870 if (track->isStopping_1()) {
5871 track->mRetryCount = kMaxTrackStopRetriesOffload;
5872 } else {
5873 track->mRetryCount = kMaxTrackRetriesOffload;
5874 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005875 track->flushAck();
5876 if (last) {
5877 mFlushPending = true;
5878 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005879 } else if (track->isResumePending()){
5880 track->resumeAck();
5881 if (last) {
5882 if (mPausedBytesRemaining) {
5883 // Need to continue write that was interrupted
5884 mCurrentWriteLength = mPausedWriteLength;
5885 mBytesRemaining = mPausedBytesRemaining;
5886 mPausedBytesRemaining = 0;
5887 }
5888 if (mHwPaused) {
5889 doHwResume = true;
5890 mHwPaused = false;
5891 // threadLoop_mix() will handle the case that we need to
5892 // resume an interrupted write
5893 }
5894 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005895 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005896
Eric Laurent3df841a2016-07-15 15:15:40 -07005897 mLeftVolFloat = mRightVolFloat = -1.0;
5898
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005899 // Do not handle new data in this iteration even if track->framesReady()
5900 mixerStatus = MIXER_TRACKS_ENABLED;
5901 }
5902 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005903 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005904 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005905 if (track->mFillingUpStatus == Track::FS_FILLED) {
5906 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005907 if (last) {
5908 // make sure processVolume_l() will apply new volume even if 0
5909 mLeftVolFloat = mRightVolFloat = -1.0;
5910 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005911 }
5912
5913 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005914 sp<Track> previousTrack = mPreviousTrack.promote();
5915 if (previousTrack != 0) {
5916 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005917 // Flush any data still being written from last track
5918 mBytesRemaining = 0;
5919 if (mPausedBytesRemaining) {
5920 // Last track was paused so we also need to flush saved
5921 // mixbuffer state and invalidate track so that it will
5922 // re-submit that unwritten data when it is next resumed
5923 mPausedBytesRemaining = 0;
5924 // Invalidate is a bit drastic - would be more efficient
5925 // to have a flag to tell client that some of the
5926 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005927 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005928 }
5929 // flush data already sent to the DSP if changing audio session as audio
5930 // comes from a different source. Also invalidate previous track to force a
5931 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005932 if (previousTrack->sessionId() != track->sessionId()) {
5933 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005934 }
5935 }
5936 }
5937 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005938 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005939 if (track->isStopping_1()) {
5940 track->mRetryCount = kMaxTrackStopRetriesOffload;
5941 } else {
5942 track->mRetryCount = kMaxTrackRetriesOffload;
5943 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005944 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005945 mixerStatus = MIXER_TRACKS_READY;
5946 }
5947 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005948 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005949 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005950 if (--(track->mRetryCount) <= 0) {
5951 // Hardware buffer can hold a large amount of audio so we must
5952 // wait for all current track's data to drain before we say
5953 // that the track is stopped.
5954 if (mBytesRemaining == 0) {
5955 // Only start draining when all data in mixbuffer
5956 // has been written
5957 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5958 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5959 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5960 if (last && !mStandby) {
5961 // do not modify drain sequence if we are already draining. This happens
5962 // when resuming from pause after drain.
5963 if ((mDrainSequence & 1) == 0) {
5964 mSleepTimeUs = 0;
5965 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5966 mixerStatus = MIXER_DRAIN_TRACK;
5967 mDrainSequence += 2;
5968 }
5969 if (mHwPaused) {
5970 // It is possible to move from PAUSED to STOPPING_1 without
5971 // a resume so we must ensure hardware is running
5972 doHwResume = true;
5973 mHwPaused = false;
5974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005975 }
5976 }
Eric Laurente93cc032016-05-05 10:15:10 -07005977 } else if (last) {
5978 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5979 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005980 }
5981 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005982 // Drain has completed or we are in standby, signal presentation complete
5983 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005984 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005985 uint32_t latency = 0;
5986 status_t result = mOutput->stream->getLatency(&latency);
5987 ALOGE_IF(result != OK,
5988 "Error when retrieving output stream latency: %d", result);
5989 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005990 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005991 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005992 track->presentationComplete(framesWritten, audioHALFrames);
5993 track->reset();
5994 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07005995 // DIRECT and OFFLOADED stop resets frame counts.
5996 if (!mUseAsyncWrite) {
5997 // If we don't get explicit drain notification we must
5998 // register discontinuity regardless of whether this is
5999 // the previous (!last) or the upcoming (last) track
6000 // to avoid skipping the discontinuity.
6001 mTimestampVerifier.discontinuity();
6002 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006003 }
6004 } else {
6005 // No buffers for this track. Give it a few chances to
6006 // fill a buffer, then remove it from active list.
6007 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006008 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006009 uint64_t position = 0;
6010 struct timespec unused;
6011 // The running check restarts the retry counter at least once.
6012 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6013 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6014 running = true;
6015 mOffloadUnderrunPosition = position;
6016 }
6017 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006018 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6019 (long long)position, (long long)mOffloadUnderrunPosition);
6020 }
6021 if (running) { // still running, give us more time.
6022 track->mRetryCount = kMaxTrackRetriesOffload;
6023 } else {
6024 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
6025 track->name());
6026 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006027 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006028 // it will then automatically call start() when data is available
6029 track->disable();
6030 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006031 } else if (last){
6032 mixerStatus = MIXER_TRACKS_ENABLED;
6033 }
6034 }
6035 }
6036 // compute volume for this track
6037 processVolume_l(track, last);
6038 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006039
Eric Laurentea0fade2013-10-04 16:23:48 -07006040 // make sure the pause/flush/resume sequence is executed in the right order.
6041 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6042 // before flush and then resume HW. This can happen in case of pause/flush/resume
6043 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006044 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006045 status_t result = mOutput->stream->pause();
6046 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006047 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006048 if (mFlushPending) {
6049 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006050 }
Eric Laurentfd477972013-10-25 18:10:40 -07006051 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006052 status_t result = mOutput->stream->resume();
6053 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006054 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006055
Eric Laurentbfb1b832013-01-07 09:53:42 -08006056 // remove all the tracks that need to be...
6057 removeTracks_l(*tracksToRemove);
6058
6059 return mixerStatus;
6060}
6061
Eric Laurentbfb1b832013-01-07 09:53:42 -08006062// must be called with thread mutex locked
6063bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6064{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006065 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6066 mWriteAckSequence, mDrainSequence);
6067 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006068 return true;
6069 }
6070 return false;
6071}
6072
Eric Laurentbfb1b832013-01-07 09:53:42 -08006073bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6074{
6075 Mutex::Autolock _l(mLock);
6076 return waitingAsyncCallback_l();
6077}
6078
6079void AudioFlinger::OffloadThread::flushHw_l()
6080{
Eric Laurente659ef42014-09-29 13:06:46 -07006081 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006082 // Flush anything still waiting in the mixbuffer
6083 mCurrentWriteLength = 0;
6084 mBytesRemaining = 0;
6085 mPausedWriteLength = 0;
6086 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006087 // reset bytes written count to reflect that DSP buffers are empty after flush.
6088 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006089 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006090
Eric Laurentbfb1b832013-01-07 09:53:42 -08006091 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006092 // discard any pending drain or write ack by incrementing sequence
6093 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6094 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006095 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006096 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6097 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006098 }
6099}
6100
Haynes Mathew George05317d22016-05-03 16:34:26 -07006101void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6102{
6103 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006104 if (PlaybackThread::invalidateTracks_l(streamType)) {
6105 mFlushPending = true;
6106 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006107}
6108
Eric Laurentbfb1b832013-01-07 09:53:42 -08006109// ----------------------------------------------------------------------------
6110
Eric Laurent81784c32012-11-19 14:55:58 -08006111AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006112 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006113 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006114 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006115 mWaitTimeMs(UINT_MAX)
6116{
6117 addOutputTrack(mainThread);
6118}
6119
6120AudioFlinger::DuplicatingThread::~DuplicatingThread()
6121{
6122 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6123 mOutputTracks[i]->destroy();
6124 }
6125}
6126
6127void AudioFlinger::DuplicatingThread::threadLoop_mix()
6128{
6129 // mix buffers...
6130 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006131 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006132 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006133 if (mMixerBufferValid) {
6134 memset(mMixerBuffer, 0, mMixerBufferSize);
6135 } else {
6136 memset(mSinkBuffer, 0, mSinkBufferSize);
6137 }
Eric Laurent81784c32012-11-19 14:55:58 -08006138 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006139 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006140 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006141 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006142 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006143}
6144
6145void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6146{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006147 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006148 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006149 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006150 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006151 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006152 }
6153 } else if (mBytesWritten != 0) {
6154 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6155 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006156 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006157 } else {
6158 // flush remaining overflow buffers in output tracks
6159 writeFrames = 0;
6160 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006161 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006162 }
6163}
6164
Eric Laurentbfb1b832013-01-07 09:53:42 -08006165ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006166{
6167 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006168 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6169
6170 // Consider the first OutputTrack for timestamp and frame counting.
6171
6172 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6173 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6174 // we always claim success.
6175 if (i == 0) {
6176 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6177 ALOGD_IF(correction != 0 && writeFrames != 0,
6178 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6179 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6180 mFramesWritten -= correction;
6181 }
6182
6183 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006184 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006185 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006186 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006187}
6188
6189void AudioFlinger::DuplicatingThread::threadLoop_standby()
6190{
6191 // DuplicatingThread implements standby by stopping all tracks
6192 for (size_t i = 0; i < outputTracks.size(); i++) {
6193 outputTracks[i]->stop();
6194 }
6195}
6196
Andy Hung1bc088a2018-02-09 15:57:31 -08006197void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6198{
6199 MixerThread::dumpInternals(fd, args);
6200
6201 std::stringstream ss;
6202 const size_t numTracks = mOutputTracks.size();
6203 ss << " " << numTracks << " OutputTracks";
6204 if (numTracks > 0) {
6205 ss << ":";
6206 for (const auto &track : mOutputTracks) {
6207 const sp<ThreadBase> thread = track->thread().promote();
6208 ss << " (" << track->name() << " : ";
6209 if (thread.get() != nullptr) {
6210 ss << thread.get() << ", " << thread->id();
6211 } else {
6212 ss << "null";
6213 }
6214 ss << ")";
6215 }
6216 }
6217 ss << "\n";
6218 std::string result = ss.str();
6219 write(fd, result.c_str(), result.size());
6220}
6221
Eric Laurent81784c32012-11-19 14:55:58 -08006222void AudioFlinger::DuplicatingThread::saveOutputTracks()
6223{
6224 outputTracks = mOutputTracks;
6225}
6226
6227void AudioFlinger::DuplicatingThread::clearOutputTracks()
6228{
6229 outputTracks.clear();
6230}
6231
6232void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6233{
6234 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006235 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6236 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6237 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6238 const size_t frameCount =
6239 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6240 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6241 // from different OutputTracks and their associated MixerThreads (e.g. one may
6242 // nearly empty and the other may be dropping data).
6243
6244 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006245 this,
6246 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006247 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006248 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006249 frameCount,
6250 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006251 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6252 if (status != NO_ERROR) {
6253 ALOGE("addOutputTrack() initCheck failed %d", status);
6254 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006255 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006256 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6257 mOutputTracks.add(outputTrack);
6258 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6259 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006260}
6261
6262void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6263{
6264 Mutex::Autolock _l(mLock);
6265 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6266 if (mOutputTracks[i]->thread() == thread) {
6267 mOutputTracks[i]->destroy();
6268 mOutputTracks.removeAt(i);
6269 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006270 if (thread->getOutput() == mOutput) {
6271 mOutput = NULL;
6272 }
Eric Laurent81784c32012-11-19 14:55:58 -08006273 return;
6274 }
6275 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006276 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006277}
6278
6279// caller must hold mLock
6280void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6281{
6282 mWaitTimeMs = UINT_MAX;
6283 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6284 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6285 if (strong != 0) {
6286 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6287 if (waitTimeMs < mWaitTimeMs) {
6288 mWaitTimeMs = waitTimeMs;
6289 }
6290 }
6291 }
6292}
6293
6294
6295bool AudioFlinger::DuplicatingThread::outputsReady(
6296 const SortedVector< sp<OutputTrack> > &outputTracks)
6297{
6298 for (size_t i = 0; i < outputTracks.size(); i++) {
6299 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6300 if (thread == 0) {
6301 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6302 outputTracks[i].get());
6303 return false;
6304 }
6305 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6306 // see note at standby() declaration
6307 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6308 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6309 thread.get());
6310 return false;
6311 }
6312 }
6313 return true;
6314}
6315
Kevin Rocard12381092018-04-11 09:19:59 -07006316void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6317 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006318{
Kevin Rocard12381092018-04-11 09:19:59 -07006319 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6320 outputTrack->setMetadatas(metadata.tracks);
6321 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006322}
6323
Eric Laurent81784c32012-11-19 14:55:58 -08006324uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6325{
6326 return (mWaitTimeMs * 1000) / 2;
6327}
6328
6329void AudioFlinger::DuplicatingThread::cacheParameters_l()
6330{
6331 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6332 updateWaitTime_l();
6333
6334 MixerThread::cacheParameters_l();
6335}
6336
Eric Laurent6acd1d42017-01-04 14:23:29 -08006337
Eric Laurent81784c32012-11-19 14:55:58 -08006338// ----------------------------------------------------------------------------
6339// Record
6340// ----------------------------------------------------------------------------
6341
6342AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6343 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006344 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006345 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006346 audio_devices_t inDevice,
6347 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006348 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006349 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006350 mInput(input),
6351 mActiveTracks(&this->mLocalLog),
6352 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006353 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006354 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006355 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6356 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006357 // mFastCapture below
6358 , mFastCaptureFutex(0)
6359 // mInputSource
6360 // mPipeSink
6361 // mPipeSource
6362 , mPipeFramesP2(0)
6363 // mPipeMemory
6364 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006365 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006366 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006367{
Glenn Kastend7dca052015-03-05 16:05:54 -08006368 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6369 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006370
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006371 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006372
6373 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006374 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006375 size_t numCounterOffers = 0;
6376 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006377#if !LOG_NDEBUG
6378 ssize_t index =
6379#else
6380 (void)
6381#endif
6382 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006383 ALOG_ASSERT(index == 0);
6384
6385 // initialize fast capture depending on configuration
6386 bool initFastCapture;
6387 switch (kUseFastCapture) {
6388 case FastCapture_Never:
6389 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006390 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006391 break;
6392 case FastCapture_Always:
6393 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006394 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006395 break;
6396 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006397 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006398 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6399 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6400 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006401 break;
6402 // case FastCapture_Dynamic:
6403 }
6404
6405 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006406 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006407 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006408 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6409 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006410 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006411 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006412 const sp<MemoryDealer> roHeap(readOnlyHeap());
6413 sp<IMemory> pipeMemory;
6414 if ((roHeap == 0) ||
6415 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006416 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6417 ALOGE("not enough memory for pipe buffer size=%zu; "
6418 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6419 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6420 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006421 goto failed;
6422 }
6423 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6424 memset(pipeBuffer, 0, pipeSize);
6425 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6426 const NBAIO_Format offers[1] = {format};
6427 size_t numCounterOffers = 0;
6428 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6429 ALOG_ASSERT(index == 0);
6430 mPipeSink = pipe;
6431 PipeReader *pipeReader = new PipeReader(*pipe);
6432 numCounterOffers = 0;
6433 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6434 ALOG_ASSERT(index == 0);
6435 mPipeSource = pipeReader;
6436 mPipeFramesP2 = pipeFramesP2;
6437 mPipeMemory = pipeMemory;
6438
6439 // create fast capture
6440 mFastCapture = new FastCapture();
6441 FastCaptureStateQueue *sq = mFastCapture->sq();
6442#ifdef STATE_QUEUE_DUMP
6443 // FIXME
6444#endif
6445 FastCaptureState *state = sq->begin();
6446 state->mCblk = NULL;
6447 state->mInputSource = mInputSource.get();
6448 state->mInputSourceGen++;
6449 state->mPipeSink = pipe;
6450 state->mPipeSinkGen++;
6451 state->mFrameCount = mFrameCount;
6452 state->mCommand = FastCaptureState::COLD_IDLE;
6453 // already done in constructor initialization list
6454 //mFastCaptureFutex = 0;
6455 state->mColdFutexAddr = &mFastCaptureFutex;
6456 state->mColdGen++;
6457 state->mDumpState = &mFastCaptureDumpState;
6458#ifdef TEE_SINK
6459 // FIXME
6460#endif
6461 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6462 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6463 sq->end();
6464 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6465
6466 // start the fast capture
6467 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6468 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006469 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006470 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006471#ifdef AUDIO_WATCHDOG
6472 // FIXME
6473#endif
6474
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006475 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006476 }
Andy Hung8946a282018-04-19 20:04:56 -07006477#ifdef TEE_SINK
6478 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6479 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6480#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006481failed: ;
6482
6483 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006484}
6485
Eric Laurent81784c32012-11-19 14:55:58 -08006486AudioFlinger::RecordThread::~RecordThread()
6487{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006488 if (mFastCapture != 0) {
6489 FastCaptureStateQueue *sq = mFastCapture->sq();
6490 FastCaptureState *state = sq->begin();
6491 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6492 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6493 if (old == -1) {
6494 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6495 }
6496 }
6497 state->mCommand = FastCaptureState::EXIT;
6498 sq->end();
6499 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6500 mFastCapture->join();
6501 mFastCapture.clear();
6502 }
6503 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006504 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006505 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006506}
6507
6508void AudioFlinger::RecordThread::onFirstRef()
6509{
Glenn Kastend7dca052015-03-05 16:05:54 -08006510 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006511}
6512
Eric Laurent555530a2017-02-07 18:17:24 -08006513void AudioFlinger::RecordThread::preExit()
6514{
6515 ALOGV(" preExit()");
6516 Mutex::Autolock _l(mLock);
6517 for (size_t i = 0; i < mTracks.size(); i++) {
6518 sp<RecordTrack> track = mTracks[i];
6519 track->invalidate();
6520 }
6521 mActiveTracks.clear();
6522 mStartStopCond.broadcast();
6523}
6524
Eric Laurent81784c32012-11-19 14:55:58 -08006525bool AudioFlinger::RecordThread::threadLoop()
6526{
Eric Laurent81784c32012-11-19 14:55:58 -08006527 nsecs_t lastWarning = 0;
6528
6529 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006530
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006531reacquire_wakelock:
6532 sp<RecordTrack> activeTrack;
6533 {
6534 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006535 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006536 }
6537
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006538 // used to request a deferred sleep, to be executed later while mutex is unlocked
6539 uint32_t sleepUs = 0;
6540
6541 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006542 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006543 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006544
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006545 // activeTracks accumulates a copy of a subset of mActiveTracks
6546 Vector< sp<RecordTrack> > activeTracks;
6547
Glenn Kasten735f45f2014-08-18 15:51:59 -07006548 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006549 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006550
Glenn Kasten735f45f2014-08-18 15:51:59 -07006551 // reference to a fast track which is about to be removed
6552 sp<RecordTrack> fastTrackToRemove;
6553
Eric Laurent81784c32012-11-19 14:55:58 -08006554 { // scope for mLock
6555 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006556
Eric Laurent021cf962014-05-13 10:18:14 -07006557 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006558
Eric Laurent000a4192014-01-29 15:17:32 -08006559 // check exitPending here because checkForNewParameters_l() and
6560 // checkForNewParameters_l() can temporarily release mLock
6561 if (exitPending()) {
6562 break;
6563 }
6564
Eric Laurent5c25d562016-07-13 17:17:45 -07006565 // sleep with mutex unlocked
6566 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006567 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006568 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6569 ATRACE_END();
6570 sleepUs = 0;
6571 continue;
6572 }
6573
Glenn Kasten2b806402013-11-20 16:37:38 -08006574 // if no active track(s), then standby and release wakelock
6575 size_t size = mActiveTracks.size();
6576 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006577 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006578 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006579 releaseWakeLock_l();
6580 ALOGV("RecordThread: loop stopping");
6581 // go to sleep
6582 mWaitWorkCV.wait(mLock);
6583 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006584 goto reacquire_wakelock;
6585 }
6586
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006587 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006588 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006589 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006590
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006591 activeTrack = mActiveTracks[i];
6592 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006593 if (activeTrack->isFastTrack()) {
6594 ALOG_ASSERT(fastTrackToRemove == 0);
6595 fastTrackToRemove = activeTrack;
6596 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006597 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006598 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006599 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006600 continue;
6601 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006602
6603 TrackBase::track_state activeTrackState = activeTrack->mState;
6604 switch (activeTrackState) {
6605
6606 case TrackBase::PAUSING:
6607 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006608 doBroadcast = true;
6609 size--;
6610 continue;
6611
6612 case TrackBase::STARTING_1:
6613 sleepUs = 10000;
6614 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006615 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006616 continue;
6617
6618 case TrackBase::STARTING_2:
6619 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006620 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006621 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006622 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006623 break;
6624
6625 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006626 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006627 break;
6628
6629 case TrackBase::IDLE:
6630 i++;
6631 continue;
6632
6633 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006634 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006635 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006636
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006637 activeTracks.add(activeTrack);
6638 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006639
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006640 if (activeTrack->isFastTrack()) {
6641 ALOG_ASSERT(!mFastTrackAvail);
6642 ALOG_ASSERT(fastTrack == 0);
6643 fastTrack = activeTrack;
6644 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006645 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006646
Andy Hungdae27702016-10-31 14:01:16 -07006647 mActiveTracks.updatePowerState(this);
6648
Kevin Rocard069c2712018-03-29 19:09:14 -07006649 updateMetadata_l();
6650
Eric Laurent5c25d562016-07-13 17:17:45 -07006651 if (allStopped) {
6652 standbyIfNotAlreadyInStandby();
6653 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006654 if (doBroadcast) {
6655 mStartStopCond.broadcast();
6656 }
6657
6658 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006659 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006660 if (sleepUs == 0) {
6661 sleepUs = kRecordThreadSleepUs;
6662 }
6663 continue;
6664 }
6665 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006666
Eric Laurent81784c32012-11-19 14:55:58 -08006667 lockEffectChains_l(effectChains);
6668 }
6669
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006670 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006671
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006672 size_t size = effectChains.size();
6673 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006674 // thread mutex is not locked, but effect chain is locked
6675 effectChains[i]->process_l();
6676 }
6677
Glenn Kasten735f45f2014-08-18 15:51:59 -07006678 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006679 if (mFastCapture != 0) {
6680 FastCaptureStateQueue *sq = mFastCapture->sq();
6681 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006682 bool didModify = false;
6683 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006684 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6685 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6686 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6687 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6688 if (old == -1) {
6689 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6690 }
6691 }
6692 state->mCommand = FastCaptureState::READ_WRITE;
6693#if 0 // FIXME
6694 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006695 FastThreadDumpState::kSamplingNforLowRamDevice :
6696 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006697#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006698 didModify = true;
6699 }
6700 audio_track_cblk_t *cblkOld = state->mCblk;
6701 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6702 if (cblkNew != cblkOld) {
6703 state->mCblk = cblkNew;
6704 // block until acked if removing a fast track
6705 if (cblkOld != NULL) {
6706 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6707 }
6708 didModify = true;
6709 }
jiabin01c8f562018-07-19 17:47:28 -07006710 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6711 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6712 if (state->mFastPatchRecordBufferProvider != abp) {
6713 state->mFastPatchRecordBufferProvider = abp;
6714 state->mFastPatchRecordFormat = fastTrack == 0 ?
6715 AUDIO_FORMAT_INVALID : fastTrack->format();
6716 didModify = true;
6717 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006718 sq->end(didModify);
6719 if (didModify) {
6720 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006721#if 0
6722 if (kUseFastCapture == FastCapture_Dynamic) {
6723 mNormalSource = mPipeSource;
6724 }
6725#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006726 }
6727 }
6728
Glenn Kasten735f45f2014-08-18 15:51:59 -07006729 // now run the fast track destructor with thread mutex unlocked
6730 fastTrackToRemove.clear();
6731
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006732 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6733 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6734 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6735 // If destination is non-contiguous, first read past the nominal end of buffer, then
6736 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006737
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006738 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006739 ssize_t framesRead;
6740
6741 // If an NBAIO source is present, use it to read the normal capture's data
6742 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006743 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006744
6745 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6746 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6747 // we immediately retry the read() to get data and prevent another overflow.
6748 for (int retries = 0; retries <= 2; ++retries) {
6749 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6750 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6751 framesToRead);
6752 if (framesRead != OVERRUN) break;
6753 }
6754
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006755 const ssize_t availableToRead = mPipeSource->availableToRead();
6756 if (availableToRead >= 0) {
6757 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6758 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6759 "more frames to read than fifo size, %zd > %zu",
6760 availableToRead, mPipeFramesP2);
6761 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6762 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6763 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6764 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006765 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6766 }
6767 if (framesRead < 0) {
6768 status_t status = (status_t) framesRead;
6769 switch (status) {
6770 case OVERRUN:
6771 ALOGW("overrun on read from pipe");
6772 framesRead = 0;
6773 break;
6774 case NEGOTIATE:
6775 ALOGE("re-negotiation is needed");
6776 framesRead = -1; // Will cause an attempt to recover.
6777 break;
6778 default:
6779 ALOGE("unknown error %d on read from pipe", status);
6780 break;
6781 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006782 }
6783 // otherwise use the HAL / AudioStreamIn directly
6784 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006785 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006786 size_t bytesRead;
6787 status_t result = mInput->stream->read(
6788 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006789 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006790 if (result < 0) {
6791 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006792 } else {
6793 framesRead = bytesRead / mFrameSize;
6794 }
6795 }
6796
Andy Hung3f0c9022016-01-15 17:49:46 -08006797 // Update server timestamp with server stats
6798 // systemTime() is optional if the hardware supports timestamps.
6799 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6800 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6801
6802 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006803 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006804 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006805 if (mStandby) {
6806 mTimestampVerifier.discontinuity();
6807 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006808 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6809 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6810 // Note: In general record buffers should tend to be empty in
6811 // a properly running pipeline.
6812 //
6813 // Also, it is not advantageous to call get_presentation_position during the read
6814 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006815
6816 mTimestampVerifier.add(mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
6817 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
6818 mSampleRate);
6819 } else {
6820 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006821 }
6822 }
6823 // Use this to track timestamp information
6824 // ALOGD("%s", mTimestamp.toString().c_str());
6825
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006826 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006827 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006828 // Force input into standby so that it tries to recover at next read attempt
6829 inputStandBy();
6830 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006831 }
6832 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006833 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006834 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006835 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006836
Andy Hung8946a282018-04-19 20:04:56 -07006837#ifdef TEE_SINK
6838 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6839#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006840 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006841 {
6842 size_t part1 = mRsmpInFramesP2 - rear;
6843 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006844 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006845 (framesRead - part1) * mFrameSize);
6846 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006847 }
6848 rear = mRsmpInRear += framesRead;
6849
6850 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006851
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006852 // loop over each active track
6853 for (size_t i = 0; i < size; i++) {
6854 activeTrack = activeTracks[i];
6855
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006856 // skip fast tracks, as those are handled directly by FastCapture
6857 if (activeTrack->isFastTrack()) {
6858 continue;
6859 }
6860
Andy Hung73c02e42015-03-29 01:13:58 -07006861 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006862 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6863
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006864 enum {
6865 OVERRUN_UNKNOWN,
6866 OVERRUN_TRUE,
6867 OVERRUN_FALSE
6868 } overrun = OVERRUN_UNKNOWN;
6869
6870 // loop over getNextBuffer to handle circular sink
6871 for (;;) {
6872
6873 activeTrack->mSink.frameCount = ~0;
6874 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6875 size_t framesOut = activeTrack->mSink.frameCount;
6876 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6877
Andy Hung73c02e42015-03-29 01:13:58 -07006878 // check available frames and handle overrun conditions
6879 // if the record track isn't draining fast enough.
6880 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006881 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006882 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6883 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006884 overrun = OVERRUN_TRUE;
6885 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006886 if (framesOut == 0 || framesIn == 0) {
6887 break;
6888 }
6889
Andy Hung6770c6f2015-04-07 13:43:36 -07006890 // Don't allow framesOut to be larger than what is possible with resampling
6891 // from framesIn.
6892 // This isn't strictly necessary but helps limit buffer resizing in
6893 // RecordBufferConverter. TODO: remove when no longer needed.
6894 framesOut = min(framesOut,
6895 destinationFramesPossible(
6896 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006897
6898 if (activeTrack->isDirect()) {
6899 // No RecordBufferConverter used for compressed formats. Pass
6900 // straight from RecordThread buffer to RecordTrack buffer.
6901 AudioBufferProvider::Buffer buffer;
6902 buffer.frameCount = framesOut;
6903 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6904 if (status == OK && buffer.frameCount != 0) {
6905 ALOGV_IF(buffer.frameCount != framesOut,
6906 "%s() read less than expected (%zu vs %zu)",
6907 __func__, buffer.frameCount, framesOut);
6908 framesOut = buffer.frameCount;
6909 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
6910 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6911 } else {
6912 framesOut = 0;
6913 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6914 __func__, status, buffer.frameCount);
6915 }
6916 } else {
6917 // process frames from the RecordThread buffer provider to the RecordTrack
6918 // buffer
6919 framesOut = activeTrack->mRecordBufferConverter->convert(
6920 activeTrack->mSink.raw,
6921 activeTrack->mResamplerBufferProvider,
6922 framesOut);
6923 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006924
6925 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6926 overrun = OVERRUN_FALSE;
6927 }
6928
6929 if (activeTrack->mFramesToDrop == 0) {
6930 if (framesOut > 0) {
6931 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006932 // Sanitize before releasing if the track has no access to the source data
6933 // An idle UID receives silence from non virtual devices until active
6934 if (activeTrack->isSilenced()) {
6935 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6936 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006937 activeTrack->releaseBuffer(&activeTrack->mSink);
6938 }
6939 } else {
6940 // FIXME could do a partial drop of framesOut
6941 if (activeTrack->mFramesToDrop > 0) {
6942 activeTrack->mFramesToDrop -= framesOut;
6943 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006944 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006945 }
6946 } else {
6947 activeTrack->mFramesToDrop += framesOut;
6948 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6949 activeTrack->mSyncStartEvent->isCancelled()) {
6950 ALOGW("Synced record %s, session %d, trigger session %d",
6951 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6952 activeTrack->sessionId(),
6953 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006954 activeTrack->mSyncStartEvent->triggerSession() :
6955 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006956 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006957 }
6958 }
6959 }
6960
6961 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006962 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006963 }
6964 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006965
6966 switch (overrun) {
6967 case OVERRUN_TRUE:
6968 // client isn't retrieving buffers fast enough
6969 if (!activeTrack->setOverflow()) {
6970 nsecs_t now = systemTime();
6971 // FIXME should lastWarning per track?
6972 if ((now - lastWarning) > kWarningThrottleNs) {
6973 ALOGW("RecordThread: buffer overflow");
6974 lastWarning = now;
6975 }
6976 }
6977 break;
6978 case OVERRUN_FALSE:
6979 activeTrack->clearOverflow();
6980 break;
6981 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006982 break;
6983 }
6984
Andy Hung3f0c9022016-01-15 17:49:46 -08006985 // update frame information and push timestamp out
6986 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006987 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006988 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6989 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006990 }
6991
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006992unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006993 // enable changes in effect chain
6994 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006995 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006996 }
6997
Glenn Kasten93e471f2013-08-19 08:40:07 -07006998 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006999
7000 {
7001 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007002 for (size_t i = 0; i < mTracks.size(); i++) {
7003 sp<RecordTrack> track = mTracks[i];
7004 track->invalidate();
7005 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007006 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007007 mStartStopCond.broadcast();
7008 }
7009
7010 releaseWakeLock();
7011
7012 ALOGV("RecordThread %p exiting", this);
7013 return false;
7014}
7015
Glenn Kasten93e471f2013-08-19 08:40:07 -07007016void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007017{
7018 if (!mStandby) {
7019 inputStandBy();
7020 mStandby = true;
7021 }
7022}
7023
7024void AudioFlinger::RecordThread::inputStandBy()
7025{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007026 // Idle the fast capture if it's currently running
7027 if (mFastCapture != 0) {
7028 FastCaptureStateQueue *sq = mFastCapture->sq();
7029 FastCaptureState *state = sq->begin();
7030 if (!(state->mCommand & FastCaptureState::IDLE)) {
7031 state->mCommand = FastCaptureState::COLD_IDLE;
7032 state->mColdFutexAddr = &mFastCaptureFutex;
7033 state->mColdGen++;
7034 mFastCaptureFutex = 0;
7035 sq->end();
7036 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7037 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7038#if 0
7039 if (kUseFastCapture == FastCapture_Dynamic) {
7040 // FIXME
7041 }
7042#endif
7043#ifdef AUDIO_WATCHDOG
7044 // FIXME
7045#endif
7046 } else {
7047 sq->end(false /*didModify*/);
7048 }
7049 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007050 status_t result = mInput->stream->standby();
7051 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007052
7053 // If going into standby, flush the pipe source.
7054 if (mPipeSource.get() != nullptr) {
7055 const ssize_t flushed = mPipeSource->flush();
7056 if (flushed > 0) {
7057 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7058 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7059 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7060 }
7061 }
Eric Laurent81784c32012-11-19 14:55:58 -08007062}
7063
Glenn Kasten05997e22014-03-13 15:08:33 -07007064// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007065sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007066 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007067 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007068 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007069 audio_format_t format,
7070 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007071 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007072 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007073 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007074 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007075 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007076 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007077 status_t *status,
7078 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007079{
Glenn Kasten74935e42013-12-19 08:56:45 -08007080 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007081 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007082 sp<RecordTrack> track;
7083 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007084 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007085 audio_input_flags_t requestedFlags = *flags;
7086 uint32_t sampleRate;
7087
7088 lStatus = initCheck();
7089 if (lStatus != NO_ERROR) {
7090 ALOGE("createRecordTrack_l() audio driver not initialized");
7091 goto Exit;
7092 }
7093
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007094 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7095 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7096 lStatus = BAD_VALUE;
7097 goto Exit;
7098 }
7099
Eric Laurentf14db3c2017-12-08 14:20:36 -08007100 if (*pSampleRate == 0) {
7101 *pSampleRate = mSampleRate;
7102 }
7103 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007104
7105 // special case for FAST flag considered OK if fast capture is present
7106 if (hasFastCapture()) {
7107 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7108 }
7109
Eric Laurentf14db3c2017-12-08 14:20:36 -08007110 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007111 if ((*flags & inputFlags) != *flags) {
7112 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7113 " input flags (%08x)",
7114 *flags, inputFlags);
7115 *flags = (audio_input_flags_t)(*flags & inputFlags);
7116 }
Eric Laurent81784c32012-11-19 14:55:58 -08007117
Glenn Kasten90e58b12013-07-31 16:16:02 -07007118 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007119 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007120 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007121 // we formerly checked for a callback handler (non-0 tid),
7122 // but that is no longer required for TRANSFER_OBTAIN mode
7123 //
Glenn Kasten74105912014-07-03 12:28:53 -07007124 // frame count is not specified, or is exactly the pipe depth
7125 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007126 // PCM data
7127 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007128 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007129 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007130 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007131 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007132 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007133 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007134 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007135 hasFastCapture() &&
7136 // there are sufficient fast track slots available
7137 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007138 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007139 // check compatibility with audio effects.
7140 Mutex::Autolock _l(mLock);
7141 // Do not accept FAST flag if the session has software effects
7142 sp<EffectChain> chain = getEffectChain_l(sessionId);
7143 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007144 audio_input_flags_t old = *flags;
7145 chain->checkInputFlagCompatibility(flags);
7146 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007147 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7148 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007149 }
7150 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007151 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007152 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7153 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007154 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007155 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7156 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007157 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007158 this, frameCount, mFrameCount, mPipeFramesP2,
7159 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007160 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007161 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007162 }
7163 }
7164
Eric Laurentf14db3c2017-12-08 14:20:36 -08007165 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7166 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7167 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7168 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7169 lStatus = BAD_TYPE;
7170 goto Exit;
7171 }
7172
Glenn Kasten74105912014-07-03 12:28:53 -07007173 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007174 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007175 // fast track: frame count is exactly the pipe depth
7176 frameCount = mPipeFramesP2;
7177 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007178 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007179 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007180 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7181 // or 20 ms if there is a fast capture
7182 // TODO This could be a roundupRatio inline, and const
7183 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7184 * sampleRate + mSampleRate - 1) / mSampleRate;
7185 // minimum number of notification periods is at least kMinNotifications,
7186 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7187 static const size_t kMinNotifications = 3;
7188 static const uint32_t kMinMs = 30;
7189 // TODO This could be a roundupRatio inline
7190 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7191 // TODO This could be a roundupRatio inline
7192 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7193 maxNotificationFrames;
7194 const size_t minFrameCount = maxNotificationFrames *
7195 max(kMinNotifications, minNotificationsByMs);
7196 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007197 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7198 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007199 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007200 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007201 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007202 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007203
7204 { // scope for mLock
7205 Mutex::Autolock _l(mLock);
7206
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007207 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007208 format, channelMask, frameCount,
7209 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007210 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007211
Glenn Kasten03003332013-08-06 15:40:54 -07007212 lStatus = track->initCheck();
7213 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007214 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007215 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007216 goto Exit;
7217 }
7218 mTracks.add(track);
7219
Eric Laurent05067782016-06-01 18:27:28 -07007220 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007221 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7222 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7223 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007224 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007225 }
Eric Laurent81784c32012-11-19 14:55:58 -08007226 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007227
Eric Laurent81784c32012-11-19 14:55:58 -08007228 lStatus = NO_ERROR;
7229
7230Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007231 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007232 return track;
7233}
7234
7235status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7236 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007237 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007238{
7239 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7240 sp<ThreadBase> strongMe = this;
7241 status_t status = NO_ERROR;
7242
7243 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007244 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007245 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007246 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007247 triggerSession,
7248 recordTrack->sessionId(),
7249 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007250 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007251 // Sync event can be cancelled by the trigger session if the track is not in a
7252 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007253 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007254 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007255 } else {
7256 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007257 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007258 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007259 }
7260 }
7261
7262 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007263 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007264 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007265 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7266 if (recordTrack->mState == TrackBase::PAUSING) {
7267 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007268 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007269 } else {
7270 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007271 }
7272 return status;
7273 }
7274
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007275 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7276 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7277 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007278 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007279 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007280 status_t status = NO_ERROR;
7281 if (recordTrack->isExternalTrack()) {
7282 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007283 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007284 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007285 mLock.lock();
7286 // FIXME should verify that recordTrack is still in mActiveTracks
7287 if (status != NO_ERROR) {
7288 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007289 recordTrack->clearSyncStartEvent();
7290 ALOGV("RecordThread::start error %d", status);
7291 return status;
7292 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007293 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007294 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007295 // Catch up with current buffer indices if thread is already running.
7296 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7297 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7298 // see previously buffered data before it called start(), but with greater risk of overrun.
7299
Andy Hung73c02e42015-03-29 01:13:58 -07007300 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007301 if (!recordTrack->isDirect()) {
7302 // clear any converter state as new data will be discontinuous
7303 recordTrack->mRecordBufferConverter->reset();
7304 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007305 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007306 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007307 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007308 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007309 ALOGV("Record failed to start");
7310 status = BAD_VALUE;
7311 goto startError;
7312 }
Eric Laurent81784c32012-11-19 14:55:58 -08007313 return status;
7314 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007315
Eric Laurent81784c32012-11-19 14:55:58 -08007316startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007317 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007318 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007319 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007320 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007321 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007322 return status;
7323}
7324
Eric Laurent81784c32012-11-19 14:55:58 -08007325void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7326{
7327 sp<SyncEvent> strongEvent = event.promote();
7328
7329 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007330 sp<RefBase> ptr = strongEvent->cookie().promote();
7331 if (ptr != 0) {
7332 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7333 recordTrack->handleSyncStartEvent(strongEvent);
7334 }
Eric Laurent81784c32012-11-19 14:55:58 -08007335 }
7336}
7337
Glenn Kastena8356f62013-07-25 14:37:52 -07007338bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007339 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007340 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007341 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007342 return false;
7343 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007344 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007345 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007346 // signal thread to stop
7347 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007348 // do not wait for mStartStopCond if exiting
7349 if (exitPending()) {
7350 return true;
7351 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007352 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007353 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007354 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007355 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007356 ALOGV("Record stopped OK");
7357 return true;
7358 }
7359 return false;
7360}
7361
Glenn Kasten0f11b512014-01-31 16:18:54 -08007362bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007363{
7364 return false;
7365}
7366
Glenn Kasten0f11b512014-01-31 16:18:54 -08007367status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007368{
7369#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7370 if (!isValidSyncEvent(event)) {
7371 return BAD_VALUE;
7372 }
7373
Glenn Kastend848eb42016-03-08 13:42:11 -08007374 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007375 status_t ret = NAME_NOT_FOUND;
7376
7377 Mutex::Autolock _l(mLock);
7378
7379 for (size_t i = 0; i < mTracks.size(); i++) {
7380 sp<RecordTrack> track = mTracks[i];
7381 if (eventSession == track->sessionId()) {
7382 (void) track->setSyncEvent(event);
7383 ret = NO_ERROR;
7384 }
7385 }
7386 return ret;
7387#else
7388 return BAD_VALUE;
7389#endif
7390}
7391
jiabin653cc0a2018-01-17 17:54:10 -08007392status_t AudioFlinger::RecordThread::getActiveMicrophones(
7393 std::vector<media::MicrophoneInfo>* activeMicrophones)
7394{
7395 ALOGV("RecordThread::getActiveMicrophones");
7396 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007397 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7398 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007399}
7400
Kevin Rocard069c2712018-03-29 19:09:14 -07007401void AudioFlinger::RecordThread::updateMetadata_l()
7402{
7403 if (mInput == nullptr || mInput->stream == nullptr ||
7404 !mActiveTracks.readAndClearHasChanged()) {
7405 return;
7406 }
7407 StreamInHalInterface::SinkMetadata metadata;
7408 for (const sp<RecordTrack> &track : mActiveTracks) {
7409 // No track is invalid as this is called after prepareTrack_l in the same critical section
7410 metadata.tracks.push_back({
7411 .source = track->attributes().source,
7412 .gain = 1, // capture tracks do not have volumes
7413 });
7414 }
7415 mInput->stream->updateSinkMetadata(metadata);
7416}
7417
Eric Laurent81784c32012-11-19 14:55:58 -08007418// destroyTrack_l() must be called with ThreadBase::mLock held
7419void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7420{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007421 track->terminate();
7422 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007423 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007424 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007425 removeTrack_l(track);
7426 }
7427}
7428
7429void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7430{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007431 String8 result;
7432 track->appendDump(result, false /* active */);
7433 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7434
Eric Laurent81784c32012-11-19 14:55:58 -08007435 mTracks.remove(track);
7436 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007437 if (track->isFastTrack()) {
7438 ALOG_ASSERT(!mFastTrackAvail);
7439 mFastTrackAvail = true;
7440 }
Eric Laurent81784c32012-11-19 14:55:58 -08007441}
7442
7443void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7444{
7445 dumpInternals(fd, args);
7446 dumpTracks(fd, args);
7447 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007448 dprintf(fd, " Local log:\n");
7449 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007450}
7451
7452void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7453{
Glenn Kasten44182c22015-03-05 17:12:23 -08007454 dumpBase(fd, args);
7455
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007456 AudioStreamIn *input = mInput;
7457 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7458 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7459 input, flags, inputFlagsToString(flags).c_str());
Eric Tan39ec8d62018-07-24 09:49:29 -07007460 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007461 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007462 }
Andy Hungbfa64962017-06-12 14:43:19 -07007463
7464 if (input != nullptr) {
7465 dprintf(fd, " Hal stream dump:\n");
7466 (void)input->stream->dump(fd);
7467 }
7468
Andy Hung20bd30b2018-06-01 15:39:35 -07007469 const double latencyMs = - mTimestamp.getOutputServerLatencyMs(mSampleRate);
7470 if (latencyMs != 0.) {
7471 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7472 } else {
7473 dprintf(fd, " NormalRecord latency ms: unavail\n");
7474 }
7475
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007476 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007477 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007478
Glenn Kasten2f90c512015-12-02 11:40:09 -08007479 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7480 // while we are dumping it. It may be inconsistent, but it won't mutate!
7481 // This is a large object so we place it on the heap.
7482 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan7b651152018-07-13 10:17:19 -07007483 std::unique_ptr<FastCaptureDumpState> copy(new FastCaptureDumpState(mFastCaptureDumpState));
Glenn Kasten2f90c512015-12-02 11:40:09 -08007484 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007485}
7486
Glenn Kasten0f11b512014-01-31 16:18:54 -08007487void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007488{
Eric Laurent81784c32012-11-19 14:55:58 -08007489 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007490 size_t numtracks = mTracks.size();
7491 size_t numactive = mActiveTracks.size();
7492 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007493 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007494 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007495 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007496 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007497 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007498 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007499 for (size_t i = 0; i < numtracks ; ++i) {
7500 sp<RecordTrack> track = mTracks[i];
7501 if (track != 0) {
7502 bool active = mActiveTracks.indexOf(track) >= 0;
7503 if (active) {
7504 numactiveseen++;
7505 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007506 result.append(prefix);
7507 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007508 }
Eric Laurent81784c32012-11-19 14:55:58 -08007509 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007510 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007511 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007512 }
7513
Marco Nelissenb2208842014-02-07 14:00:50 -08007514 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007515 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007516 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007517 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007518 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007519 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007520 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007521 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007522 result.append(prefix);
7523 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007524 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007525 }
Eric Laurent81784c32012-11-19 14:55:58 -08007526
7527 }
7528 write(fd, result.string(), result.size());
7529}
7530
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007531void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7532{
7533 Mutex::Autolock _l(mLock);
7534 for (size_t i = 0; i < mTracks.size() ; i++) {
7535 sp<RecordTrack> track = mTracks[i];
7536 if (track != 0 && track->uid() == uid) {
7537 track->setSilenced(silenced);
7538 }
7539 }
7540}
Andy Hung73c02e42015-03-29 01:13:58 -07007541
7542void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7543{
7544 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7545 RecordThread *recordThread = (RecordThread *) threadBase.get();
7546 mRsmpInFront = recordThread->mRsmpInRear;
7547 mRsmpInUnrel = 0;
7548}
7549
7550void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7551 size_t *framesAvailable, bool *hasOverrun)
7552{
7553 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7554 RecordThread *recordThread = (RecordThread *) threadBase.get();
7555 const int32_t rear = recordThread->mRsmpInRear;
7556 const int32_t front = mRsmpInFront;
7557 const ssize_t filled = rear - front;
7558
7559 size_t framesIn;
7560 bool overrun = false;
7561 if (filled < 0) {
7562 // should not happen, but treat like a massive overrun and re-sync
7563 framesIn = 0;
7564 mRsmpInFront = rear;
7565 overrun = true;
7566 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7567 framesIn = (size_t) filled;
7568 } else {
7569 // client is not keeping up with server, but give it latest data
7570 framesIn = recordThread->mRsmpInFrames;
7571 mRsmpInFront = /* front = */ rear - framesIn;
7572 overrun = true;
7573 }
7574 if (framesAvailable != NULL) {
7575 *framesAvailable = framesIn;
7576 }
7577 if (hasOverrun != NULL) {
7578 *hasOverrun = overrun;
7579 }
7580}
7581
Eric Laurent81784c32012-11-19 14:55:58 -08007582// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007583status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007584 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007585{
Andy Hung73c02e42015-03-29 01:13:58 -07007586 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007587 if (threadBase == 0) {
7588 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007589 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007590 return NOT_ENOUGH_DATA;
7591 }
7592 RecordThread *recordThread = (RecordThread *) threadBase.get();
7593 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007594 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007595 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007596 // FIXME should not be P2 (don't want to increase latency)
7597 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007598 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007599 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007600 front &= recordThread->mRsmpInFramesP2 - 1;
7601 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007602 if (part1 > (size_t) filled) {
7603 part1 = filled;
7604 }
7605 size_t ask = buffer->frameCount;
7606 ALOG_ASSERT(ask > 0);
7607 if (part1 > ask) {
7608 part1 = ask;
7609 }
7610 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007611 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007612 buffer->raw = NULL;
7613 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007614 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007615 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007616 }
7617
Andy Hung57446612015-04-19 23:56:46 -07007618 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007619 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007620 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007621 return NO_ERROR;
7622}
7623
7624// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007625void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7626 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007627{
Glenn Kasten85948432013-08-19 12:09:05 -07007628 size_t stepCount = buffer->frameCount;
7629 if (stepCount == 0) {
7630 return;
7631 }
Andy Hung73c02e42015-03-29 01:13:58 -07007632 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7633 mRsmpInUnrel -= stepCount;
7634 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007635 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007636 buffer->frameCount = 0;
7637}
7638
Eric Laurentd8365c52017-07-16 15:27:05 -07007639void AudioFlinger::RecordThread::checkBtNrec()
7640{
7641 Mutex::Autolock _l(mLock);
7642 checkBtNrec_l();
7643}
7644
7645void AudioFlinger::RecordThread::checkBtNrec_l()
7646{
7647 // disable AEC and NS if the device is a BT SCO headset supporting those
7648 // pre processings
7649 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7650 mAudioFlinger->btNrecIsOff();
7651 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7652 for (size_t i = 0; i < mEffectChains.size(); i++) {
7653 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7654 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7655 }
7656 }
7657}
7658
Andy Hung97a893e2015-03-29 01:03:07 -07007659
Eric Laurent10351942014-05-08 18:49:52 -07007660bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7661 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007662{
7663 bool reconfig = false;
7664
Eric Laurent10351942014-05-08 18:49:52 -07007665 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007666
Eric Laurent10351942014-05-08 18:49:52 -07007667 audio_format_t reqFormat = mFormat;
7668 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007669 // 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 -07007670 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7671
7672 AudioParameter param = AudioParameter(keyValuePair);
7673 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007674
7675 // scope for AutoPark extends to end of method
7676 AutoPark<FastCapture> park(mFastCapture);
7677
Eric Laurent10351942014-05-08 18:49:52 -07007678 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7679 // channel count change can be requested. Do we mandate the first client defines the
7680 // HAL sampling rate and channel count or do we allow changes on the fly?
7681 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7682 samplingRate = value;
7683 reconfig = true;
7684 }
7685 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007686 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007687 status = BAD_VALUE;
7688 } else {
7689 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007690 reconfig = true;
7691 }
Eric Laurent10351942014-05-08 18:49:52 -07007692 }
7693 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7694 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007695 if (!audio_is_input_channel(mask) ||
7696 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007697 status = BAD_VALUE;
7698 } else {
7699 channelMask = mask;
7700 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007701 }
Eric Laurent10351942014-05-08 18:49:52 -07007702 }
7703 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7704 // do not accept frame count changes if tracks are open as the track buffer
7705 // size depends on frame count and correct behavior would not be guaranteed
7706 // if frame count is changed after track creation
7707 if (mActiveTracks.size() > 0) {
7708 status = INVALID_OPERATION;
7709 } else {
7710 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007711 }
Eric Laurent10351942014-05-08 18:49:52 -07007712 }
7713 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7714 // forward device change to effects that have requested to be
7715 // aware of attached audio device.
7716 for (size_t i = 0; i < mEffectChains.size(); i++) {
7717 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007718 }
Eric Laurent81784c32012-11-19 14:55:58 -08007719
Eric Laurent10351942014-05-08 18:49:52 -07007720 // store input device and output device but do not forward output device to audio HAL.
7721 // Note that status is ignored by the caller for output device
7722 // (see AudioFlinger::setParameters()
7723 if (audio_is_output_devices(value)) {
7724 mOutDevice = value;
7725 status = BAD_VALUE;
7726 } else {
7727 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007728 if (value != AUDIO_DEVICE_NONE) {
7729 mPrevInDevice = value;
7730 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007731 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007732 }
Eric Laurent10351942014-05-08 18:49:52 -07007733 }
7734 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7735 mAudioSource != (audio_source_t)value) {
7736 // forward device change to effects that have requested to be
7737 // aware of attached audio device.
7738 for (size_t i = 0; i < mEffectChains.size(); i++) {
7739 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007740 }
Eric Laurent10351942014-05-08 18:49:52 -07007741 mAudioSource = (audio_source_t)value;
7742 }
Glenn Kastene198c362013-08-13 09:13:36 -07007743
Eric Laurent10351942014-05-08 18:49:52 -07007744 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007745 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007746 if (status == INVALID_OPERATION) {
7747 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007748 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007749 }
7750 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007751 if (status == BAD_VALUE) {
7752 uint32_t sRate;
7753 audio_channel_mask_t channelMask;
7754 audio_format_t format;
7755 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7756 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7757 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7758 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7759 status = NO_ERROR;
7760 }
Eric Laurent81784c32012-11-19 14:55:58 -08007761 }
Eric Laurent10351942014-05-08 18:49:52 -07007762 if (status == NO_ERROR) {
7763 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007764 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007765 }
7766 }
Eric Laurent81784c32012-11-19 14:55:58 -08007767 }
Eric Laurent10351942014-05-08 18:49:52 -07007768
Eric Laurent81784c32012-11-19 14:55:58 -08007769 return reconfig;
7770}
7771
7772String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7773{
Eric Laurent81784c32012-11-19 14:55:58 -08007774 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007775 if (initCheck() == NO_ERROR) {
7776 String8 out_s8;
7777 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7778 return out_s8;
7779 }
Eric Laurent81784c32012-11-19 14:55:58 -08007780 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007781 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007782}
7783
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007784void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007785 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7786
7787 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007788
7789 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007790 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007791 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007792 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007793 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007794 desc->mChannelMask = mChannelMask;
7795 desc->mSamplingRate = mSampleRate;
7796 desc->mFormat = mFormat;
7797 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007798 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007799 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007800 break;
7801
Eric Laurent73e26b62015-04-27 16:55:58 -07007802 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007803 default:
7804 break;
7805 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007806 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007807}
7808
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007809void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007810{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007811 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7812 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07007813 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007814 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7815 if (audio_is_linear_pcm(mFormat)) {
7816 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
7817 mChannelCount, FCC_8);
7818 } else {
7819 // Can have more that FCC_8 channels in encoded streams.
7820 ALOGI("HAL format %#x is not linear pcm", mFormat);
7821 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007822 result = mInput->stream->getFrameSize(&mFrameSize);
7823 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7824 result = mInput->stream->getBufferSize(&mBufferSize);
7825 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007826 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007827 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7828 "mBufferSize=%lld, mFrameCount=%lld",
7829 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7830 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007831 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007832 // 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 -07007833 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007834 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007835 // A larger value should allow more old data to be read after a track calls start(),
7836 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007837 //
7838 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007839 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007840 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007841 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007842 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007843
7844 // TODO optimize audio capture buffer sizes ...
7845 // Here we calculate the size of the sliding buffer used as a source
7846 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7847 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7848 // be better to have it derived from the pipe depth in the long term.
7849 // The current value is higher than necessary. However it should not add to latency.
7850
Glenn Kasten85948432013-08-19 12:09:05 -07007851 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007852 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7853 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007854 // if posix_memalign fails, will segv here.
7855 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007856
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007857 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7858 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007859}
7860
Glenn Kasten5f972c02014-01-13 09:59:31 -08007861uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007862{
7863 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007864 uint32_t result;
7865 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7866 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007867 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007868 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007869}
7870
Eric Laurent4c415062016-06-17 16:14:16 -07007871// hasAudioSession_l() must be called with ThreadBase::mLock held
7872uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007873{
Eric Laurent81784c32012-11-19 14:55:58 -08007874 uint32_t result = 0;
7875 if (getEffectChain_l(sessionId) != 0) {
7876 result = EFFECT_SESSION;
7877 }
7878
7879 for (size_t i = 0; i < mTracks.size(); ++i) {
7880 if (sessionId == mTracks[i]->sessionId()) {
7881 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007882 if (mTracks[i]->isFastTrack()) {
7883 result |= FAST_SESSION;
7884 }
Eric Laurent81784c32012-11-19 14:55:58 -08007885 break;
7886 }
7887 }
7888
7889 return result;
7890}
7891
Glenn Kastend848eb42016-03-08 13:42:11 -08007892KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007893{
Glenn Kastend848eb42016-03-08 13:42:11 -08007894 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007895 Mutex::Autolock _l(mLock);
7896 for (size_t j = 0; j < mTracks.size(); ++j) {
7897 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007898 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007899 if (ids.indexOfKey(sessionId) < 0) {
7900 ids.add(sessionId, true);
7901 }
7902 }
7903 return ids;
7904}
7905
7906AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7907{
7908 Mutex::Autolock _l(mLock);
7909 AudioStreamIn *input = mInput;
7910 mInput = NULL;
7911 return input;
7912}
7913
7914// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007915sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007916{
7917 if (mInput == NULL) {
7918 return NULL;
7919 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007920 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007921}
7922
7923status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7924{
7925 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07007926 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007927 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007928 return INVALID_OPERATION;
7929 }
7930 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007931 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007932 chain->setInBuffer(NULL);
7933 chain->setOutBuffer(NULL);
7934
7935 checkSuspendOnAddEffectChain_l(chain);
7936
Eric Laurent1b928682014-10-02 19:41:47 -07007937 // make sure enabled pre processing effects state is communicated to the HAL as we
7938 // just moved them to a new input stream.
7939 chain->syncHalEffectsState();
7940
Eric Laurent81784c32012-11-19 14:55:58 -08007941 mEffectChains.add(chain);
7942
7943 return NO_ERROR;
7944}
7945
7946size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7947{
7948 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7949 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007950 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007951 chain.get(), mEffectChains.size(), this);
7952 if (mEffectChains.size() == 1) {
7953 mEffectChains.removeAt(0);
7954 }
7955 return 0;
7956}
7957
Eric Laurent1c333e22014-05-20 10:48:17 -07007958status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7959 audio_patch_handle_t *handle)
7960{
7961 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007962
7963 // store new device and send to effects
7964 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007965 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007966 for (size_t i = 0; i < mEffectChains.size(); i++) {
7967 mEffectChains[i]->setDevice_l(mInDevice);
7968 }
7969
Eric Laurentd8365c52017-07-16 15:27:05 -07007970 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007971
7972 // store new source and send to effects
7973 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7974 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007975 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007976 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007977 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007978 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007979
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007980 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007981 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7982 status = hwDevice->createAudioPatch(patch->num_sources,
7983 patch->sources,
7984 patch->num_sinks,
7985 patch->sinks,
7986 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007987 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007988 char *address;
7989 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7990 address = audio_device_address_to_parameter(
7991 patch->sources[0].ext.device.type,
7992 patch->sources[0].ext.device.address);
7993 } else {
7994 address = (char *)calloc(1, 1);
7995 }
7996 AudioParameter param = AudioParameter(String8(address));
7997 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007998 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007999 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008000 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008001 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008002 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008003 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008004 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008005
Eric Laurente8726fe2015-06-26 09:39:24 -07008006 if (mInDevice != mPrevInDevice) {
8007 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8008 mPrevInDevice = mInDevice;
8009 }
Eric Laurent296fb132015-05-01 11:38:42 -07008010
Eric Laurent1c333e22014-05-20 10:48:17 -07008011 return status;
8012}
8013
8014status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8015{
8016 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008017
8018 mInDevice = AUDIO_DEVICE_NONE;
8019
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008020 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008021 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8022 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008023 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008024 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008025 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008026 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008027 }
8028 return status;
8029}
8030
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008031void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008032{
8033 Mutex::Autolock _l(mLock);
8034 mTracks.add(record);
8035}
8036
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008037void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008038{
8039 Mutex::Autolock _l(mLock);
8040 destroyTrack_l(record);
8041}
8042
Mikhail Naganovdc769682018-05-04 15:34:08 -07008043void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008044{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008045 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008046 config->role = AUDIO_PORT_ROLE_SINK;
8047 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8048 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008049 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8050 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8051 config->flags.input = mInput->flags;
8052 }
Eric Laurent83b88082014-06-20 18:31:16 -07008053}
Eric Laurent1c333e22014-05-20 10:48:17 -07008054
Eric Laurent6acd1d42017-01-04 14:23:29 -08008055// ----------------------------------------------------------------------------
8056// Mmap
8057// ----------------------------------------------------------------------------
8058
8059AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8060 : mThread(thread)
8061{
Phil Burk9fabbf82017-08-03 12:02:00 -07008062 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008063}
8064
8065AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8066{
Phil Burk9fabbf82017-08-03 12:02:00 -07008067 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008068}
8069
8070status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8071 struct audio_mmap_buffer_info *info)
8072{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008073 return mThread->createMmapBuffer(minSizeFrames, info);
8074}
8075
8076status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8077{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008078 return mThread->getMmapPosition(position);
8079}
8080
Eric Laurenta54f1282017-07-01 19:39:32 -07008081status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008082 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008083
8084{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008085 return mThread->start(client, handle);
8086}
8087
8088status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8089{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008090 return mThread->stop(handle);
8091}
8092
Eric Laurent18b57012017-02-13 16:23:52 -08008093status_t AudioFlinger::MmapThreadHandle::standby()
8094{
Eric Laurent18b57012017-02-13 16:23:52 -08008095 return mThread->standby();
8096}
8097
Eric Laurent6acd1d42017-01-04 14:23:29 -08008098
8099AudioFlinger::MmapThread::MmapThread(
8100 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8101 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8102 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8103 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008104 mSessionId(AUDIO_SESSION_NONE),
8105 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008106 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008107 mActiveTracks(&this->mLocalLog),
8108 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8109 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008110{
Eric Laurent18b57012017-02-13 16:23:52 -08008111 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008112 readHalParameters_l();
8113}
8114
8115AudioFlinger::MmapThread::~MmapThread()
8116{
Eric Laurent18b57012017-02-13 16:23:52 -08008117 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008118}
8119
8120void AudioFlinger::MmapThread::onFirstRef()
8121{
8122 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8123}
8124
8125void AudioFlinger::MmapThread::disconnect()
8126{
Eric Laurent331679c2018-04-16 17:03:16 -07008127 ActiveTracks<MmapTrack> activeTracks;
8128 {
8129 Mutex::Autolock _l(mLock);
8130 for (const sp<MmapTrack> &t : mActiveTracks) {
8131 activeTracks.add(t);
8132 }
8133 }
8134 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008135 stop(t->portId());
8136 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008137 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008138 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008139 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008140 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008141 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008142 }
8143}
8144
8145
8146void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8147 audio_stream_type_t streamType __unused,
8148 audio_session_t sessionId,
8149 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008150 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008151 audio_port_handle_t portId)
8152{
8153 mAttr = *attr;
8154 mSessionId = sessionId;
8155 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008156 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008157 mPortId = portId;
8158}
8159
8160status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8161 struct audio_mmap_buffer_info *info)
8162{
8163 if (mHalStream == 0) {
8164 return NO_INIT;
8165 }
Eric Laurent18b57012017-02-13 16:23:52 -08008166 mStandby = true;
8167 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008168 return mHalStream->createMmapBuffer(minSizeFrames, info);
8169}
8170
8171status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8172{
8173 if (mHalStream == 0) {
8174 return NO_INIT;
8175 }
8176 return mHalStream->getMmapPosition(position);
8177}
8178
Eric Laurent331679c2018-04-16 17:03:16 -07008179status_t AudioFlinger::MmapThread::exitStandby()
8180{
8181 status_t ret = mHalStream->start();
8182 if (ret != NO_ERROR) {
8183 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8184 return ret;
8185 }
8186 mStandby = false;
8187 return NO_ERROR;
8188}
8189
Eric Laurenta54f1282017-07-01 19:39:32 -07008190status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008191 audio_port_handle_t *handle)
8192{
Eric Laurenta54f1282017-07-01 19:39:32 -07008193 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8194 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008195 if (mHalStream == 0) {
8196 return NO_INIT;
8197 }
8198
8199 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008200
Eric Laurenta54f1282017-07-01 19:39:32 -07008201 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008202 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008203 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008204 }
8205
8206 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8207
8208 audio_io_handle_t io = mId;
8209 if (isOutput()) {
8210 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8211 config.sample_rate = mSampleRate;
8212 config.channel_mask = mChannelMask;
8213 config.format = mFormat;
8214 audio_stream_type_t stream = streamType();
8215 audio_output_flags_t flags =
8216 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008217 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008218 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8219 mSessionId,
8220 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008221 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008222 client.clientUid,
8223 &config,
8224 flags,
8225 &deviceId,
8226 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008227 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008228 audio_config_base_t config;
8229 config.sample_rate = mSampleRate;
8230 config.channel_mask = mChannelMask;
8231 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008232 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008233 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8234 mSessionId,
8235 client.clientPid,
8236 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008237 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008238 &config,
8239 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8240 &deviceId,
8241 &portId);
8242 }
8243 // APM should not chose a different input or output stream for the same set of attributes
8244 // and audo configuration
8245 if (ret != NO_ERROR || io != mId) {
8246 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8247 __FUNCTION__, ret, io, mId);
8248 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008249 }
8250
Eric Laurent331679c2018-04-16 17:03:16 -07008251 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008252 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008253 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008254 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008255 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008256 }
8257
Eric Laurent331679c2018-04-16 17:03:16 -07008258 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008259 // abort if start is rejected by audio policy manager
8260 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008261 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008262 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008263 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008264 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008265 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008266 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008267 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008268 }
Eric Laurent331679c2018-04-16 17:03:16 -07008269 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008270 } else {
8271 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008272 }
8273 return PERMISSION_DENIED;
8274 }
8275
Eric Laurent67f97292018-04-20 18:05:41 -07008276 if (isOutput()) {
8277 // force volume update when a new track is added
8278 mHalVolFloat = -1.0f;
8279 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008280 for (const sp<MmapTrack> &track : mActiveTracks) {
8281 if (track->isSilenced_l() && track->uid() != client.clientUid)
8282 track->invalidate();
8283 }
8284 }
8285
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008286 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8287 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008288 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008289
Eric Laurent331679c2018-04-16 17:03:16 -07008290 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008291 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008292 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008293 if (chain != 0) {
8294 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8295 chain->incTrackCnt();
8296 chain->incActiveTrackCnt();
8297 }
8298
8299 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008300 broadcast_l();
8301
Eric Laurenta54f1282017-07-01 19:39:32 -07008302 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008303
8304 return NO_ERROR;
8305}
8306
8307status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8308{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008309 ALOGV("%s handle %d", __FUNCTION__, handle);
8310
8311 if (mHalStream == 0) {
8312 return NO_INIT;
8313 }
8314
Eric Laurenta54f1282017-07-01 19:39:32 -07008315 if (handle == mPortId) {
8316 mHalStream->stop();
8317 return NO_ERROR;
8318 }
8319
Eric Laurent331679c2018-04-16 17:03:16 -07008320 Mutex::Autolock _l(mLock);
8321
Eric Laurent6acd1d42017-01-04 14:23:29 -08008322 sp<MmapTrack> track;
8323 for (const sp<MmapTrack> &t : mActiveTracks) {
8324 if (handle == t->portId()) {
8325 track = t;
8326 break;
8327 }
8328 }
8329 if (track == 0) {
8330 return BAD_VALUE;
8331 }
8332
8333 mActiveTracks.remove(track);
8334
Eric Laurent331679c2018-04-16 17:03:16 -07008335 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008336 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008337 AudioSystem::stopOutput(track->portId());
8338 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008339 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008340 AudioSystem::stopInput(track->portId());
8341 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008342 }
Eric Laurent331679c2018-04-16 17:03:16 -07008343 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008344
8345 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8346 if (chain != 0) {
8347 chain->decActiveTrackCnt();
8348 chain->decTrackCnt();
8349 }
8350
8351 broadcast_l();
8352
Eric Laurent6acd1d42017-01-04 14:23:29 -08008353 return NO_ERROR;
8354}
8355
Eric Laurent18b57012017-02-13 16:23:52 -08008356status_t AudioFlinger::MmapThread::standby()
8357{
8358 ALOGV("%s", __FUNCTION__);
8359
8360 if (mHalStream == 0) {
8361 return NO_INIT;
8362 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008363 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008364 return INVALID_OPERATION;
8365 }
8366 mHalStream->standby();
8367 mStandby = true;
8368 releaseWakeLock();
8369 return NO_ERROR;
8370}
8371
Eric Laurent6acd1d42017-01-04 14:23:29 -08008372
8373void AudioFlinger::MmapThread::readHalParameters_l()
8374{
8375 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8376 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8377 mFormat = mHALFormat;
8378 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8379 result = mHalStream->getFrameSize(&mFrameSize);
8380 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8381 result = mHalStream->getBufferSize(&mBufferSize);
8382 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8383 mFrameCount = mBufferSize / mFrameSize;
8384}
8385
8386bool AudioFlinger::MmapThread::threadLoop()
8387{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008388 checkSilentMode_l();
8389
8390 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8391
8392 while (!exitPending())
8393 {
8394 Mutex::Autolock _l(mLock);
8395 Vector< sp<EffectChain> > effectChains;
8396
8397 if (mSignalPending) {
8398 // A signal was raised while we were unlocked
8399 mSignalPending = false;
8400 } else {
8401 if (mConfigEvents.isEmpty()) {
8402 // we're about to wait, flush the binder command buffer
8403 IPCThreadState::self()->flushCommands();
8404
8405 if (exitPending()) {
8406 break;
8407 }
8408
Eric Laurent6acd1d42017-01-04 14:23:29 -08008409 // wait until we have something to do...
8410 ALOGV("%s going to sleep", myName.string());
8411 mWaitWorkCV.wait(mLock);
8412 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008413
8414 checkSilentMode_l();
8415
8416 continue;
8417 }
8418 }
8419
8420 processConfigEvents_l();
8421
8422 processVolume_l();
8423
8424 checkInvalidTracks_l();
8425
8426 mActiveTracks.updatePowerState(this);
8427
Kevin Rocard069c2712018-03-29 19:09:14 -07008428 updateMetadata_l();
8429
Eric Laurent6acd1d42017-01-04 14:23:29 -08008430 lockEffectChains_l(effectChains);
8431 for (size_t i = 0; i < effectChains.size(); i ++) {
8432 effectChains[i]->process_l();
8433 }
8434 // enable changes in effect chain
8435 unlockEffectChains(effectChains);
8436 // Effect chains will be actually deleted here if they were removed from
8437 // mEffectChains list during mixing or effects processing
8438 }
8439
8440 threadLoop_exit();
8441
8442 if (!mStandby) {
8443 threadLoop_standby();
8444 mStandby = true;
8445 }
8446
Eric Laurent6acd1d42017-01-04 14:23:29 -08008447 ALOGV("Thread %p type %d exiting", this, mType);
8448 return false;
8449}
8450
8451// checkForNewParameter_l() must be called with ThreadBase::mLock held
8452bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8453 status_t& status)
8454{
8455 AudioParameter param = AudioParameter(keyValuePair);
8456 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008457 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008458 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008459 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008460 // forward device change to effects that have requested to be
8461 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008462 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008463 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008464 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008465 }
8466 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008467 if (audio_is_output_devices(device)) {
8468 mOutDevice = device;
8469 if (!isOutput()) {
8470 sendToHal = false;
8471 }
8472 } else {
8473 mInDevice = device;
8474 if (device != AUDIO_DEVICE_NONE) {
8475 mPrevInDevice = value;
8476 }
8477 // TODO: implement and call checkBtNrec_l();
8478 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008479 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008480 if (sendToHal) {
8481 status = mHalStream->setParameters(keyValuePair);
8482 } else {
8483 status = NO_ERROR;
8484 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008485
8486 return false;
8487}
8488
8489String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8490{
8491 Mutex::Autolock _l(mLock);
8492 String8 out_s8;
8493 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8494 return out_s8;
8495 }
8496 return String8();
8497}
8498
8499void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8500 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8501
8502 desc->mIoHandle = mId;
8503
8504 switch (event) {
8505 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008506 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008507 case AUDIO_INPUT_CONFIG_CHANGED:
8508 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008509 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008510 case AUDIO_OUTPUT_CONFIG_CHANGED:
8511 desc->mPatch = mPatch;
8512 desc->mChannelMask = mChannelMask;
8513 desc->mSamplingRate = mSampleRate;
8514 desc->mFormat = mFormat;
8515 desc->mFrameCount = mFrameCount;
8516 desc->mFrameCountHAL = mFrameCount;
8517 desc->mLatency = 0;
8518 break;
8519
8520 case AUDIO_INPUT_CLOSED:
8521 case AUDIO_OUTPUT_CLOSED:
8522 default:
8523 break;
8524 }
8525 mAudioFlinger->ioConfigChanged(event, desc, pid);
8526}
8527
8528status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8529 audio_patch_handle_t *handle)
8530{
8531 status_t status = NO_ERROR;
8532
8533 // store new device and send to effects
8534 audio_devices_t type = AUDIO_DEVICE_NONE;
8535 audio_port_handle_t deviceId;
8536 if (isOutput()) {
8537 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8538 type |= patch->sinks[i].ext.device.type;
8539 }
8540 deviceId = patch->sinks[0].id;
8541 } else {
8542 type = patch->sources[0].ext.device.type;
8543 deviceId = patch->sources[0].id;
8544 }
8545
8546 for (size_t i = 0; i < mEffectChains.size(); i++) {
8547 mEffectChains[i]->setDevice_l(type);
8548 }
8549
8550 if (isOutput()) {
8551 mOutDevice = type;
8552 } else {
8553 mInDevice = type;
8554 // store new source and send to effects
8555 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8556 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8557 for (size_t i = 0; i < mEffectChains.size(); i++) {
8558 mEffectChains[i]->setAudioSource_l(mAudioSource);
8559 }
8560 }
8561 }
8562
8563 if (mAudioHwDev->supportsAudioPatches()) {
8564 status = mHalDevice->createAudioPatch(patch->num_sources,
8565 patch->sources,
8566 patch->num_sinks,
8567 patch->sinks,
8568 handle);
8569 } else {
8570 char *address;
8571 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8572 //FIXME: we only support address on first sink with HAL version < 3.0
8573 address = audio_device_address_to_parameter(
8574 patch->sinks[0].ext.device.type,
8575 patch->sinks[0].ext.device.address);
8576 } else {
8577 address = (char *)calloc(1, 1);
8578 }
8579 AudioParameter param = AudioParameter(String8(address));
8580 free(address);
8581 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8582 if (!isOutput()) {
8583 param.addInt(String8(AudioParameter::keyInputSource),
8584 (int)patch->sinks[0].ext.mix.usecase.source);
8585 }
8586 status = mHalStream->setParameters(param.toString());
8587 *handle = AUDIO_PATCH_HANDLE_NONE;
8588 }
8589
8590 if (isOutput() && mPrevOutDevice != mOutDevice) {
8591 mPrevOutDevice = type;
8592 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008593 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008594 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008595 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008596 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008597 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008598 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008599 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008600 }
8601 if (!isOutput() && mPrevInDevice != mInDevice) {
8602 mPrevInDevice = type;
8603 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008604 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008605 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008606 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008607 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008608 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008609 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008610 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008611 }
8612 return status;
8613}
8614
8615status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8616{
8617 status_t status = NO_ERROR;
8618
8619 mInDevice = AUDIO_DEVICE_NONE;
8620
8621 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8622 supportsAudioPatches : false;
8623
8624 if (supportsAudioPatches) {
8625 status = mHalDevice->releaseAudioPatch(handle);
8626 } else {
8627 AudioParameter param;
8628 param.addInt(String8(AudioParameter::keyRouting), 0);
8629 status = mHalStream->setParameters(param.toString());
8630 }
8631 return status;
8632}
8633
Mikhail Naganovdc769682018-05-04 15:34:08 -07008634void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008635{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008636 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008637 if (isOutput()) {
8638 config->role = AUDIO_PORT_ROLE_SOURCE;
8639 config->ext.mix.hw_module = mAudioHwDev->handle();
8640 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8641 } else {
8642 config->role = AUDIO_PORT_ROLE_SINK;
8643 config->ext.mix.hw_module = mAudioHwDev->handle();
8644 config->ext.mix.usecase.source = mAudioSource;
8645 }
8646}
8647
8648status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8649{
8650 audio_session_t session = chain->sessionId();
8651
8652 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8653 // Attach all tracks with same session ID to this chain.
8654 // indicate all active tracks in the chain
8655 for (const sp<MmapTrack> &track : mActiveTracks) {
8656 if (session == track->sessionId()) {
8657 chain->incTrackCnt();
8658 chain->incActiveTrackCnt();
8659 }
8660 }
8661
8662 chain->setThread(this);
8663 chain->setInBuffer(nullptr);
8664 chain->setOutBuffer(nullptr);
8665 chain->syncHalEffectsState();
8666
8667 mEffectChains.add(chain);
8668 checkSuspendOnAddEffectChain_l(chain);
8669 return NO_ERROR;
8670}
8671
8672size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8673{
8674 audio_session_t session = chain->sessionId();
8675
8676 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8677
8678 for (size_t i = 0; i < mEffectChains.size(); i++) {
8679 if (chain == mEffectChains[i]) {
8680 mEffectChains.removeAt(i);
8681 // detach all active tracks from the chain
8682 // detach all tracks with same session ID from this chain
8683 for (const sp<MmapTrack> &track : mActiveTracks) {
8684 if (session == track->sessionId()) {
8685 chain->decActiveTrackCnt();
8686 chain->decTrackCnt();
8687 }
8688 }
8689 break;
8690 }
8691 }
8692 return mEffectChains.size();
8693}
8694
8695// hasAudioSession_l() must be called with ThreadBase::mLock held
8696uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8697{
8698 uint32_t result = 0;
8699 if (getEffectChain_l(sessionId) != 0) {
8700 result = EFFECT_SESSION;
8701 }
8702
8703 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8704 sp<MmapTrack> track = mActiveTracks[i];
8705 if (sessionId == track->sessionId()) {
8706 result |= TRACK_SESSION;
8707 if (track->isFastTrack()) {
8708 result |= FAST_SESSION;
8709 }
8710 break;
8711 }
8712 }
8713
8714 return result;
8715}
8716
8717void AudioFlinger::MmapThread::threadLoop_standby()
8718{
8719 mHalStream->standby();
8720}
8721
8722void AudioFlinger::MmapThread::threadLoop_exit()
8723{
Phil Burk7dce7282017-09-27 13:51:41 -07008724 // Do not call callback->onTearDown() because it is redundant for thread exit
8725 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008726}
8727
8728status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8729{
8730 return BAD_VALUE;
8731}
8732
8733bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8734{
8735 return false;
8736}
8737
8738status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8739 const effect_descriptor_t *desc, audio_session_t sessionId)
8740{
8741 // No global effect sessions on mmap threads
8742 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8743 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8744 desc->name, mThreadName);
8745 return BAD_VALUE;
8746 }
8747
8748 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8749 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8750 desc->name);
8751 return BAD_VALUE;
8752 }
8753 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008754 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8755 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008756 return BAD_VALUE;
8757 }
8758
8759 // Only allow effects without processing load or latency
8760 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8761 return BAD_VALUE;
8762 }
8763
8764 return NO_ERROR;
8765
8766}
8767
8768void AudioFlinger::MmapThread::checkInvalidTracks_l()
8769{
8770 for (const sp<MmapTrack> &track : mActiveTracks) {
8771 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008772 sp<MmapStreamCallback> callback = mCallback.promote();
8773 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008774 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008775 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008776 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008777 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8778 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8779 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008780 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008781 }
8782 }
8783}
8784
8785void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8786{
8787 dumpInternals(fd, args);
8788 dumpTracks(fd, args);
8789 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008790 dprintf(fd, " Local log:\n");
8791 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008792}
8793
8794void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8795{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008796 dumpBase(fd, args);
8797
8798 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8799 mAttr.content_type, mAttr.usage, mAttr.source);
8800 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07008801 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008802 dprintf(fd, " No active clients\n");
8803 }
8804}
8805
8806void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8807{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008808 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008809 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008810 dprintf(fd, " %zu Tracks\n", numtracks);
8811 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008812 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008813 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008814 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008815 for (size_t i = 0; i < numtracks ; ++i) {
8816 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008817 result.append(prefix);
8818 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008819 }
8820 } else {
8821 dprintf(fd, "\n");
8822 }
8823 write(fd, result.string(), result.size());
8824}
8825
8826AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8827 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8828 AudioHwDevice *hwDev, AudioStreamOut *output,
8829 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8830 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8831 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008832 mStreamVolume(1.0),
8833 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008834 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008835{
8836 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8837 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8838 mMasterVolume = audioFlinger->masterVolume_l();
8839 mMasterMute = audioFlinger->masterMute_l();
8840 if (mAudioHwDev) {
8841 if (mAudioHwDev->canSetMasterVolume()) {
8842 mMasterVolume = 1.0;
8843 }
8844
8845 if (mAudioHwDev->canSetMasterMute()) {
8846 mMasterMute = false;
8847 }
8848 }
8849}
8850
8851void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8852 audio_stream_type_t streamType,
8853 audio_session_t sessionId,
8854 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008855 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008856 audio_port_handle_t portId)
8857{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008858 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008859 mStreamType = streamType;
8860}
8861
8862AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8863{
8864 Mutex::Autolock _l(mLock);
8865 AudioStreamOut *output = mOutput;
8866 mOutput = NULL;
8867 return output;
8868}
8869
8870void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8871{
8872 Mutex::Autolock _l(mLock);
8873 // Don't apply master volume in SW if our HAL can do it for us.
8874 if (mAudioHwDev &&
8875 mAudioHwDev->canSetMasterVolume()) {
8876 mMasterVolume = 1.0;
8877 } else {
8878 mMasterVolume = value;
8879 }
8880}
8881
8882void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8883{
8884 Mutex::Autolock _l(mLock);
8885 // Don't apply master mute in SW if our HAL can do it for us.
8886 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8887 mMasterMute = false;
8888 } else {
8889 mMasterMute = muted;
8890 }
8891}
8892
8893void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8894{
8895 Mutex::Autolock _l(mLock);
8896 if (stream == mStreamType) {
8897 mStreamVolume = value;
8898 broadcast_l();
8899 }
8900}
8901
8902float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8903{
8904 Mutex::Autolock _l(mLock);
8905 if (stream == mStreamType) {
8906 return mStreamVolume;
8907 }
8908 return 0.0f;
8909}
8910
8911void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8912{
8913 Mutex::Autolock _l(mLock);
8914 if (stream == mStreamType) {
8915 mStreamMute= muted;
8916 broadcast_l();
8917 }
8918}
8919
8920void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8921{
8922 Mutex::Autolock _l(mLock);
8923 if (streamType == mStreamType) {
8924 for (const sp<MmapTrack> &track : mActiveTracks) {
8925 track->invalidate();
8926 }
8927 broadcast_l();
8928 }
8929}
8930
8931void AudioFlinger::MmapPlaybackThread::processVolume_l()
8932{
8933 float volume;
8934
8935 if (mMasterMute || mStreamMute) {
8936 volume = 0;
8937 } else {
8938 volume = mMasterVolume * mStreamVolume;
8939 }
8940
8941 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008942
8943 // Convert volumes from float to 8.24
8944 uint32_t vol = (uint32_t)(volume * (1 << 24));
8945
8946 // Delegate volume control to effect in track effect chain if needed
8947 // only one effect chain can be present on DirectOutputThread, so if
8948 // there is one, the track is connected to it
8949 if (!mEffectChains.isEmpty()) {
8950 mEffectChains[0]->setVolume_l(&vol, &vol);
8951 volume = (float)vol / (1 << 24);
8952 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008953 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008954 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8955 mHalVolFloat = volume; // HW volume control worked, so update value.
8956 mNoCallbackWarningCount = 0;
8957 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008958 sp<MmapStreamCallback> callback = mCallback.promote();
8959 if (callback != 0) {
8960 int channelCount;
8961 if (isOutput()) {
8962 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8963 } else {
8964 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8965 }
8966 Vector<float> values;
8967 for (int i = 0; i < channelCount; i++) {
8968 values.add(volume);
8969 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008970 mHalVolFloat = volume; // SW volume control worked, so update value.
8971 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008972 mLock.unlock();
8973 callback->onVolumeChanged(mChannelMask, values);
8974 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008975 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008976 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8977 ALOGW("Could not set MMAP stream volume: no volume callback!");
8978 mNoCallbackWarningCount++;
8979 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008980 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008981 }
8982 }
8983}
8984
Kevin Rocard069c2712018-03-29 19:09:14 -07008985void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8986{
8987 if (mOutput == nullptr || mOutput->stream == nullptr ||
8988 !mActiveTracks.readAndClearHasChanged()) {
8989 return;
8990 }
8991 StreamOutHalInterface::SourceMetadata metadata;
8992 for (const sp<MmapTrack> &track : mActiveTracks) {
8993 // No track is invalid as this is called after prepareTrack_l in the same critical section
8994 metadata.tracks.push_back({
8995 .usage = track->attributes().usage,
8996 .content_type = track->attributes().content_type,
8997 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8998 });
8999 }
9000 mOutput->stream->updateSourceMetadata(metadata);
9001}
9002
Eric Laurent6acd1d42017-01-04 14:23:29 -08009003void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9004{
9005 if (!mMasterMute) {
9006 char value[PROPERTY_VALUE_MAX];
9007 if (property_get("ro.audio.silent", value, "0") > 0) {
9008 char *endptr;
9009 unsigned long ul = strtoul(value, &endptr, 0);
9010 if (*endptr == '\0' && ul != 0) {
9011 ALOGD("Silence is golden");
9012 // The setprop command will not allow a property to be changed after
9013 // the first time it is set, so we don't have to worry about un-muting.
9014 setMasterMute_l(true);
9015 }
9016 }
9017 }
9018}
9019
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009020void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9021{
9022 MmapThread::toAudioPortConfig(config);
9023 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9024 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9025 config->flags.output = mOutput->flags;
9026 }
9027}
9028
Eric Laurent6acd1d42017-01-04 14:23:29 -08009029void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9030{
9031 MmapThread::dumpInternals(fd, args);
9032
Glenn Kastend3bb6452016-12-05 18:14:37 -08009033 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9034 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009035 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9036}
9037
9038AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9039 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9040 AudioHwDevice *hwDev, AudioStreamIn *input,
9041 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9042 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9043 mInput(input)
9044{
9045 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9046 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9047}
9048
Eric Laurent331679c2018-04-16 17:03:16 -07009049status_t AudioFlinger::MmapCaptureThread::exitStandby()
9050{
9051 mInput->stream->setGain(1.0f);
9052 return MmapThread::exitStandby();
9053}
9054
Eric Laurent6acd1d42017-01-04 14:23:29 -08009055AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9056{
9057 Mutex::Autolock _l(mLock);
9058 AudioStreamIn *input = mInput;
9059 mInput = NULL;
9060 return input;
9061}
Kevin Rocard069c2712018-03-29 19:09:14 -07009062
Eric Laurent331679c2018-04-16 17:03:16 -07009063
9064void AudioFlinger::MmapCaptureThread::processVolume_l()
9065{
9066 bool changed = false;
9067 bool silenced = false;
9068
9069 sp<MmapStreamCallback> callback = mCallback.promote();
9070 if (callback == 0) {
9071 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9072 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9073 mNoCallbackWarningCount++;
9074 }
9075 }
9076
9077 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9078 // track is silenced and unmute otherwise
9079 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9080 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9081 changed = true;
9082 silenced = mActiveTracks[i]->isSilenced_l();
9083 }
9084 }
9085
9086 if (changed) {
9087 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9088 }
9089}
9090
Kevin Rocard069c2712018-03-29 19:09:14 -07009091void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9092{
9093 if (mInput == nullptr || mInput->stream == nullptr ||
9094 !mActiveTracks.readAndClearHasChanged()) {
9095 return;
9096 }
9097 StreamInHalInterface::SinkMetadata metadata;
9098 for (const sp<MmapTrack> &track : mActiveTracks) {
9099 // No track is invalid as this is called after prepareTrack_l in the same critical section
9100 metadata.tracks.push_back({
9101 .source = track->attributes().source,
9102 .gain = 1, // capture tracks do not have volumes
9103 });
9104 }
9105 mInput->stream->updateSinkMetadata(metadata);
9106}
9107
Eric Laurent331679c2018-04-16 17:03:16 -07009108void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9109{
9110 Mutex::Autolock _l(mLock);
9111 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9112 if (mActiveTracks[i]->uid() == uid) {
9113 mActiveTracks[i]->setSilenced_l(silenced);
9114 broadcast_l();
9115 }
9116 }
9117}
9118
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009119void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9120{
9121 MmapThread::toAudioPortConfig(config);
9122 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9123 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9124 config->flags.input = mInput->flags;
9125 }
9126}
9127
Glenn Kasten63238ef2015-03-02 15:50:29 -08009128} // namespace android