blob: e07fb06194b6e57fb04cea5e2c6d7355f242395e [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>
jiabin10d86fd2019-10-31 17:20:42 -070032#include <media/AudioContainers.h>
33#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070034#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070035#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080036#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070037#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080039#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070042#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010043#include <audio_utils/Balance.h>
jiabin245cdd92018-12-07 17:55:15 -080044#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080045#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080047#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070048#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070049#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070050#include <system/audio_effects/effect_ns.h>
51#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070055#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056#include <media/nbaio/AudioStreamOutSink.h>
57#include <media/nbaio/MonoPipe.h>
58#include <media/nbaio/MonoPipeReader.h>
59#include <media/nbaio/Pipe.h>
60#include <media/nbaio/PipeReader.h>
61#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080062#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063
Mikhail Naganov2996f672019-04-18 12:29:59 -070064#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080065#include <powermanager/PowerManager.h>
66
Kevin Rocard7588ff42018-01-08 11:11:30 -080067#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070068#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080069
Eric Laurent81784c32012-11-19 14:55:58 -080070#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080071#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070072#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070073#include <mediautils/SchedulingPolicyService.h>
74#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080075
Eric Laurent81784c32012-11-19 14:55:58 -080076#ifdef ADD_BATTERY_DATA
77#include <media/IMediaPlayerService.h>
78#include <media/IMediaDeathNotifier.h>
79#endif
80
Eric Laurent81784c32012-11-19 14:55:58 -080081#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070082#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083#include <cpustats/ThreadCpuUsage.h>
84#endif
85
Glenn Kastenc05b8d72016-03-24 09:48:17 -070086#include "AutoPark.h"
87
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080088#include <pthread.h>
89#include "TypedLogger.h"
90
Eric Laurent81784c32012-11-19 14:55:58 -080091// ----------------------------------------------------------------------------
92
93// Note: the following macro is used for extremely verbose logging message. In
94// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
95// 0; but one side effect of this is to turn all LOGV's as well. Some messages
96// are so verbose that we want to suppress them even when we have ALOG_ASSERT
97// turned on. Do not uncomment the #def below unless you really know what you
98// are doing and want to see all of the extremely verbose messages.
99//#define VERY_VERY_VERBOSE_LOGGING
100#ifdef VERY_VERY_VERBOSE_LOGGING
101#define ALOGVV ALOGV
102#else
103#define ALOGVV(a...) do { } while(0)
104#endif
105
Andy Hung6770c6f2015-04-07 13:43:36 -0700106// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700107#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700108template <typename T>
109static inline T min(const T& a, const T& b)
110{
111 return a < b ? a : b;
112}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113
Eric Laurent81784c32012-11-19 14:55:58 -0800114namespace android {
115
116// retry counts for buffer fill timeout
117// 50 * ~20msecs = 1 second
118static const int8_t kMaxTrackRetries = 50;
119static const int8_t kMaxTrackStartupRetries = 50;
120// allow less retry attempts on direct output thread.
121// direct outputs can be a scarce resource in audio hardware and should
122// be released as quickly as possible.
123static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700124
Eric Laurent51716182016-02-29 18:00:56 -0800125
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127// don't warn about blocked writes or record buffer overflows more often than this
128static const nsecs_t kWarningThrottleNs = seconds(5);
129
130// RecordThread loop sleep time upon application overrun or audio HAL read error
131static const int kRecordThreadSleepUs = 5000;
132
Eric Laurent10351942014-05-08 18:49:52 -0700133// maximum time to wait in sendConfigEvent_l() for a status to be received
134static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800135
136// minimum sleep time for the mixer thread loop when tracks are active but in underrun
137static const uint32_t kMinThreadSleepTimeUs = 5000;
138// maximum divider applied to the active sleep time in the mixer thread loop
139static const uint32_t kMaxThreadSleepTimeShift = 2;
140
Andy Hung09a50072014-02-27 14:30:47 -0800141// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700142// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800143static const uint32_t kMinNormalSinkBufferSizeMs = 20;
144// maximum normal sink buffer size
145static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800146
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700147// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
148// FIXME This should be based on experimentally observed scheduling jitter
149static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
150
Eric Laurent972a1732013-09-04 09:42:59 -0700151// Offloaded output thread standby delay: allows track transition without going to standby
152static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
153
Eric Laurent51716182016-02-29 18:00:56 -0800154// Direct output thread minimum sleep time in idle or active(underrun) state
155static const nsecs_t kDirectMinSleepTimeUs = 10000;
156
Glenn Kasten1b291842016-07-18 14:55:21 -0700157// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
158// balance between power consumption and latency, and allows threads to be scheduled reliably
159// by the CFS scheduler.
160// FIXME Express other hardcoded references to 20ms with references to this constant and move
161// it appropriately.
162#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800163
Eric Laurent81784c32012-11-19 14:55:58 -0800164// Whether to use fast mixer
165static const enum {
166 FastMixer_Never, // never initialize or use: for debugging only
167 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
168 // normal mixer multiplier is 1
169 FastMixer_Static, // initialize if needed, then use all the time if initialized,
170 // multiplier is calculated based on min & max normal mixer buffer size
171 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
172 // multiplier is calculated based on min & max normal mixer buffer size
173 // FIXME for FastMixer_Dynamic:
174 // Supporting this option will require fixing HALs that can't handle large writes.
175 // For example, one HAL implementation returns an error from a large write,
176 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
177 // We could either fix the HAL implementations, or provide a wrapper that breaks
178 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
179} kUseFastMixer = FastMixer_Static;
180
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181// Whether to use fast capture
182static const enum {
183 FastCapture_Never, // never initialize or use: for debugging only
184 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
185 FastCapture_Static, // initialize if needed, then use all the time if initialized
186} kUseFastCapture = FastCapture_Static;
187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// Priorities for requestPriority
189static const int kPriorityAudioApp = 2;
190static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700191static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800192
Glenn Kastenea38ee72016-04-18 11:08:01 -0700193// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
194// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
195// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700196
197// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800198static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800199
Glenn Kasten03490092014-05-27 12:30:54 -0700200// The minimum and maximum allowed values
201static const int kFastTrackMultiplierMin = 1;
202static const int kFastTrackMultiplierMax = 2;
203
204// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
205static int sFastTrackMultiplier = kFastTrackMultiplier;
206
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700207// See Thread::readOnlyHeap().
208// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
209// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
210// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700211static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700212
Eric Laurent81784c32012-11-19 14:55:58 -0800213// ----------------------------------------------------------------------------
214
Glenn Kasten03490092014-05-27 12:30:54 -0700215static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
216
217static void sFastTrackMultiplierInit()
218{
219 char value[PROPERTY_VALUE_MAX];
220 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
221 char *endptr;
222 unsigned long ul = strtoul(value, &endptr, 0);
223 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
224 sFastTrackMultiplier = (int) ul;
225 }
226 }
227}
228
229// ----------------------------------------------------------------------------
230
Eric Laurent81784c32012-11-19 14:55:58 -0800231#ifdef ADD_BATTERY_DATA
232// To collect the amplifier usage
233static void addBatteryData(uint32_t params) {
234 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
235 if (service == NULL) {
236 // it already logged
237 return;
238 }
239
240 service->addBatteryData(params);
241}
242#endif
243
Andy Hung3f0c9022016-01-15 17:49:46 -0800244// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
245struct {
246 // call when you acquire a partial wakelock
247 void acquire(const sp<IBinder> &wakeLockToken) {
248 pthread_mutex_lock(&mLock);
249 if (wakeLockToken.get() == nullptr) {
250 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
251 } else {
252 if (mCount == 0) {
253 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
254 }
255 ++mCount;
256 }
257 pthread_mutex_unlock(&mLock);
258 }
259
260 // call when you release a partial wakelock.
261 void release(const sp<IBinder> &wakeLockToken) {
262 if (wakeLockToken.get() == nullptr) {
263 return;
264 }
265 pthread_mutex_lock(&mLock);
266 if (--mCount < 0) {
267 ALOGE("negative wakelock count");
268 mCount = 0;
269 }
270 pthread_mutex_unlock(&mLock);
271 }
272
273 // retrieves the boottime timebase offset from monotonic.
274 int64_t getBoottimeOffset() {
275 pthread_mutex_lock(&mLock);
276 int64_t boottimeOffset = mBoottimeOffset;
277 pthread_mutex_unlock(&mLock);
278 return boottimeOffset;
279 }
280
281 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
282 // and the selected timebase.
283 // Currently only TIMEBASE_BOOTTIME is allowed.
284 //
285 // This only needs to be called upon acquiring the first partial wakelock
286 // after all other partial wakelocks are released.
287 //
288 // We do an empirical measurement of the offset rather than parsing
289 // /proc/timer_list since the latter is not a formal kernel ABI.
290 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
291 int clockbase;
292 switch (timebase) {
293 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
294 clockbase = SYSTEM_TIME_BOOTTIME;
295 break;
296 default:
297 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
298 break;
299 }
300 // try three times to get the clock offset, choose the one
301 // with the minimum gap in measurements.
302 const int tries = 3;
303 nsecs_t bestGap, measured;
304 for (int i = 0; i < tries; ++i) {
305 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
306 const nsecs_t tbase = systemTime(clockbase);
307 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
308 const nsecs_t gap = tmono2 - tmono;
309 if (i == 0 || gap < bestGap) {
310 bestGap = gap;
311 measured = tbase - ((tmono + tmono2) >> 1);
312 }
313 }
314
315 // to avoid micro-adjusting, we don't change the timebase
316 // unless it is significantly different.
317 //
318 // Assumption: It probably takes more than toleranceNs to
319 // suspend and resume the device.
320 static int64_t toleranceNs = 10000; // 10 us
321 if (llabs(*offset - measured) > toleranceNs) {
322 ALOGV("Adjusting timebase offset old: %lld new: %lld",
323 (long long)*offset, (long long)measured);
324 *offset = measured;
325 }
326 }
327
328 pthread_mutex_t mLock;
329 int32_t mCount;
330 int64_t mBoottimeOffset;
331} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800332
333// ----------------------------------------------------------------------------
334// CPU Stats
335// ----------------------------------------------------------------------------
336
337class CpuStats {
338public:
339 CpuStats();
340 void sample(const String8 &title);
341#ifdef DEBUG_CPU_USAGE
342private:
343 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700344 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800345
Andy Hung16698b82018-08-01 10:48:38 -0700346 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800347
348 int mCpuNum; // thread's current CPU number
349 int mCpukHz; // frequency of thread's current CPU in kHz
350#endif
351};
352
353CpuStats::CpuStats()
354#ifdef DEBUG_CPU_USAGE
355 : mCpuNum(-1), mCpukHz(-1)
356#endif
357{
358}
359
Glenn Kasten0f11b512014-01-31 16:18:54 -0800360void CpuStats::sample(const String8 &title
361#ifndef DEBUG_CPU_USAGE
362 __unused
363#endif
364 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800365#ifdef DEBUG_CPU_USAGE
366 // get current thread's delta CPU time in wall clock ns
367 double wcNs;
368 bool valid = mCpuUsage.sampleAndEnable(wcNs);
369
370 // record sample for wall clock statistics
371 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700372 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800373 }
374
375 // get the current CPU number
376 int cpuNum = sched_getcpu();
377
378 // get the current CPU frequency in kHz
379 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
380
381 // check if either CPU number or frequency changed
382 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
383 mCpuNum = cpuNum;
384 mCpukHz = cpukHz;
385 // ignore sample for purposes of cycles
386 valid = false;
387 }
388
389 // if no change in CPU number or frequency, then record sample for cycle statistics
390 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700391 const double cycles = wcNs * cpukHz * 0.000001;
392 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800393 }
394
Eric Tan5b13ff82018-07-27 11:20:17 -0700395 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800396 // mCpuUsage.elapsed() is expensive, so don't call it every loop
397 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700398 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800399 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700400 const double perLoop = elapsed / (double) n;
401 const double perLoop100 = perLoop * 0.01;
402 const double perLoop1k = perLoop * 0.001;
403 const double mean = mWcStats.getMean();
404 const double stddev = mWcStats.getStdDev();
405 const double minimum = mWcStats.getMin();
406 const double maximum = mWcStats.getMax();
407 const double meanCycles = mHzStats.getMean();
408 const double stddevCycles = mHzStats.getStdDev();
409 const double minCycles = mHzStats.getMin();
410 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800411 mCpuUsage.resetElapsed();
412 mWcStats.reset();
413 mHzStats.reset();
414 ALOGD("CPU usage for %s over past %.1f secs\n"
415 " (%u mixer loops at %.1f mean ms per loop):\n"
416 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
417 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
418 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
419 title.string(),
420 elapsed * .000000001, n, perLoop * .000001,
421 mean * .001,
422 stddev * .001,
423 minimum * .001,
424 maximum * .001,
425 mean / perLoop100,
426 stddev / perLoop100,
427 minimum / perLoop100,
428 maximum / perLoop100,
429 meanCycles / perLoop1k,
430 stddevCycles / perLoop1k,
431 minCycles / perLoop1k,
432 maxCycles / perLoop1k);
433
434 }
435 }
436#endif
437};
438
439// ----------------------------------------------------------------------------
440// ThreadBase
441// ----------------------------------------------------------------------------
442
Glenn Kasten97b7b752014-09-28 13:04:24 -0700443// static
444const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
445{
446 switch (type) {
447 case MIXER:
448 return "MIXER";
449 case DIRECT:
450 return "DIRECT";
451 case DUPLICATING:
452 return "DUPLICATING";
453 case RECORD:
454 return "RECORD";
455 case OFFLOAD:
456 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800457 case MMAP:
458 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700459 default:
460 return "unknown";
461 }
462}
463
Eric Laurent81784c32012-11-19 14:55:58 -0800464AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -0700465 type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800466 : Thread(false /*canCallJava*/),
467 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700468 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700469 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800470 // are set by PlaybackThread::readOutputParameters_l() or
471 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700472 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabin10d86fd2019-10-31 17:20:42 -0700473 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700474 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800475 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700476 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800477 mSystemReady(systemReady),
478 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800479{
Eric Laurent296fb132015-05-01 11:38:42 -0700480 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800481}
482
483AudioFlinger::ThreadBase::~ThreadBase()
484{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700485 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700486 mConfigEvents.clear();
487
Eric Laurent81784c32012-11-19 14:55:58 -0800488 // do not lock the mutex in destructor
489 releaseWakeLock_l();
490 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800491 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800492 binder->unlinkToDeath(mDeathRecipient);
493 }
Andy Hungd0979812019-02-21 15:51:44 -0800494
495 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800496}
497
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700498status_t AudioFlinger::ThreadBase::readyToRun()
499{
500 status_t status = initCheck();
501 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800502 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700503 } else {
504 ALOGE("No working audio driver found.");
505 }
506 return status;
507}
508
Eric Laurent81784c32012-11-19 14:55:58 -0800509void AudioFlinger::ThreadBase::exit()
510{
511 ALOGV("ThreadBase::exit");
512 // do any cleanup required for exit to succeed
513 preExit();
514 {
515 // This lock prevents the following race in thread (uniprocessor for illustration):
516 // if (!exitPending()) {
517 // // context switch from here to exit()
518 // // exit() calls requestExit(), what exitPending() observes
519 // // exit() calls signal(), which is dropped since no waiters
520 // // context switch back from exit() to here
521 // mWaitWorkCV.wait(...);
522 // // now thread is hung
523 // }
524 AutoMutex lock(mLock);
525 requestExit();
526 mWaitWorkCV.broadcast();
527 }
528 // When Thread::requestExitAndWait is made virtual and this method is renamed to
529 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
530 requestExitAndWait();
531}
532
533status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
534{
Eric Laurent81784c32012-11-19 14:55:58 -0800535 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
536 Mutex::Autolock _l(mLock);
537
Eric Laurent10351942014-05-08 18:49:52 -0700538 return sendSetParameterConfigEvent_l(keyValuePairs);
539}
540
541// sendConfigEvent_l() must be called with ThreadBase::mLock held
542// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
543status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
544{
545 status_t status = NO_ERROR;
546
Eric Laurent72e3f392015-05-20 14:43:50 -0700547 if (event->mRequiresSystemReady && !mSystemReady) {
548 event->mWaitStatus = false;
549 mPendingConfigEvents.add(event);
550 return status;
551 }
Eric Laurent10351942014-05-08 18:49:52 -0700552 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700553 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800554 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700555 mLock.unlock();
556 {
557 Mutex::Autolock _l(event->mLock);
558 while (event->mWaitStatus) {
559 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
560 event->mStatus = TIMED_OUT;
561 event->mWaitStatus = false;
562 }
563 }
564 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800565 }
Eric Laurent10351942014-05-08 18:49:52 -0700566 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800567 return status;
568}
569
Eric Laurent09f1ed22019-04-24 17:45:17 -0700570void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
571 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800572{
573 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700574 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800575}
576
577// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700578void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
579 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800580{
Andy Hungd0979812019-02-21 15:51:44 -0800581 // The audio statistics history is exponentially weighted to forget events
582 // about five or more seconds in the past. In order to have
583 // crisper statistics for mediametrics, we reset the statistics on
584 // an IoConfigEvent, to reflect different properties for a new device.
585 mIoJitterMs.reset();
586 mLatencyMs.reset();
587 mProcessTimeMs.reset();
588 mTimestampVerifier.discontinuity();
589
Eric Laurent09f1ed22019-04-24 17:45:17 -0700590 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700591 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800592}
593
Mikhail Naganov83f04272017-02-07 10:45:09 -0800594void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700595{
596 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800597 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700598}
599
Eric Laurent81784c32012-11-19 14:55:58 -0800600// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800601void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
602 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800604 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700605 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
Eric Laurent10351942014-05-08 18:49:52 -0700608// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
609status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Andy Hung2ddee192015-12-18 17:34:44 -0800611 sp<ConfigEvent> configEvent;
612 AudioParameter param(keyValuePair);
613 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700614 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800615 setMasterMono_l(value != 0);
616 if (param.size() == 1) {
617 return NO_ERROR; // should be a solo parameter - we don't pass down
618 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700619 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800620 configEvent = new SetParameterConfigEvent(param.toString());
621 } else {
622 configEvent = new SetParameterConfigEvent(keyValuePair);
623 }
Eric Laurent10351942014-05-08 18:49:52 -0700624 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700625}
626
Eric Laurent1c333e22014-05-20 10:48:17 -0700627status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
628 const struct audio_patch *patch,
629 audio_patch_handle_t *handle)
630{
631 Mutex::Autolock _l(mLock);
632 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
633 status_t status = sendConfigEvent_l(configEvent);
634 if (status == NO_ERROR) {
635 CreateAudioPatchConfigEventData *data =
636 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
637 *handle = data->mHandle;
638 }
639 return status;
640}
641
642status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
643 const audio_patch_handle_t handle)
644{
645 Mutex::Autolock _l(mLock);
646 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
647 return sendConfigEvent_l(configEvent);
648}
649
jiabin10d86fd2019-10-31 17:20:42 -0700650status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
651 const DeviceDescriptorBaseVector& outDevices)
652{
653 if (type() != RECORD) {
654 // The update out device operation is only for record thread.
655 return INVALID_OPERATION;
656 }
657 Mutex::Autolock _l(mLock);
658 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
659 return sendConfigEvent_l(configEvent);
660}
661
Eric Laurent1c333e22014-05-20 10:48:17 -0700662
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700663// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700664void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700665{
Eric Laurent10351942014-05-08 18:49:52 -0700666 bool configChanged = false;
667
Eric Laurent81784c32012-11-19 14:55:58 -0800668 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700669 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700670 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800671 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700672 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700673 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700674 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
675 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800676 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700677 true /*asynchronous*/);
678 if (err != 0) {
679 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700680 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 }
682 } break;
683 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700684 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700685 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700686 } break;
687 case CFG_EVENT_SET_PARAMETER: {
688 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
689 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
690 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700691 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
692 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700693 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700694 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700695 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700696 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700697 CreateAudioPatchConfigEventData *data =
698 (CreateAudioPatchConfigEventData *)event->mData.get();
699 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700700 const DeviceTypeSet newDevices = getDeviceTypes();
701 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
702 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
703 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 } break;
705 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700706 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700707 ReleaseAudioPatchConfigEventData *data =
708 (ReleaseAudioPatchConfigEventData *)event->mData.get();
709 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700710 const DeviceTypeSet newDevices = getDeviceTypes();
711 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
712 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
713 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
714 } break;
715 case CFG_EVENT_UPDATE_OUT_DEVICE: {
716 UpdateOutDevicesConfigEventData *data =
717 (UpdateOutDevicesConfigEventData *)event->mData.get();
718 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700720 default:
Eric Laurent10351942014-05-08 18:49:52 -0700721 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700722 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800723 }
Eric Laurent10351942014-05-08 18:49:52 -0700724 {
725 Mutex::Autolock _l(event->mLock);
726 if (event->mWaitStatus) {
727 event->mWaitStatus = false;
728 event->mCond.signal();
729 }
730 }
731 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
732 }
733
734 if (configChanged) {
735 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent81784c32012-11-19 14:55:58 -0800737}
738
Marco Nelissenb2208842014-02-07 14:00:50 -0800739String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
740 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700741 const audio_channel_representation_t representation =
742 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700743
744 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800745 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700746 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
747 if (output) {
748 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
749 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
750 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
751 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
752 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
757 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
758 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
759 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
760 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
765 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700766 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
767 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800768 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
769 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700770 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
771 } else {
772 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
773 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
774 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
775 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
776 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
781 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
782 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
783 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700784 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
785 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
786 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
787 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
788 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
789 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
791 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
792 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
793 }
794 const int len = s.length();
795 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700796 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 s.unlockBuffer(len - 2); // remove trailing ", "
798 }
799 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800800 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700801 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
802 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
803 return s;
804 default:
805 s.appendFormat("unknown mask, representation:%d bits:%#x",
806 representation, audio_channel_mask_get_bits(mask));
807 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800808 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800809}
810
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700811void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800812{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800813 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
814 this, mThreadName, getTid(), type(), threadTypeToString(type()));
815
Eric Laurent81784c32012-11-19 14:55:58 -0800816 bool locked = AudioFlinger::dumpTryLock(mLock);
817 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800818 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800819 }
820
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700821 dumpBase_l(fd, args);
822 dumpInternals_l(fd, args);
823 dumpTracks_l(fd, args);
824 dumpEffectChains_l(fd, args);
825
826 if (locked) {
827 mLock.unlock();
828 }
829
830 dprintf(fd, " Local log:\n");
831 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
832}
833
834void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
835{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700838 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700840 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700841 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700842 dprintf(fd, " Channel count: %u\n", mChannelCount);
843 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700845 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700846 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 size_t numConfig = mConfigEvents.size();
849 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700850 const size_t SIZE = 256;
851 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800852 for (size_t i = 0; i < numConfig; i++) {
853 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700854 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700856 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700858 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Andy Hung293558a2017-03-21 12:19:20 -0700860 // Note: output device may be used by capture threads for effects such as AEC.
jiabin10d86fd2019-10-31 17:20:42 -0700861 dprintf(fd, " Output devices: %s (%s)\n",
862 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
863 dprintf(fd, " Input device: %#x (%s)\n",
864 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800865 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800866
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700867 // Dump timestamp statistics for the Thread types that support it.
868 if (mType == RECORD
869 || mType == MIXER
870 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700871 || mType == DIRECT
872 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700873 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700874 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700875 }
876
Andy Hung446f4df2019-02-21 12:26:41 -0800877 if (mLastIoBeginNs > 0) { // MMAP may not set this
878 dprintf(fd, " Last %s occurred (msecs): %lld\n",
879 isOutput() ? "write" : "read",
880 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
881 }
882
883 if (mProcessTimeMs.getN() > 0) {
884 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
885 }
886
887 if (mIoJitterMs.getN() > 0) {
888 dprintf(fd, " Hal %s jitter ms stats: %s\n",
889 isOutput() ? "write" : "read",
890 mIoJitterMs.toString().c_str());
891 }
892
Andy Hunge6c37112019-02-26 17:38:10 -0800893 if (mLatencyMs.getN() > 0) {
894 dprintf(fd, " Threadloop %s latency stats: %s\n",
895 isOutput() ? "write" : "read",
896 mLatencyMs.toString().c_str());
897 }
Eric Laurent81784c32012-11-19 14:55:58 -0800898}
899
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700900void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800901{
902 const size_t SIZE = 256;
903 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800904
Marco Nelissenb2208842014-02-07 14:00:50 -0800905 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000906 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800907 write(fd, buffer, strlen(buffer));
908
Marco Nelissenb2208842014-02-07 14:00:50 -0800909 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800910 sp<EffectChain> chain = mEffectChains[i];
911 if (chain != 0) {
912 chain->dump(fd, args);
913 }
914 }
915}
916
Andy Hungdae27702016-10-31 14:01:16 -0700917void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800918{
919 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700920 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800921}
922
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100923String16 AudioFlinger::ThreadBase::getWakeLockTag()
924{
925 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800926 case MIXER:
927 return String16("AudioMix");
928 case DIRECT:
929 return String16("AudioDirectOut");
930 case DUPLICATING:
931 return String16("AudioDup");
932 case RECORD:
933 return String16("AudioIn");
934 case OFFLOAD:
935 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800936 case MMAP:
937 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800938 default:
939 ALOG_ASSERT(false);
940 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100941 }
942}
943
Andy Hungdae27702016-10-31 14:01:16 -0700944void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800945{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800947 if (mPowerManager != 0) {
948 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700949 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
950 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700951 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100952 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700953 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700954 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800955 if (status == NO_ERROR) {
956 mWakeLockToken = binder;
957 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800958 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800959 }
Wei Jia3f273d12015-11-24 09:06:49 -0800960
Andy Hung3f0c9022016-01-15 17:49:46 -0800961 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800962 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
963 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800964}
965
966void AudioFlinger::ThreadBase::releaseWakeLock()
967{
968 Mutex::Autolock _l(mLock);
969 releaseWakeLock_l();
970}
971
972void AudioFlinger::ThreadBase::releaseWakeLock_l()
973{
Andy Hung3f0c9022016-01-15 17:49:46 -0800974 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800975 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800976 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800977 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700978 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
979 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800980 }
981 mWakeLockToken.clear();
982 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800983}
984
985void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700986 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800987 // use checkService() to avoid blocking if power service is not up yet
988 sp<IBinder> binder =
989 defaultServiceManager()->checkService(String16("power"));
990 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800991 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800992 } else {
993 mPowerManager = interface_cast<IPowerManager>(binder);
994 binder->linkToDeath(mDeathRecipient);
995 }
996 }
997}
998
Andy Hungd01b0f12016-11-07 16:10:30 -0800999void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001000 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001001
1002#if !LOG_NDEBUG
1003 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001004 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001005 s << uid << " ";
1006 }
1007 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1008#endif
1009
Andy Hung438e7572015-12-14 15:51:17 -08001010 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1011 if (mSystemReady) {
1012 ALOGE("no wake lock to update, but system ready!");
1013 } else {
1014 ALOGW("no wake lock to update, system not ready yet");
1015 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001016 return;
1017 }
1018 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001019 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1020 status_t status = mPowerManager->updateWakeLockUids(
1021 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1022 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001023 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001024 }
1025}
1026
Eric Laurent81784c32012-11-19 14:55:58 -08001027void AudioFlinger::ThreadBase::clearPowerManager()
1028{
1029 Mutex::Autolock _l(mLock);
1030 releaseWakeLock_l();
1031 mPowerManager.clear();
1032}
1033
jiabin10d86fd2019-10-31 17:20:42 -07001034void AudioFlinger::ThreadBase::updateOutDevices(
1035 const DeviceDescriptorBaseVector& outDevices __unused)
1036{
1037 ALOGE("%s should only be called in RecordThread", __func__);
1038}
1039
Glenn Kasten0f11b512014-01-31 16:18:54 -08001040void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001041{
1042 sp<ThreadBase> thread = mThread.promote();
1043 if (thread != 0) {
1044 thread->clearPowerManager();
1045 }
1046 ALOGW("power manager service died !!!");
1047}
1048
Eric Laurent81784c32012-11-19 14:55:58 -08001049void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001050 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001051{
1052 sp<EffectChain> chain = getEffectChain_l(sessionId);
1053 if (chain != 0) {
1054 if (type != NULL) {
1055 chain->setEffectSuspended_l(type, suspend);
1056 } else {
1057 chain->setEffectSuspendedAll_l(suspend);
1058 }
1059 }
1060
1061 updateSuspendedSessions_l(type, suspend, sessionId);
1062}
1063
1064void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1065{
1066 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1067 if (index < 0) {
1068 return;
1069 }
1070
1071 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1072 mSuspendedSessions.valueAt(index);
1073
1074 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001075 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001076 for (int j = 0; j < desc->mRefCount; j++) {
1077 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1078 chain->setEffectSuspendedAll_l(true);
1079 } else {
1080 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1081 desc->mType.timeLow);
1082 chain->setEffectSuspended_l(&desc->mType, true);
1083 }
1084 }
1085 }
1086}
1087
1088void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1089 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001090 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001091{
1092 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1093
1094 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1095
1096 if (suspend) {
1097 if (index >= 0) {
1098 sessionEffects = mSuspendedSessions.valueAt(index);
1099 } else {
1100 mSuspendedSessions.add(sessionId, sessionEffects);
1101 }
1102 } else {
1103 if (index < 0) {
1104 return;
1105 }
1106 sessionEffects = mSuspendedSessions.valueAt(index);
1107 }
1108
1109
1110 int key = EffectChain::kKeyForSuspendAll;
1111 if (type != NULL) {
1112 key = type->timeLow;
1113 }
1114 index = sessionEffects.indexOfKey(key);
1115
1116 sp<SuspendedSessionDesc> desc;
1117 if (suspend) {
1118 if (index >= 0) {
1119 desc = sessionEffects.valueAt(index);
1120 } else {
1121 desc = new SuspendedSessionDesc();
1122 if (type != NULL) {
1123 desc->mType = *type;
1124 }
1125 sessionEffects.add(key, desc);
1126 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1127 }
1128 desc->mRefCount++;
1129 } else {
1130 if (index < 0) {
1131 return;
1132 }
1133 desc = sessionEffects.valueAt(index);
1134 if (--desc->mRefCount == 0) {
1135 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1136 sessionEffects.removeItemsAt(index);
1137 if (sessionEffects.isEmpty()) {
1138 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1139 sessionId);
1140 mSuspendedSessions.removeItem(sessionId);
1141 }
1142 }
1143 }
1144 if (!sessionEffects.isEmpty()) {
1145 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1146 }
1147}
1148
1149void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1150 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001151 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001152{
1153 Mutex::Autolock _l(mLock);
1154 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1155}
1156
1157void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1158 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001159 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001160{
1161 if (mType != RECORD) {
1162 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1163 // another session. This gives the priority to well behaved effect control panels
1164 // and applications not using global effects.
1165 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1166 // global effects
Eric Laurenta20c4e92019-11-12 15:55:51 -08001167 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001168 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1169 }
1170 }
1171
1172 sp<EffectChain> chain = getEffectChain_l(sessionId);
1173 if (chain != 0) {
1174 chain->checkSuspendOnEffectEnabled(effect, enabled);
1175 }
1176}
1177
Eric Laurent4c415062016-06-17 16:14:16 -07001178// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1179status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1180 const effect_descriptor_t *desc, audio_session_t sessionId)
1181{
Eric Laurenta20c4e92019-11-12 15:55:51 -08001182 // No global output effect sessions on record threads
1183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1184 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001185 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1186 desc->name, mThreadName);
1187 return BAD_VALUE;
1188 }
1189 // only pre processing effects on record thread
1190 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1191 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1192 desc->name, mThreadName);
1193 return BAD_VALUE;
1194 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001195
1196 // always allow effects without processing load or latency
1197 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1198 return NO_ERROR;
1199 }
1200
Eric Laurent4c415062016-06-17 16:14:16 -07001201 audio_input_flags_t flags = mInput->flags;
1202 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1203 if (flags & AUDIO_INPUT_FLAG_RAW) {
1204 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1205 desc->name, mThreadName);
1206 return BAD_VALUE;
1207 }
1208 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1209 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1210 desc->name, mThreadName);
1211 return BAD_VALUE;
1212 }
1213 }
1214 return NO_ERROR;
1215}
1216
1217// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1218status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1219 const effect_descriptor_t *desc, audio_session_t sessionId)
1220{
1221 // no preprocessing on playback threads
1222 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1223 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1224 " thread %s", desc->name, mThreadName);
1225 return BAD_VALUE;
1226 }
1227
Eric Laurent3e4de772017-07-16 16:55:08 -07001228 // always allow effects without processing load or latency
1229 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1230 return NO_ERROR;
1231 }
1232
Eric Laurent4c415062016-06-17 16:14:16 -07001233 switch (mType) {
1234 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001235#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001236 // Reject any effect on mixer multichannel sinks.
1237 // TODO: fix both format and multichannel issues with effects.
1238 if (mChannelCount != FCC_2) {
1239 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1240 " thread %s", desc->name, mChannelCount, mThreadName);
1241 return BAD_VALUE;
1242 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001243#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001244 audio_output_flags_t flags = mOutput->flags;
1245 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1246 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1247 // global effects are applied only to non fast tracks if they are SW
1248 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1249 break;
1250 }
1251 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1252 // only post processing on output stage session
1253 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1254 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1255 " on output stage session", desc->name);
1256 return BAD_VALUE;
1257 }
Eric Laurenta20c4e92019-11-12 15:55:51 -08001258 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1259 // only post processing on output stage session
1260 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1261 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1262 " on device session", desc->name);
1263 return BAD_VALUE;
1264 }
Eric Laurent4c415062016-06-17 16:14:16 -07001265 } else {
1266 // no restriction on effects applied on non fast tracks
1267 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1268 break;
1269 }
1270 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001271
Eric Laurent4c415062016-06-17 16:14:16 -07001272 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1273 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1274 desc->name);
1275 return BAD_VALUE;
1276 }
1277 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1278 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1279 " in fast mode", desc->name);
1280 return BAD_VALUE;
1281 }
1282 }
1283 } break;
1284 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001285 // nothing actionable on offload threads, if the effect:
1286 // - is offloadable: the effect can be created
1287 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1288 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001289 break;
1290 case DIRECT:
1291 // Reject any effect on Direct output threads for now, since the format of
1292 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1293 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1294 desc->name, mThreadName);
1295 return BAD_VALUE;
1296 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001297#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001298 // Reject any effect on mixer multichannel sinks.
1299 // TODO: fix both format and multichannel issues with effects.
1300 if (mChannelCount != FCC_2) {
1301 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1302 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1303 return BAD_VALUE;
1304 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001305#endif
Eric Laurenta20c4e92019-11-12 15:55:51 -08001306 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001307 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1308 " thread %s", desc->name, mThreadName);
1309 return BAD_VALUE;
1310 }
1311 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1312 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1313 " DUPLICATING thread %s", desc->name, mThreadName);
1314 return BAD_VALUE;
1315 }
1316 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1317 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1318 " DUPLICATING thread %s", desc->name, mThreadName);
1319 return BAD_VALUE;
1320 }
1321 break;
1322 default:
1323 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1324 }
1325
1326 return NO_ERROR;
1327}
1328
Eric Laurent81784c32012-11-19 14:55:58 -08001329// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1330sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1331 const sp<AudioFlinger::Client>& client,
1332 const sp<IEffectClient>& effectClient,
1333 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001334 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001335 effect_descriptor_t *desc,
1336 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001337 status_t *status,
1338 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001339{
1340 sp<EffectModule> effect;
1341 sp<EffectHandle> handle;
1342 status_t lStatus;
1343 sp<EffectChain> chain;
1344 bool chainCreated = false;
1345 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001346 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001347
1348 lStatus = initCheck();
1349 if (lStatus != NO_ERROR) {
1350 ALOGW("createEffect_l() Audio driver not initialized.");
1351 goto Exit;
1352 }
1353
Eric Laurent81784c32012-11-19 14:55:58 -08001354 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1355
1356 { // scope for mLock
1357 Mutex::Autolock _l(mLock);
1358
Eric Laurent4c415062016-06-17 16:14:16 -07001359 lStatus = checkEffectCompatibility_l(desc, sessionId);
1360 if (lStatus != NO_ERROR) {
1361 goto Exit;
1362 }
1363
Eric Laurent81784c32012-11-19 14:55:58 -08001364 // check for existing effect chain with the requested audio session
1365 chain = getEffectChain_l(sessionId);
1366 if (chain == 0) {
1367 // create a new chain for this session
1368 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1369 chain = new EffectChain(this, sessionId);
1370 addEffectChain_l(chain);
1371 chain->setStrategy(getStrategyForSession_l(sessionId));
1372 chainCreated = true;
1373 } else {
1374 effect = chain->getEffectFromDesc_l(desc);
1375 }
1376
1377 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1378
1379 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001380 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001381 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001382 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001383 if (lStatus != NO_ERROR) {
1384 goto Exit;
1385 }
1386 effectCreated = true;
1387
jiabin10d86fd2019-10-31 17:20:42 -07001388 // FIXME: use vector of device and address when effect interface is ready.
jiabinb8269fd2019-11-11 12:16:27 -08001389 effect->setDevices(outDeviceTypeAddrs());
1390 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001391 effect->setMode(mAudioFlinger->getMode());
1392 effect->setAudioSource(mAudioSource);
1393 }
1394 // create effect handle and connect it to effect module
1395 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001396 lStatus = handle->initCheck();
1397 if (lStatus == OK) {
1398 lStatus = effect->addHandle(handle.get());
1399 }
Eric Laurent81784c32012-11-19 14:55:58 -08001400 if (enabled != NULL) {
1401 *enabled = (int)effect->isEnabled();
1402 }
1403 }
1404
1405Exit:
1406 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1407 Mutex::Autolock _l(mLock);
1408 if (effectCreated) {
1409 chain->removeEffect_l(effect);
1410 }
Eric Laurent81784c32012-11-19 14:55:58 -08001411 if (chainCreated) {
1412 removeEffectChain_l(chain);
1413 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001414 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001415 }
1416
Glenn Kasten9156ef32013-08-06 15:39:08 -07001417 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001418 return handle;
1419}
1420
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001421void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1422 bool unpinIfLast)
1423{
1424 bool remove = false;
1425 sp<EffectModule> effect;
1426 {
1427 Mutex::Autolock _l(mLock);
1428
1429 effect = handle->effect().promote();
1430 if (effect == 0) {
1431 return;
1432 }
1433 // restore suspended effects if the disconnected handle was enabled and the last one.
1434 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1435 if (remove) {
1436 removeEffect_l(effect, true);
1437 }
1438 }
1439 if (remove) {
1440 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001441 if (handle->enabled()) {
1442 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1443 }
1444 }
1445}
1446
Glenn Kastend848eb42016-03-08 13:42:11 -08001447sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1448 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001449{
1450 Mutex::Autolock _l(mLock);
1451 return getEffect_l(sessionId, effectId);
1452}
1453
Glenn Kastend848eb42016-03-08 13:42:11 -08001454sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1455 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001456{
1457 sp<EffectChain> chain = getEffectChain_l(sessionId);
1458 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1459}
1460
Eric Laurent6c796322019-04-09 14:13:17 -07001461std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1462{
1463 sp<EffectChain> chain = getEffectChain_l(sessionId);
1464 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1465}
1466
Eric Laurent81784c32012-11-19 14:55:58 -08001467// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1468// PlaybackThread::mLock held
1469status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1470{
1471 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001472 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001473 sp<EffectChain> chain = getEffectChain_l(sessionId);
1474 bool chainCreated = false;
1475
Eric Laurent5baf2af2013-09-12 17:37:00 -07001476 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001477 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001478 this, effect->desc().name, effect->desc().flags);
1479
Eric Laurent81784c32012-11-19 14:55:58 -08001480 if (chain == 0) {
1481 // create a new chain for this session
1482 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1483 chain = new EffectChain(this, sessionId);
1484 addEffectChain_l(chain);
1485 chain->setStrategy(getStrategyForSession_l(sessionId));
1486 chainCreated = true;
1487 }
1488 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1489
1490 if (chain->getEffectFromId_l(effect->id()) != 0) {
1491 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1492 this, effect->desc().name, chain.get());
1493 return BAD_VALUE;
1494 }
1495
Eric Laurent5baf2af2013-09-12 17:37:00 -07001496 effect->setOffloaded(mType == OFFLOAD, mId);
1497
Eric Laurent81784c32012-11-19 14:55:58 -08001498 status_t status = chain->addEffect_l(effect);
1499 if (status != NO_ERROR) {
1500 if (chainCreated) {
1501 removeEffectChain_l(chain);
1502 }
1503 return status;
1504 }
1505
jiabinb8269fd2019-11-11 12:16:27 -08001506 effect->setDevices(outDeviceTypeAddrs());
1507 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001508 effect->setMode(mAudioFlinger->getMode());
1509 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001510
Eric Laurent81784c32012-11-19 14:55:58 -08001511 return NO_ERROR;
1512}
1513
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001514void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001515
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001516 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001517 effect_descriptor_t desc = effect->desc();
1518 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1519 detachAuxEffect_l(effect->id());
1520 }
1521
1522 sp<EffectChain> chain = effect->chain().promote();
1523 if (chain != 0) {
1524 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001525 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001526 removeEffectChain_l(chain);
1527 }
1528 } else {
1529 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1530 }
1531}
1532
1533void AudioFlinger::ThreadBase::lockEffectChains_l(
1534 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1535{
1536 effectChains = mEffectChains;
1537 for (size_t i = 0; i < mEffectChains.size(); i++) {
1538 mEffectChains[i]->lock();
1539 }
1540}
1541
1542void AudioFlinger::ThreadBase::unlockEffectChains(
1543 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1544{
1545 for (size_t i = 0; i < effectChains.size(); i++) {
1546 effectChains[i]->unlock();
1547 }
1548}
1549
Glenn Kastend848eb42016-03-08 13:42:11 -08001550sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001551{
1552 Mutex::Autolock _l(mLock);
1553 return getEffectChain_l(sessionId);
1554}
1555
Glenn Kastend848eb42016-03-08 13:42:11 -08001556sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1557 const
Eric Laurent81784c32012-11-19 14:55:58 -08001558{
1559 size_t size = mEffectChains.size();
1560 for (size_t i = 0; i < size; i++) {
1561 if (mEffectChains[i]->sessionId() == sessionId) {
1562 return mEffectChains[i];
1563 }
1564 }
1565 return 0;
1566}
1567
1568void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1569{
1570 Mutex::Autolock _l(mLock);
1571 size_t size = mEffectChains.size();
1572 for (size_t i = 0; i < size; i++) {
1573 mEffectChains[i]->setMode_l(mode);
1574 }
1575}
1576
Mikhail Naganovdc769682018-05-04 15:34:08 -07001577void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001578{
1579 config->type = AUDIO_PORT_TYPE_MIX;
1580 config->ext.mix.handle = mId;
1581 config->sample_rate = mSampleRate;
1582 config->format = mFormat;
1583 config->channel_mask = mChannelMask;
1584 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1585 AUDIO_PORT_CONFIG_FORMAT;
1586}
1587
Eric Laurent72e3f392015-05-20 14:43:50 -07001588void AudioFlinger::ThreadBase::systemReady()
1589{
1590 Mutex::Autolock _l(mLock);
1591 if (mSystemReady) {
1592 return;
1593 }
1594 mSystemReady = true;
1595
1596 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1597 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1598 }
1599 mPendingConfigEvents.clear();
1600}
1601
Andy Hungdae27702016-10-31 14:01:16 -07001602template <typename T>
1603ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1604 ssize_t index = mActiveTracks.indexOf(track);
1605 if (index >= 0) {
1606 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1607 return index;
1608 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001609 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001610 mActiveTracksGeneration++;
1611 mLatestActiveTrack = track;
1612 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001613 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001614 return mActiveTracks.add(track);
1615}
1616
1617template <typename T>
1618ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1619 ssize_t index = mActiveTracks.remove(track);
1620 if (index < 0) {
1621 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1622 return index;
1623 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001624 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001625 mActiveTracksGeneration++;
1626 --mBatteryCounter[track->uid()].second;
1627 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001628 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001629#ifdef TEE_SINK
1630 track->dumpTee(-1 /* fd */, "_REMOVE");
1631#endif
Andy Hungdae27702016-10-31 14:01:16 -07001632 return index;
1633}
1634
1635template <typename T>
1636void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1637 for (const sp<T> &track : mActiveTracks) {
1638 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001639 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001640 }
1641 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001642 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001643 mActiveTracks.clear();
1644 mLatestActiveTrack.clear();
1645 mBatteryCounter.clear();
1646}
1647
1648template <typename T>
1649void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1650 sp<ThreadBase> thread, bool force) {
1651 // Updates ActiveTracks client uids to the thread wakelock.
1652 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1653 thread->updateWakeLockUids_l(getWakeLockUids());
1654 mLastActiveTracksGeneration = mActiveTracksGeneration;
1655 }
1656
1657 // Updates BatteryNotifier uids
1658 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1659 const uid_t uid = it->first;
1660 ssize_t &previous = it->second.first;
1661 ssize_t &current = it->second.second;
1662 if (current > 0) {
1663 if (previous == 0) {
1664 BatteryNotifier::getInstance().noteStartAudio(uid);
1665 }
1666 previous = current;
1667 ++it;
1668 } else if (current == 0) {
1669 if (previous > 0) {
1670 BatteryNotifier::getInstance().noteStopAudio(uid);
1671 }
1672 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1673 } else /* (current < 0) */ {
1674 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1675 }
1676 }
1677}
Eric Laurent83b88082014-06-20 18:31:16 -07001678
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001679template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001680bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1681 const bool hasChanged = mHasChanged;
1682 mHasChanged = false;
1683 return hasChanged;
1684}
1685
1686template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001687void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1688 const char *funcName, const sp<T> &track) const {
1689 if (mLocalLog != nullptr) {
1690 String8 result;
1691 track->appendDump(result, false /* active */);
1692 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1693 }
1694}
1695
Eric Laurent6acd1d42017-01-04 14:23:29 -08001696void AudioFlinger::ThreadBase::broadcast_l()
1697{
1698 // Thread could be blocked waiting for async
1699 // so signal it to handle state changes immediately
1700 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1701 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1702 mSignalPending = true;
1703 mWaitWorkCV.broadcast();
1704}
1705
Andy Hungd0979812019-02-21 15:51:44 -08001706// Call only from threadLoop() or when it is idle.
1707// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1708void AudioFlinger::ThreadBase::sendStatistics(bool force)
1709{
1710 // Do not log if we have no stats.
1711 // We choose the timestamp verifier because it is the most likely item to be present.
1712 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1713 if (nstats == 0) {
1714 return;
1715 }
1716
1717 // Don't log more frequently than once per 12 hours.
1718 // We use BOOTTIME to include suspend time.
1719 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1720 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1721 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1722 return;
1723 }
1724
1725 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1726 mLastRecordedTimeNs = timeNs;
1727
1728 std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create("audiothread"));
1729
1730#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1731
1732 // thread configuration
1733 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1734 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1735 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1736 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1737 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1738 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1739 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabin10d86fd2019-10-31 17:20:42 -07001740 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1741 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001742
1743 // thread statistics
1744 if (mIoJitterMs.getN() > 0) {
1745 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1746 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1747 }
1748 if (mProcessTimeMs.getN() > 0) {
1749 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1750 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1751 }
1752 const auto tsjitter = mTimestampVerifier.getJitterMs();
1753 if (tsjitter.getN() > 0) {
1754 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1755 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1756 }
1757 if (mLatencyMs.getN() > 0) {
1758 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1759 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1760 }
1761
1762 item->selfrecord();
1763}
1764
Eric Laurent81784c32012-11-19 14:55:58 -08001765// ----------------------------------------------------------------------------
1766// Playback
1767// ----------------------------------------------------------------------------
1768
1769AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1770 AudioStreamOut* output,
1771 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001772 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001773 bool systemReady)
jiabin10d86fd2019-10-31 17:20:42 -07001774 : ThreadBase(audioFlinger, id, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001775 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001776 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001777 mMixerBuffer(NULL),
1778 mMixerBufferSize(0),
1779 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1780 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001781 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001782 mEffectBuffer(NULL),
1783 mEffectBufferSize(0),
1784 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1785 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001786 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001787 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001788 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001789 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001790 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001791 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001792 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001793 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001794 mMixerStatus(MIXER_IDLE),
1795 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001796 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001797 mBytesRemaining(0),
1798 mCurrentWriteLength(0),
1799 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001800 mWriteAckSequence(0),
1801 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001802 mScreenState(AudioFlinger::mScreenState),
1803 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001804 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001805 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1806 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001807{
Glenn Kastend7dca052015-03-05 16:05:54 -08001808 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1809 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001810
1811 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1812 // it would be safer to explicitly pass initial masterVolume/masterMute as
1813 // parameter.
1814 //
1815 // If the HAL we are using has support for master volume or master mute,
1816 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1817 // and the mute set to false).
1818 mMasterVolume = audioFlinger->masterVolume_l();
1819 mMasterMute = audioFlinger->masterMute_l();
1820 if (mOutput && mOutput->audioHwDev) {
1821 if (mOutput->audioHwDev->canSetMasterVolume()) {
1822 mMasterVolume = 1.0;
1823 }
1824
1825 if (mOutput->audioHwDev->canSetMasterMute()) {
1826 mMasterMute = false;
1827 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001828 mIsMsdDevice = strcmp(
1829 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001830 }
1831
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001832 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001833
Andy Hungc8fddf32018-08-08 18:32:37 -07001834 // TODO: We may also match on address as well as device type for
1835 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001836 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabin10d86fd2019-10-31 17:20:42 -07001837 // TODO: This property should be ensure that only contains one single device type.
1838 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1839 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001840 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1841 : AUDIO_DEVICE_NONE));
1842 }
1843
Eric Laurent223fd5c2014-11-11 13:43:36 -08001844 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001845 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001846 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001847 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001848 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1849 }
Eric Laurent98e38192018-02-15 18:31:53 -08001850 // Audio patch volume is always max
1851 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1852 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
1855AudioFlinger::PlaybackThread::~PlaybackThread()
1856{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001857 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001858 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001859 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001860 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001861}
1862
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001863// Thread virtuals
1864
1865void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001866{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001867 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001868}
1869
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001870// ThreadBase virtuals
1871void AudioFlinger::PlaybackThread::preExit()
1872{
1873 ALOGV(" preExit()");
1874 // FIXME this is using hard-coded strings but in the future, this functionality will be
1875 // converted to use audio HAL extensions required to support tunneling
1876 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1877 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1878}
1879
1880void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001881{
Eric Laurent81784c32012-11-19 14:55:58 -08001882 String8 result;
1883
Marco Nelissenb2208842014-02-07 14:00:50 -08001884 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001885 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1886 const stream_type_t *st = &mStreamTypes[i];
1887 if (i > 0) {
1888 result.appendFormat(", ");
1889 }
1890 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1891 if (st->mute) {
1892 result.append("M");
1893 }
1894 }
1895 result.append("\n");
1896 write(fd, result.string(), result.length());
1897 result.clear();
1898
Eric Laurent81784c32012-11-19 14:55:58 -08001899 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1900 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001901 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001902 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001903
1904 size_t numtracks = mTracks.size();
1905 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001906 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001907 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001908 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001909 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001910 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001911 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001912 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001913 for (size_t i = 0; i < numtracks; ++i) {
1914 sp<Track> track = mTracks[i];
1915 if (track != 0) {
1916 bool active = mActiveTracks.indexOf(track) >= 0;
1917 if (active) {
1918 numactiveseen++;
1919 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001920 result.append(prefix);
1921 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001922 }
1923 }
1924 } else {
1925 result.append("\n");
1926 }
1927 if (numactiveseen != numactive) {
1928 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001929 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001930 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001931 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001932 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001933 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001934 sp<Track> track = mActiveTracks[i];
1935 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001936 result.append(prefix);
1937 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001938 }
1939 }
1940 }
1941
1942 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001943}
1944
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001945void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001946{
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001947 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001948 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1949 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1950 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1951 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001952 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001953 dprintf(fd, " Total writes: %d\n", mNumWrites);
1954 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1955 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1956 dprintf(fd, " Suspend count: %d\n", mSuspended);
1957 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1958 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1959 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1960 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001961 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001962 AudioStreamOut *output = mOutput;
1963 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001964 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08001965 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001966 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1967 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1968 if (mPipeSink.get() != nullptr) {
1969 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1970 }
1971 if (output != nullptr) {
1972 dprintf(fd, " Hal stream dump:\n");
1973 (void)output->stream->dump(fd);
1974 }
Eric Laurent81784c32012-11-19 14:55:58 -08001975}
1976
Eric Laurent81784c32012-11-19 14:55:58 -08001977// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1978sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1979 const sp<AudioFlinger::Client>& client,
1980 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001981 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001982 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001983 audio_format_t format,
1984 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001985 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001986 size_t *pNotificationFrameCount,
1987 uint32_t notificationsPerBuffer,
1988 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001989 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001990 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001991 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001992 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08001993 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001994 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001995 status_t *status,
1996 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001997{
Glenn Kasten74935e42013-12-19 08:56:45 -08001998 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001999 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002000 sp<Track> track;
2001 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002002 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002003 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002004 uint32_t sampleRate;
2005
2006 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2007 lStatus = BAD_VALUE;
2008 goto Exit;
2009 }
Eric Laurent21da6472017-11-09 16:29:26 -08002010
2011 if (*pSampleRate == 0) {
2012 *pSampleRate = mSampleRate;
2013 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002014 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002015
2016 // special case for FAST flag considered OK if fast mixer is present
2017 if (hasFastMixer()) {
2018 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2019 }
2020
2021 // Check if requested flags are compatible with output stream flags
2022 if ((*flags & outputFlags) != *flags) {
2023 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2024 *flags, outputFlags);
2025 *flags = (audio_output_flags_t)(*flags & outputFlags);
2026 }
Eric Laurent81784c32012-11-19 14:55:58 -08002027
Eric Laurent81784c32012-11-19 14:55:58 -08002028 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002029 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002030 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002031 // PCM data
2032 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002033 // TODO: extract as a data library function that checks that a computationally
2034 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002035 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002036 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2037 (channelMask == AUDIO_CHANNEL_OUT_MONO
2038 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002039 // hardware sample rate
2040 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002041 // normal mixer has an associated fast mixer
2042 hasFastMixer() &&
2043 // there are sufficient fast track slots available
2044 (mFastTrackAvailMask != 0)
2045 // FIXME test that MixerThread for this fast track has a capable output HAL
2046 // FIXME add a permission test also?
2047 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002048 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2049 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002050 // read the fast track multiplier property the first time it is needed
2051 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2052 if (ok != 0) {
2053 ALOGE("%s pthread_once failed: %d", __func__, ok);
2054 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002055 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002056 }
Eric Laurent4c415062016-06-17 16:14:16 -07002057
2058 // check compatibility with audio effects.
2059 { // scope for mLock
2060 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002061 for (audio_session_t session : {
Eric Laurenta20c4e92019-11-12 15:55:51 -08002062 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002063 AUDIO_SESSION_OUTPUT_STAGE,
2064 AUDIO_SESSION_OUTPUT_MIX,
2065 sessionId,
2066 }) {
2067 sp<EffectChain> chain = getEffectChain_l(session);
2068 if (chain.get() != nullptr) {
2069 audio_output_flags_t old = *flags;
2070 chain->checkOutputFlagCompatibility(flags);
2071 if (old != *flags) {
2072 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2073 (int)session, (int)old, (int)*flags);
2074 }
Eric Laurent4c415062016-06-17 16:14:16 -07002075 }
2076 }
2077 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002078 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002079 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2080 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002081 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002082 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2083 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002084 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002085 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002086 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002087 audio_is_linear_pcm(format),
2088 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002089 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002090 }
2091 }
Eric Laurent21da6472017-11-09 16:29:26 -08002092
2093 if (!audio_has_proportional_frames(format)) {
2094 if (sharedBuffer != 0) {
2095 // Same comment as below about ignoring frameCount parameter for set()
2096 frameCount = sharedBuffer->size();
2097 } else if (frameCount == 0) {
2098 frameCount = mNormalFrameCount;
2099 }
2100 if (notificationFrameCount != frameCount) {
2101 notificationFrameCount = frameCount;
2102 }
2103 } else if (sharedBuffer != 0) {
2104 // FIXME: Ensure client side memory buffers need
2105 // not have additional alignment beyond sample
2106 // (e.g. 16 bit stereo accessed as 32 bit frame).
2107 size_t alignment = audio_bytes_per_sample(format);
2108 if (alignment & 1) {
2109 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2110 alignment = 1;
2111 }
2112 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2113 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2114 if (channelCount > 1) {
2115 // More than 2 channels does not require stronger alignment than stereo
2116 alignment <<= 1;
2117 }
2118 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2119 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2120 sharedBuffer->pointer(), channelCount);
2121 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002122 goto Exit;
2123 }
Eric Laurent21da6472017-11-09 16:29:26 -08002124
2125 // When initializing a shared buffer AudioTrack via constructors,
2126 // there's no frameCount parameter.
2127 // But when initializing a shared buffer AudioTrack via set(),
2128 // there _is_ a frameCount parameter. We silently ignore it.
2129 frameCount = sharedBuffer->size() / frameSize;
2130 } else {
2131 size_t minFrameCount = 0;
2132 // For fast tracks we try to respect the application's request for notifications per buffer.
2133 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2134 if (notificationsPerBuffer > 0) {
2135 // Avoid possible arithmetic overflow during multiplication.
2136 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2137 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2138 notificationsPerBuffer, mFrameCount);
2139 } else {
2140 minFrameCount = mFrameCount * notificationsPerBuffer;
2141 }
2142 }
2143 } else {
2144 // For normal PCM streaming tracks, update minimum frame count.
2145 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2146 // cover audio hardware latency.
2147 // This is probably too conservative, but legacy application code may depend on it.
2148 // If you change this calculation, also review the start threshold which is related.
2149 uint32_t latencyMs = latency_l();
2150 if (latencyMs == 0) {
2151 ALOGE("Error when retrieving output stream latency");
2152 lStatus = UNKNOWN_ERROR;
2153 goto Exit;
2154 }
2155
2156 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2157 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2158
Eric Laurent81784c32012-11-19 14:55:58 -08002159 }
Eric Laurent21da6472017-11-09 16:29:26 -08002160 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002161 frameCount = minFrameCount;
2162 }
Eric Laurent81784c32012-11-19 14:55:58 -08002163 }
Eric Laurent21da6472017-11-09 16:29:26 -08002164
2165 // Make sure that application is notified with sufficient margin before underrun.
2166 // The client can divide the AudioTrack buffer into sub-buffers,
2167 // and expresses its desire to server as the notification frame count.
2168 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2169 size_t maxNotificationFrames;
2170 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2171 // notify every HAL buffer, regardless of the size of the track buffer
2172 maxNotificationFrames = mFrameCount;
2173 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002174 // Triple buffer the notification period for a triple buffered mixer period;
2175 // otherwise, double buffering for the notification period is fine.
2176 //
2177 // TODO: This should be moved to AudioTrack to modify the notification period
2178 // on AudioTrack::setBufferSizeInFrames() changes.
2179 const int nBuffering =
2180 (uint64_t{frameCount} * mSampleRate)
2181 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2182
Eric Laurent21da6472017-11-09 16:29:26 -08002183 maxNotificationFrames = frameCount / nBuffering;
2184 // If client requested a fast track but this was denied, then use the smaller maximum.
2185 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2186 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2187 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2188 maxNotificationFrames = maxNotificationFramesFastDenied;
2189 }
2190 }
2191 }
2192 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2193 if (notificationFrameCount == 0) {
2194 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2195 maxNotificationFrames, frameCount);
2196 } else {
2197 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2198 notificationFrameCount, maxNotificationFrames, frameCount);
2199 }
2200 notificationFrameCount = maxNotificationFrames;
2201 }
2202 }
2203
Glenn Kasten74935e42013-12-19 08:56:45 -08002204 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002205 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002206
Glenn Kastenc3df8382014-03-13 15:05:25 -07002207 switch (mType) {
2208
2209 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002210 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002211 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002212 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2213 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002214 sampleRate, format, channelMask, mOutput, mFormat);
2215 lStatus = BAD_VALUE;
2216 goto Exit;
2217 }
2218 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002219 break;
2220
2221 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002222 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002223 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2224 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002225 sampleRate, format, channelMask, mOutput, mFormat);
2226 lStatus = BAD_VALUE;
2227 goto Exit;
2228 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002229 break;
2230
2231 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002232 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002233 ALOGE("createTrack_l() Bad parameter: format %#x \""
2234 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002235 format, mOutput, mFormat);
2236 lStatus = BAD_VALUE;
2237 goto Exit;
2238 }
Andy Hungcd044842014-08-07 11:04:34 -07002239 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002240 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2241 lStatus = BAD_VALUE;
2242 goto Exit;
2243 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002244 break;
2245
Eric Laurent81784c32012-11-19 14:55:58 -08002246 }
2247
2248 lStatus = initCheck();
2249 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002250 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002251 goto Exit;
2252 }
2253
2254 { // scope for mLock
2255 Mutex::Autolock _l(mLock);
2256
2257 // all tracks in same audio session must share the same routing strategy otherwise
2258 // conflicts will happen when tracks are moved from one output to another by audio policy
2259 // manager
2260 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2261 for (size_t i = 0; i < mTracks.size(); ++i) {
2262 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002263 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002264 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2265 if (sessionId == t->sessionId() && strategy != actual) {
2266 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2267 strategy, actual);
2268 lStatus = BAD_VALUE;
2269 goto Exit;
2270 }
2271 }
2272 }
2273
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002274 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002275 channelMask, frameCount,
2276 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002277 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002278
Glenn Kasten03003332013-08-06 15:40:54 -07002279 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2280 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002281 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002282 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002283 goto Exit;
2284 }
2285 mTracks.add(track);
2286
2287 sp<EffectChain> chain = getEffectChain_l(sessionId);
2288 if (chain != 0) {
2289 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2290 track->setMainBuffer(chain->inBuffer());
2291 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2292 chain->incTrackCnt();
2293 }
2294
Eric Laurent05067782016-06-01 18:27:28 -07002295 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002296 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2297 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2298 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002299 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002300 }
2301 }
2302
2303 lStatus = NO_ERROR;
2304
2305Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002306 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002307 return track;
2308}
2309
Andy Hung1bc088a2018-02-09 15:57:31 -08002310template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002311ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2312{
Andy Hungc0691382018-09-12 18:01:57 -07002313 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002314 const ssize_t index = mTracks.remove(track);
2315 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002316 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002317 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002318 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002319 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002320 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002321 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002322 }
2323 return index;
2324}
2325
Eric Laurent81784c32012-11-19 14:55:58 -08002326uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2327{
2328 return latency;
2329}
2330
2331uint32_t AudioFlinger::PlaybackThread::latency() const
2332{
2333 Mutex::Autolock _l(mLock);
2334 return latency_l();
2335}
2336uint32_t AudioFlinger::PlaybackThread::latency_l() const
2337{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002338 uint32_t latency;
2339 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2340 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002341 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002342 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002343}
2344
2345void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2346{
2347 Mutex::Autolock _l(mLock);
2348 // Don't apply master volume in SW if our HAL can do it for us.
2349 if (mOutput && mOutput->audioHwDev &&
2350 mOutput->audioHwDev->canSetMasterVolume()) {
2351 mMasterVolume = 1.0;
2352 } else {
2353 mMasterVolume = value;
2354 }
2355}
2356
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002357void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2358{
2359 mMasterBalance.store(balance);
2360}
2361
Eric Laurent81784c32012-11-19 14:55:58 -08002362void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2363{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002364 if (isDuplicating()) {
2365 return;
2366 }
Eric Laurent81784c32012-11-19 14:55:58 -08002367 Mutex::Autolock _l(mLock);
2368 // Don't apply master mute in SW if our HAL can do it for us.
2369 if (mOutput && mOutput->audioHwDev &&
2370 mOutput->audioHwDev->canSetMasterMute()) {
2371 mMasterMute = false;
2372 } else {
2373 mMasterMute = muted;
2374 }
2375}
2376
2377void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2378{
2379 Mutex::Autolock _l(mLock);
2380 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002381 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002382}
2383
2384void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2385{
2386 Mutex::Autolock _l(mLock);
2387 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002388 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002389}
2390
2391float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2392{
2393 Mutex::Autolock _l(mLock);
2394 return mStreamTypes[stream].volume;
2395}
2396
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002397void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2398{
2399 mOutput->stream->setVolume(left, right);
2400}
2401
Eric Laurent81784c32012-11-19 14:55:58 -08002402// addTrack_l() must be called with ThreadBase::mLock held
2403status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2404{
2405 status_t status = ALREADY_EXISTS;
2406
Eric Laurent81784c32012-11-19 14:55:58 -08002407 if (mActiveTracks.indexOf(track) < 0) {
2408 // the track is newly added, make sure it fills up all its
2409 // buffers before playing. This is to ensure the client will
2410 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002411 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 TrackBase::track_state state = track->mState;
2413 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002414 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002415 mLock.lock();
2416 // abort track was stopped/paused while we released the lock
2417 if (state != track->mState) {
2418 if (status == NO_ERROR) {
2419 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002420 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002421 mLock.lock();
2422 }
2423 return INVALID_OPERATION;
2424 }
2425 // abort if start is rejected by audio policy manager
2426 if (status != NO_ERROR) {
2427 return PERMISSION_DENIED;
2428 }
2429#ifdef ADD_BATTERY_DATA
2430 // to track the speaker usage
2431 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2432#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002433 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002434 }
2435
Eric Laurent51716182016-02-29 18:00:56 -08002436 // set retry count for buffer fill
2437 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002438 if (track->isStopping_1()) {
2439 track->mRetryCount = kMaxTrackStopRetriesOffload;
2440 } else {
2441 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2442 }
2443 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002444 } else {
2445 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002446 track->mFillingUpStatus =
2447 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002448 }
2449
jiabin245cdd92018-12-07 17:55:15 -08002450 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2451 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002452 // Unlock due to VibratorService will lock for this call and will
2453 // call Tracks.mute/unmute which also require thread's lock.
2454 mLock.unlock();
2455 const int intensity = AudioFlinger::onExternalVibrationStart(
2456 track->getExternalVibration());
2457 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002458 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002459 // Haptic playback should be enabled by vibrator service.
2460 if (track->getHapticPlaybackEnabled()) {
2461 // Disable haptic playback of all active track to ensure only
2462 // one track playing haptic if current track should play haptic.
2463 for (const auto &t : mActiveTracks) {
2464 t->setHapticPlaybackEnabled(false);
2465 }
jiabin245cdd92018-12-07 17:55:15 -08002466 }
jiabin245cdd92018-12-07 17:55:15 -08002467 }
2468
Eric Laurent81784c32012-11-19 14:55:58 -08002469 track->mResetDone = false;
2470 track->mPresentationCompleteFrames = 0;
2471 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002472 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2473 if (chain != 0) {
2474 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2475 track->sessionId());
2476 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002477 }
2478
2479 status = NO_ERROR;
2480 }
2481
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002482 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002483 return status;
2484}
2485
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002487{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002488 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002489 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002490 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2491 track->mState = TrackBase::STOPPED;
2492 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002493 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002494 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002495 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002496 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002497
2498 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002499}
2500
2501void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2502{
2503 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002504
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002505 String8 result;
2506 track->appendDump(result, false /* active */);
2507 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002508
Eric Laurent81784c32012-11-19 14:55:58 -08002509 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002510 if (track->isFastTrack()) {
2511 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002512 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002513 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2514 mFastTrackAvailMask |= 1 << index;
2515 // redundant as track is about to be destroyed, for dumpsys only
2516 track->mFastIndex = -1;
2517 }
2518 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2519 if (chain != 0) {
2520 chain->decTrackCnt();
2521 }
2522}
2523
2524String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2525{
Eric Laurent81784c32012-11-19 14:55:58 -08002526 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002527 String8 out_s8;
2528 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2529 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002530 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002531 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002532}
2533
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002534status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2535 Mutex::Autolock _l(mLock);
2536 if (mOutput == nullptr || mOutput->stream == nullptr) {
2537 return NO_INIT;
2538 }
2539 return mOutput->stream->selectPresentation(presentationId, programId);
2540}
2541
Eric Laurent09f1ed22019-04-24 17:45:17 -07002542void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2543 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002544 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2545 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002546
Eric Laurent73e26b62015-04-27 16:55:58 -07002547 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002548
2549 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002550 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002551 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002552 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002553 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002554 desc->mChannelMask = mChannelMask;
2555 desc->mSamplingRate = mSampleRate;
2556 desc->mFormat = mFormat;
2557 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002558 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002559 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002560 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002561 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002562 case AUDIO_CLIENT_STARTED:
2563 desc->mPatch = mPatch;
2564 desc->mPortId = portId;
2565 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002566 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002567 default:
2568 break;
2569 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002570 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002571}
2572
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002573void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002575 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002576}
2577
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002578void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002579{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002580 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581}
2582
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002583void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002584{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002585 mCallbackThread->setAsyncError();
2586}
2587
Eric Laurent3b4529e2013-09-05 18:09:19 -07002588void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002589{
2590 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002591 // reject out of sequence requests
2592 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2593 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002594 mWaitWorkCV.signal();
2595 }
2596}
2597
Eric Laurent3b4529e2013-09-05 18:09:19 -07002598void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002599{
2600 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002601 // reject out of sequence requests
2602 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002603 // Register discontinuity when HW drain is completed because that can cause
2604 // the timestamp frame position to reset to 0 for direct and offload threads.
2605 // (Out of sequence requests are ignored, since the discontinuity would be handled
2606 // elsewhere, e.g. in flush).
2607 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002608 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609 mWaitWorkCV.signal();
2610 }
2611}
2612
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002613void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002614{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002615 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002616 mSampleRate = mOutput->getSampleRate();
2617 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002618 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002619 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002620 }
Andy Hung9a592762014-07-21 21:56:01 -07002621 if ((mType == MIXER || mType == DUPLICATING)
2622 && !isValidPcmSinkChannelMask(mChannelMask)) {
2623 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2624 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002625 }
Andy Hunge5412692014-05-16 11:25:07 -07002626 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002627 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002628
2629 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002630 status_t result = mOutput->stream->getFormat(&mHALFormat);
2631 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002632 // Get format from the shim, which will be different than the HAL format
2633 // if playing compressed audio over HDMI passthrough.
2634 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002635 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002636 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002637 }
Andy Hung6146c082014-03-18 11:56:15 -07002638 if ((mType == MIXER || mType == DUPLICATING)
2639 && !isValidPcmSinkFormat(mFormat)) {
2640 LOG_FATAL("HAL format %#x not supported for mixed output",
2641 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002642 }
Phil Burk062e67a2015-02-11 13:40:50 -08002643 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002644 result = mOutput->stream->getBufferSize(&mBufferSize);
2645 LOG_ALWAYS_FATAL_IF(result != OK,
2646 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002647 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002648 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002649 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002650 mFrameCount);
2651 }
2652
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002653 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2654 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002656 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 }
2658 }
2659
Eric Laurentd1f69b02014-12-15 14:33:13 -08002660 mHwSupportsPause = false;
2661 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002662 bool supportsPause = false, supportsResume = false;
2663 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2664 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002665 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002666 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002667 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002668 } else if (supportsResume) {
2669 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002670 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002671 }
2672 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002673 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2674 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2675 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002676
Andy Hungfbfc3952015-01-15 13:33:51 -08002677 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2678 // For best precision, we use float instead of the associated output
2679 // device format (typically PCM 16 bit).
2680
2681 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2682 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2683 mBufferSize = mFrameSize * mFrameCount;
2684
2685 // TODO: We currently use the associated output device channel mask and sample rate.
2686 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2687 // (if a valid mask) to avoid premature downmix.
2688 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2689 // instead of the output device sample rate to avoid loss of high frequency information.
2690 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2691 }
2692
Andy Hung09a50072014-02-27 14:30:47 -08002693 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002694 double multiplier = 1.0;
2695 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2696 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002697 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2698 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002699
Eric Laurent81784c32012-11-19 14:55:58 -08002700 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2701 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2702 maxNormalFrameCount = maxNormalFrameCount & ~15;
2703 if (maxNormalFrameCount < minNormalFrameCount) {
2704 maxNormalFrameCount = minNormalFrameCount;
2705 }
2706 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2707 if (multiplier <= 1.0) {
2708 multiplier = 1.0;
2709 } else if (multiplier <= 2.0) {
2710 if (2 * mFrameCount <= maxNormalFrameCount) {
2711 multiplier = 2.0;
2712 } else {
2713 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2714 }
2715 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002716 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002717 }
2718 }
2719 mNormalFrameCount = multiplier * mFrameCount;
2720 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002721 if (mType == MIXER || mType == DUPLICATING) {
2722 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2723 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002724 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002725 mNormalFrameCount);
2726
Andy Hung08fb1742015-05-31 23:22:10 -07002727 // Check if we want to throttle the processing to no more than 2x normal rate
2728 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002729 mThreadThrottleTimeMs = 0;
2730 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002731 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2732
Andy Hung010a1a12014-03-13 13:57:33 -07002733 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2734 // Originally this was int16_t[] array, need to remove legacy implications.
2735 free(mSinkBuffer);
2736 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002737 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2738 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2739 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002740 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002741
Andy Hung69aed5f2014-02-25 17:24:40 -08002742 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2743 // drives the output.
2744 free(mMixerBuffer);
2745 mMixerBuffer = NULL;
2746 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002747 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002748 mMixerBufferSize = mNormalFrameCount * mChannelCount
2749 * audio_bytes_per_sample(mMixerBufferFormat);
2750 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2751 }
Andy Hung98ef9782014-03-04 14:46:50 -08002752 free(mEffectBuffer);
2753 mEffectBuffer = NULL;
2754 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002755 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002756 mEffectBufferSize = mNormalFrameCount * mChannelCount
2757 * audio_bytes_per_sample(mEffectBufferFormat);
2758 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2759 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002760
jiabin245cdd92018-12-07 17:55:15 -08002761 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2762 mChannelMask &= ~mHapticChannelMask;
2763 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2764 mChannelCount -= mHapticChannelCount;
2765
Eric Laurent81784c32012-11-19 14:55:58 -08002766 // force reconfiguration of effect chains and engines to take new buffer size and audio
2767 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002768 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002769 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2770 // matter.
2771 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2772 Vector< sp<EffectChain> > effectChains = mEffectChains;
2773 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002774 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2775 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002776 }
2777}
2778
Kevin Rocard069c2712018-03-29 19:09:14 -07002779void AudioFlinger::PlaybackThread::updateMetadata_l()
2780{
Kevin Rocard12381092018-04-11 09:19:59 -07002781 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2782 return; // That should not happen
2783 }
2784 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2785 for (const sp<Track> &track : mActiveTracks) {
2786 // Do not short-circuit as all hasChanged states must be reset
2787 // as all the metadata are going to be sent
2788 hasChanged |= track->readAndClearHasChanged();
2789 }
2790 if (!hasChanged) {
2791 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002792 }
2793 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002794 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002795 for (const sp<Track> &track : mActiveTracks) {
2796 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002797 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002798 }
Kevin Rocard12381092018-04-11 09:19:59 -07002799 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002800}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002801
Kevin Rocard12381092018-04-11 09:19:59 -07002802void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2803 const StreamOutHalInterface::SourceMetadata& metadata)
2804{
2805 mOutput->stream->updateSourceMetadata(metadata);
2806};
2807
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002808status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002809{
2810 if (halFrames == NULL || dspFrames == NULL) {
2811 return BAD_VALUE;
2812 }
2813 Mutex::Autolock _l(mLock);
2814 if (initCheck() != NO_ERROR) {
2815 return INVALID_OPERATION;
2816 }
Andy Hung818e7a32016-02-16 18:08:07 -08002817 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002818 *halFrames = framesWritten;
2819
2820 if (isSuspended()) {
2821 // return an estimation of rendered frames when the output is suspended
2822 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002823 *dspFrames = (uint32_t)
2824 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002825 return NO_ERROR;
2826 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002827 status_t status;
2828 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002829 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002830 *dspFrames = (size_t)frames;
2831 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002832 }
2833}
2834
Glenn Kastend848eb42016-03-08 13:42:11 -08002835uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002836{
2837 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2838 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2839 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2840 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2841 }
2842 for (size_t i = 0; i < mTracks.size(); i++) {
2843 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002844 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002845 return AudioSystem::getStrategyForStream(track->streamType());
2846 }
2847 }
2848 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2849}
2850
2851
Phil Burk062e67a2015-02-11 13:40:50 -08002852AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002853{
2854 Mutex::Autolock _l(mLock);
2855 return mOutput;
2856}
2857
Phil Burk062e67a2015-02-11 13:40:50 -08002858AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002859{
2860 Mutex::Autolock _l(mLock);
2861 AudioStreamOut *output = mOutput;
2862 mOutput = NULL;
2863 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2864 // must push a NULL and wait for ack
2865 mOutputSink.clear();
2866 mPipeSink.clear();
2867 mNormalSink.clear();
2868 return output;
2869}
2870
2871// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002872sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002873{
2874 if (mOutput == NULL) {
2875 return NULL;
2876 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002877 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002878}
2879
2880uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2881{
2882 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2883}
2884
2885status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2886{
2887 if (!isValidSyncEvent(event)) {
2888 return BAD_VALUE;
2889 }
2890
2891 Mutex::Autolock _l(mLock);
2892
2893 for (size_t i = 0; i < mTracks.size(); ++i) {
2894 sp<Track> track = mTracks[i];
2895 if (event->triggerSession() == track->sessionId()) {
2896 (void) track->setSyncEvent(event);
2897 return NO_ERROR;
2898 }
2899 }
2900
2901 return NAME_NOT_FOUND;
2902}
2903
2904bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2905{
2906 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2907}
2908
2909void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2910 const Vector< sp<Track> >& tracksToRemove)
2911{
Andy Hungfe726a62018-09-27 15:17:25 -07002912 // Miscellaneous track cleanup when removed from the active list,
2913 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002915 for (const auto& track : tracksToRemove) {
2916 if (track->isExternalTrack()) {
2917 // to track the speaker usage
2918 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002919 }
2920 }
Andy Hungfe726a62018-09-27 15:17:25 -07002921#else
2922 (void)tracksToRemove; // suppress unused warning
2923#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002924}
2925
2926void AudioFlinger::PlaybackThread::checkSilentMode_l()
2927{
2928 if (!mMasterMute) {
2929 char value[PROPERTY_VALUE_MAX];
jiabin10d86fd2019-10-31 17:20:42 -07002930 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002931 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2932 return;
2933 }
Eric Laurent81784c32012-11-19 14:55:58 -08002934 if (property_get("ro.audio.silent", value, "0") > 0) {
2935 char *endptr;
2936 unsigned long ul = strtoul(value, &endptr, 0);
2937 if (*endptr == '\0' && ul != 0) {
2938 ALOGD("Silence is golden");
2939 // The setprop command will not allow a property to be changed after
2940 // the first time it is set, so we don't have to worry about un-muting.
2941 setMasterMute_l(true);
2942 }
2943 }
2944 }
2945}
2946
2947// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002948ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002949{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002950 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002952 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002953 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002954
2955 // If an NBAIO sink is present, use it to write the normal mixer's submix
2956 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002957
Andy Hung010a1a12014-03-13 13:57:33 -07002958 const size_t count = mBytesRemaining / mFrameSize;
2959
Simon Wilson2d590962012-11-29 15:18:50 -08002960 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002961 // update the setpoint when AudioFlinger::mScreenState changes
2962 uint32_t screenState = AudioFlinger::mScreenState;
2963 if (screenState != mScreenState) {
2964 mScreenState = screenState;
2965 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2966 if (pipe != NULL) {
2967 pipe->setAvgFrames((mScreenState & 1) ?
2968 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2969 }
2970 }
Andy Hung010a1a12014-03-13 13:57:33 -07002971 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002972 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002973 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002974 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002975#ifdef TEE_SINK
2976 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2977#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002978 } else {
2979 bytesWritten = framesWritten;
2980 }
2981 // otherwise use the HAL / AudioStreamOut directly
2982 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002983 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002984
Eric Laurentbfb1b832013-01-07 09:53:42 -08002985 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002986 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2987 mWriteAckSequence += 2;
2988 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002990 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002991 }
Mikhail Naganov76e89c32019-08-15 20:18:47 -07002992 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07002993 // FIXME We should have an implementation of timestamps for direct output threads.
2994 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002995 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganov76e89c32019-08-15 20:18:47 -07002996 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08002997
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998 if (mUseAsyncWrite &&
2999 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3000 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003001 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003002 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003003 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003004 }
Eric Laurent81784c32012-11-19 14:55:58 -08003005 }
3006
Eric Laurent81784c32012-11-19 14:55:58 -08003007 mNumWrites++;
3008 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07003009 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010 return bytesWritten;
3011}
3012
3013void AudioFlinger::PlaybackThread::threadLoop_drain()
3014{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003015 bool supportsDrain = false;
3016 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003017 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3018 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003019 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3020 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003021 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003022 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003024 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003025 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003026 }
3027}
3028
3029void AudioFlinger::PlaybackThread::threadLoop_exit()
3030{
Eric Laurent275e8e92014-11-30 15:14:47 -08003031 {
3032 Mutex::Autolock _l(mLock);
3033 for (size_t i = 0; i < mTracks.size(); i++) {
3034 sp<Track> track = mTracks[i];
3035 track->invalidate();
3036 }
Andy Hungdae27702016-10-31 14:01:16 -07003037 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3038 // After we exit there are no more track changes sent to BatteryNotifier
3039 // because that requires an active threadLoop.
3040 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3041 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003042 }
Eric Laurent81784c32012-11-19 14:55:58 -08003043}
3044
3045/*
3046The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003047 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003048 - mActiveSleepTimeUs from activeSleepTimeUs()
3049 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003050 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3051 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003052 - maxPeriod from frame count and sample rate (MIXER only)
3053
3054The parameters that affect these derived values are:
3055 - frame count
3056 - frame size
3057 - sample rate
3058 - device type: A2DP or not
3059 - device latency
3060 - format: PCM or not
3061 - active sleep time
3062 - idle sleep time
3063*/
3064
3065void AudioFlinger::PlaybackThread::cacheParameters_l()
3066{
Andy Hung25c2dac2014-02-27 14:56:00 -08003067 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003068 mActiveSleepTimeUs = activeSleepTimeUs();
3069 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003070
3071 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3072 // truncating audio when going to standby.
3073 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabin10d86fd2019-10-31 17:20:42 -07003074 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003075 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3076 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3077 }
3078 }
Eric Laurent81784c32012-11-19 14:55:58 -08003079}
3080
Eric Laurent13084622016-05-17 10:51:49 -07003081bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003082{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003083 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003084 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003085 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003086 size_t size = mTracks.size();
3087 for (size_t i = 0; i < size; i++) {
3088 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003089 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003090 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003091 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003092 }
3093 }
Eric Laurent13084622016-05-17 10:51:49 -07003094 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003095}
3096
Haynes Mathew George05317d22016-05-03 16:34:26 -07003097void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3098{
3099 Mutex::Autolock _l(mLock);
3100 invalidateTracks_l(streamType);
3101}
3102
Eric Laurent81784c32012-11-19 14:55:58 -08003103status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3104{
Glenn Kastend848eb42016-03-08 13:42:11 -08003105 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003106 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003107 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003108 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3109 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3110 &halInBuffer);
3111 if (result != OK) return result;
3112 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003113 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003114 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurenta20c4e92019-11-12 15:55:51 -08003115 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003116 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003117 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003118 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003119 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003120 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003121 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003122 &halInBuffer);
3123 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003124#ifdef FLOAT_EFFECT_CHAIN
3125 buffer = halInBuffer->audioBuffer()->f32;
3126#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003127 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003128#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003129 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3130 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003131 }
3132
3133 // Attach all tracks with same session ID to this chain.
3134 for (size_t i = 0; i < mTracks.size(); ++i) {
3135 sp<Track> track = mTracks[i];
3136 if (session == track->sessionId()) {
3137 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3138 buffer);
3139 track->setMainBuffer(buffer);
3140 chain->incTrackCnt();
3141 }
3142 }
3143
3144 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003145 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003146 if (session == track->sessionId()) {
3147 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3148 chain->incActiveTrackCnt();
3149 }
3150 }
3151 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003152 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003153 chain->setInBuffer(halInBuffer);
3154 chain->setOutBuffer(halOutBuffer);
Eric Laurenta20c4e92019-11-12 15:55:51 -08003155 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3156 // chains list in order to be processed last as it contains output device effects.
3157 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3158 // processing effects specific to an output stream before effects applied to all streams
3159 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003160 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3161 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003162 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003163 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003164 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003165 // Effect chain for other sessions are inserted at beginning of effect
3166 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003167 // sessions is not important.
3168 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurenta20c4e92019-11-12 15:55:51 -08003169 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3170 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003171 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003172 size_t size = mEffectChains.size();
3173 size_t i = 0;
3174 for (i = 0; i < size; i++) {
3175 if (mEffectChains[i]->sessionId() < session) {
3176 break;
3177 }
3178 }
3179 mEffectChains.insertAt(chain, i);
3180 checkSuspendOnAddEffectChain_l(chain);
3181
3182 return NO_ERROR;
3183}
3184
3185size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3186{
Glenn Kastend848eb42016-03-08 13:42:11 -08003187 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003188
3189 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3190
3191 for (size_t i = 0; i < mEffectChains.size(); i++) {
3192 if (chain == mEffectChains[i]) {
3193 mEffectChains.removeAt(i);
3194 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003195 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003196 if (session == track->sessionId()) {
3197 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3198 chain.get(), session);
3199 chain->decActiveTrackCnt();
3200 }
3201 }
3202
3203 // detach all tracks with same session ID from this chain
3204 for (size_t i = 0; i < mTracks.size(); ++i) {
3205 sp<Track> track = mTracks[i];
3206 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003207 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003208 chain->decTrackCnt();
3209 }
3210 }
3211 break;
3212 }
3213 }
3214 return mEffectChains.size();
3215}
3216
3217status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003218 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003219{
3220 Mutex::Autolock _l(mLock);
3221 return attachAuxEffect_l(track, EffectId);
3222}
3223
3224status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003225 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003226{
3227 status_t status = NO_ERROR;
3228
3229 if (EffectId == 0) {
3230 track->setAuxBuffer(0, NULL);
3231 } else {
3232 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3233 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3234 if (effect != 0) {
3235 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3236 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3237 } else {
3238 status = INVALID_OPERATION;
3239 }
3240 } else {
3241 status = BAD_VALUE;
3242 }
3243 }
3244 return status;
3245}
3246
3247void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3248{
3249 for (size_t i = 0; i < mTracks.size(); ++i) {
3250 sp<Track> track = mTracks[i];
3251 if (track->auxEffectId() == effectId) {
3252 attachAuxEffect_l(track, 0);
3253 }
3254 }
3255}
3256
3257bool AudioFlinger::PlaybackThread::threadLoop()
3258{
Glenn Kasten388d5712017-04-07 14:38:41 -07003259 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003260
Eric Laurent81784c32012-11-19 14:55:58 -08003261 Vector< sp<Track> > tracksToRemove;
3262
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003263 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003264 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3265 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003266
3267 // MIXER
3268 nsecs_t lastWarning = 0;
3269
3270 // DUPLICATING
3271 // FIXME could this be made local to while loop?
3272 writeFrames = 0;
3273
3274 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003275 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003276
3277 if (mType == MIXER) {
3278 sleepTimeShift = 0;
3279 }
3280
3281 CpuStats cpuStats;
3282 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3283
3284 acquireWakeLock();
3285
Glenn Kasteneef598c2017-04-03 14:41:13 -07003286 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3287 // thread associated with this PlaybackThread.
3288 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3289 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003290 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3291 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003292 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003293 const char *logString = NULL;
3294
rago1bb90822017-05-02 18:31:48 -07003295 // Estimated time for next buffer to be written to hal. This is used only on
3296 // suspended mode (for now) to help schedule the wait time until next iteration.
3297 nsecs_t timeLoopNextNs = 0;
3298
Eric Laurent664539d2013-09-23 18:24:31 -07003299 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003300
Andy Hungf3234512018-07-03 14:51:47 -07003301 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3302 // TODO: add confirmation checks:
3303 // 1) DIRECT threads and linear PCM format really resets to 0?
3304 // 2) Is frame count really valid if not linear pcm?
3305 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3306 if (mType == OFFLOAD || mType == DIRECT) {
3307 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3308 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003309 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003310
Andy Hung446f4df2019-02-21 12:26:41 -08003311 // loopCount is used for statistics and diagnostics.
3312 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003313 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003314 // Log merge requests are performed during AudioFlinger binder transactions, but
3315 // that does not cover audio playback. It's requested here for that reason.
3316 mAudioFlinger->requestLogMerge();
3317
Eric Laurent81784c32012-11-19 14:55:58 -08003318 cpuStats.sample(myName);
3319
3320 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003321 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003322 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003323
Andy Hung2dbffc22018-08-08 18:50:41 -07003324 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3325 //
jiabin10d86fd2019-10-31 17:20:42 -07003326 // Note: we access outDeviceTypes() outside of mLock.
3327 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003328 // Here, we try for the AF lock, but do not block on it as the latency
3329 // is more informational.
3330 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3331 std::vector<PatchPanel::SoftwarePatch> swPatches;
3332 double latencyMs;
3333 status_t status = INVALID_OPERATION;
3334 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3335 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3336 && swPatches.size() > 0) {
3337 status = swPatches[0].getLatencyMs_l(&latencyMs);
3338 downstreamPatchHandle = swPatches[0].getPatchHandle();
3339 }
3340 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003341 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003342 lastDownstreamPatchHandle = downstreamPatchHandle;
3343 }
3344 if (status == OK) {
3345 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003346 // latency of 5 seconds).
3347 const double minLatency = 0., maxLatency = 5000.;
3348 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003349 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003350 } else {
3351 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003352 if (latencyMs < minLatency) latencyMs = minLatency;
3353 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003354 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003355 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003356 }
3357 mAudioFlinger->mLock.unlock();
3358 }
3359 } else {
3360 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3361 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003362 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003363 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3364 }
3365 }
3366
Eric Laurent81784c32012-11-19 14:55:58 -08003367 { // scope for mLock
3368
3369 Mutex::Autolock _l(mLock);
3370
Eric Laurent021cf962014-05-13 10:18:14 -07003371 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003372
Glenn Kasteneef598c2017-04-03 14:41:13 -07003373 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003374 if (logString != NULL) {
3375 mNBLogWriter->logTimestamp();
3376 mNBLogWriter->log(logString);
3377 logString = NULL;
3378 }
3379
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003380 // Collect timestamp statistics for the Playback Thread types that support it.
3381 if (mType == MIXER
3382 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003383 || mType == DIRECT
3384 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003385 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003386 // and associate with the sink frames written out. We need
3387 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003388 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003389 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003390 if (mStandby) {
3391 mTimestampVerifier.discontinuity();
3392 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3393 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3394 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3395 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003396
3397 if (isTimestampCorrectionEnabled()) {
3398 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3399 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3400 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3401 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3402 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3403 = correctedTimestamp.mFrames;
3404 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3405 = correctedTimestamp.mTimeNs;
3406 ALOGV("TS_AFTER: %d %lld %lld", id(),
3407 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3408 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003409
3410 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003411 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003412 const int64_t newPosition =
3413 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003414 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003415 // prevent retrograde
3416 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3417 newPosition,
3418 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3419 - mSuspendedFrames));
3420 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003421 }
3422
Andy Hung818e7a32016-02-16 18:08:07 -08003423 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003424 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003425
3426 // We keep track of the last valid kernel position in case we are in underrun
3427 // and the normal mixer period is the same as the fast mixer period, or there
3428 // is some error from the HAL.
3429 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3430 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3431 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3432 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3433 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3434
3435 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3436 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3437 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3438 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003439 }
3440
3441 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3442 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003443 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003444 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003445 }
3446
Andy Hung818e7a32016-02-16 18:08:07 -08003447 // copy over kernel info
3448 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003449 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3450 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003451 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3452 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003453 } else {
3454 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003455 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003456
Andy Hungc54b1ff2016-02-23 14:07:07 -08003457 // mFramesWritten for non-offloaded tracks are contiguous
3458 // even after standby() is called. This is useful for the track frame
3459 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003460 bool serverLocationUpdate = false;
3461 if (mFramesWritten != lastFramesWritten) {
3462 serverLocationUpdate = true;
3463 lastFramesWritten = mFramesWritten;
3464 }
3465 // Only update timestamps if there is a meaningful change.
3466 // Either the kernel timestamp must be valid or we have written something.
3467 if (kernelLocationUpdate || serverLocationUpdate) {
3468 if (serverLocationUpdate) {
3469 // use the time before we called the HAL write - it is a bit more accurate
3470 // to when the server last read data than the current time here.
3471 //
Andy Hung446f4df2019-02-21 12:26:41 -08003472 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003473 // and we use systemTime().
3474 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003475 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3476 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003477 }
Andy Hungdae27702016-10-31 14:01:16 -07003478
3479 for (const sp<Track> &t : mActiveTracks) {
3480 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003481 t->updateTrackFrameInfo(
3482 t->mAudioTrackServerProxy->framesReleased(),
3483 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003484 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003485 mTimestamp);
3486 }
Andy Hunge10393e2015-06-12 13:59:33 -07003487 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003488 }
Andy Hunge6c37112019-02-26 17:38:10 -08003489
3490 if (audio_has_proportional_frames(mFormat)) {
3491 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3492 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3493 mLatencyMs.add(latencyMs);
3494 }
3495 }
3496
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003497 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003498#if 0
3499 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003500 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003501 timespec ts;
3502 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003503 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003504 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003505 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003506 }
3507 ++z;
3508#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003509 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 if (mSignalPending) {
3511 // A signal was raised while we were unlocked
3512 mSignalPending = false;
3513 } else if (waitingAsyncCallback_l()) {
3514 if (exitPending()) {
3515 break;
3516 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003517 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003518 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003519 releaseWakeLock_l();
3520 released = true;
3521 }
Andy Hung10cbff12017-02-21 17:30:14 -08003522
3523 const int64_t waitNs = computeWaitTimeNs_l();
3524 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3525 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3526 if (status == TIMED_OUT) {
3527 mSignalPending = true; // if timeout recheck everything
3528 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003530 if (released) {
3531 acquireWakeLock_l();
3532 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003533 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3534 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003535
3536 continue;
3537 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003538 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003539 isSuspended()) {
3540 // put audio hardware into standby after short delay
3541 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003542
3543 threadLoop_standby();
3544
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003545 // This is where we go into standby
3546 if (!mStandby) {
3547 LOG_AUDIO_STATE();
3548 }
Eric Laurent81784c32012-11-19 14:55:58 -08003549 mStandby = true;
Andy Hungd0979812019-02-21 15:51:44 -08003550 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003551 }
3552
Eric Tan39ec8d62018-07-24 09:49:29 -07003553 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003554 // we're about to wait, flush the binder command buffer
3555 IPCThreadState::self()->flushCommands();
3556
3557 clearOutputTracks();
3558
3559 if (exitPending()) {
3560 break;
3561 }
3562
3563 releaseWakeLock_l();
3564 // wait until we have something to do...
3565 ALOGV("%s going to sleep", myName.string());
3566 mWaitWorkCV.wait(mLock);
3567 ALOGV("%s waking up", myName.string());
3568 acquireWakeLock_l();
3569
3570 mMixerStatus = MIXER_IDLE;
3571 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3572 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003574 checkSilentMode_l();
3575
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003576 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3577 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003578 if (mType == MIXER) {
3579 sleepTimeShift = 0;
3580 }
3581
3582 continue;
3583 }
3584 }
Eric Laurent81784c32012-11-19 14:55:58 -08003585 // mMixerStatusIgnoringFastTracks is also updated internally
3586 mMixerStatus = prepareTracks_l(&tracksToRemove);
3587
Andy Hungdae27702016-10-31 14:01:16 -07003588 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003589
Kevin Rocard069c2712018-03-29 19:09:14 -07003590 updateMetadata_l();
3591
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // prevent any changes in effect chain list and in each effect chain
3593 // during mixing and effect process as the audio buffers could be deleted
3594 // or modified if an effect is created or deleted
3595 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003596
3597 // Determine which session to pick up haptic data.
3598 // This must be done under the same lock as prepareTracks_l().
3599 // TODO: Write haptic data directly to sink buffer when mixing.
3600 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3601 for (const auto& track : mActiveTracks) {
3602 if (track->getHapticPlaybackEnabled()) {
3603 activeHapticSessionId = track->sessionId();
3604 break;
3605 }
3606 }
3607 }
3608
Andy Hungc1646382019-04-30 16:12:10 -07003609 // Acquire a local copy of active tracks with lock (release w/o lock).
3610 //
3611 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3612 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3613 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3614 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003615 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003616
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 if (mBytesRemaining == 0) {
3618 mCurrentWriteLength = 0;
3619 if (mMixerStatus == MIXER_TRACKS_READY) {
3620 // threadLoop_mix() sets mCurrentWriteLength
3621 threadLoop_mix();
3622 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3623 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003624 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003625 // must be written to HAL
3626 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003627 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003628 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003629
3630 // Tally underrun frames as we are inserting 0s here.
3631 for (const auto& track : activeTracks) {
3632 if (track->mFillingUpStatus == Track::FS_ACTIVE) {
3633 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3634 }
3635 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003636 }
3637 }
Andy Hung98ef9782014-03-04 14:46:50 -08003638 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003639 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003640 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3641 // or mSinkBuffer (if there are no effects).
3642 //
3643 // This is done pre-effects computation; if effects change to
3644 // support higher precision, this needs to move.
3645 //
3646 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003647 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003648 if (mMixerBufferValid) {
3649 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3650 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3651
Andy Hung2ddee192015-12-18 17:34:44 -08003652 // mono blend occurs for mixer threads only (not direct or offloaded)
3653 // and is handled here if we're going directly to the sink.
3654 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003655 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3656 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003657 }
3658
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003659 if (!hasFastMixer()) {
3660 // Balance must take effect after mono conversion.
3661 // We do it here if there is no FastMixer.
3662 // mBalance detects zero balance within the class for speed (not needed here).
3663 mBalance.setBalance(mMasterBalance.load());
3664 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3665 }
3666
Andy Hung98ef9782014-03-04 14:46:50 -08003667 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003668 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3669
3670 // If we're going directly to the sink and there are haptic channels,
3671 // we should adjust channels as the sample data is partially interleaved
3672 // in this case.
3673 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3674 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3675 mChannelCount + mHapticChannelCount,
3676 audio_bytes_per_sample(format),
3677 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3678 }
Andy Hung98ef9782014-03-04 14:46:50 -08003679 }
3680
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 mBytesRemaining = mCurrentWriteLength;
3682 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003683 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3684 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3685 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3686 mBytesWritten += mBytesRemaining;
3687 mFramesWritten += framesRemaining;
3688 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003689 mBytesRemaining = 0;
3690 }
Eric Laurent81784c32012-11-19 14:55:58 -08003691
Eric Laurentbfb1b832013-01-07 09:53:42 -08003692 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003693 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003694 for (size_t i = 0; i < effectChains.size(); i ++) {
3695 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003696 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003697 if (activeHapticSessionId != AUDIO_SESSION_NONE
3698 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003699 // Haptic data is active in this case, copy it directly from
3700 // in buffer to out buffer.
3701 const size_t audioBufferSize = mNormalFrameCount
3702 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3703 memcpy_by_audio_format(
3704 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3705 EFFECT_BUFFER_FORMAT,
3706 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3707 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3708 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003709 }
Eric Laurent81784c32012-11-19 14:55:58 -08003710 }
3711 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003712 // Process effect chains for offloaded thread even if no audio
3713 // was read from audio track: process only updates effect state
3714 // and thus does have to be synchronized with audio writes but may have
3715 // to be called while waiting for async write callback
3716 if (mType == OFFLOAD) {
3717 for (size_t i = 0; i < effectChains.size(); i ++) {
3718 effectChains[i]->process_l();
3719 }
3720 }
Eric Laurent81784c32012-11-19 14:55:58 -08003721
Andy Hung98ef9782014-03-04 14:46:50 -08003722 // Only if the Effects buffer is enabled and there is data in the
3723 // Effects buffer (buffer valid), we need to
3724 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003725 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003726 if (mEffectBufferValid) {
3727 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003728
3729 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003730 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3731 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003732 }
3733
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003734 if (!hasFastMixer()) {
3735 // Balance must take effect after mono conversion.
3736 // We do it here if there is no FastMixer.
3737 // mBalance detects zero balance within the class for speed (not needed here).
3738 mBalance.setBalance(mMasterBalance.load());
3739 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3740 }
3741
Andy Hung98ef9782014-03-04 14:46:50 -08003742 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003743 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3744 // The sample data is partially interleaved when haptic channels exist,
3745 // we need to adjust channels here.
3746 if (mHapticChannelCount > 0) {
3747 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3748 mChannelCount + mHapticChannelCount,
3749 audio_bytes_per_sample(mFormat),
3750 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3751 }
Andy Hung98ef9782014-03-04 14:46:50 -08003752 }
3753
Eric Laurent81784c32012-11-19 14:55:58 -08003754 // enable changes in effect chain
3755 unlockEffectChains(effectChains);
3756
Eric Laurentbfb1b832013-01-07 09:53:42 -08003757 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003758 // mSleepTimeUs == 0 means we must write to audio hardware
3759 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003760 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003761 // writePeriodNs is updated >= 0 when ret > 0.
3762 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003763 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003764 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003765 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003766 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003767 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003768 if (ret < 0) {
3769 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003770 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003771 mBytesWritten += ret;
3772 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003773 const int64_t frames = ret / mFrameSize;
3774 mFramesWritten += frames;
3775
3776 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3777 // process information relating to write time.
3778 if (audio_has_proportional_frames(mFormat)) {
3779 // we are in a continuous mixing cycle
3780 if (mMixerStatus == MIXER_TRACKS_READY &&
3781 loopCount == lastLoopCountWritten + 1) {
3782
3783 const double jitterMs =
3784 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3785 {frames, writePeriodNs},
3786 {0, 0} /* lastTimestamp */, mSampleRate);
3787 const double processMs =
3788 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3789
3790 Mutex::Autolock _l(mLock);
3791 mIoJitterMs.add(jitterMs);
3792 mProcessTimeMs.add(processMs);
3793 }
3794
3795 // write blocked detection
3796 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3797 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3798 mNumDelayedWrites++;
3799 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3800 ATRACE_NAME("underrun");
3801 ALOGW("write blocked for %lld msecs, "
3802 "%d delayed writes, thread %d",
3803 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3804 mNumDelayedWrites, mId);
3805 lastWarning = lastIoEndNs;
3806 }
3807 }
3808 }
3809 // update timing info.
3810 mLastIoBeginNs = lastIoBeginNs;
3811 mLastIoEndNs = lastIoEndNs;
3812 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003813 }
3814 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3815 (mMixerStatus == MIXER_DRAIN_ALL)) {
3816 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003817 }
Andy Hung08fb1742015-05-31 23:22:10 -07003818 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003819
3820 if (mThreadThrottle
3821 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003822 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003823 // Limit MixerThread data processing to no more than twice the
3824 // expected processing rate.
3825 //
3826 // This helps prevent underruns with NuPlayer and other applications
3827 // which may set up buffers that are close to the minimum size, or use
3828 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3829 //
3830 // The throttle smooths out sudden large data drains from the device,
3831 // e.g. when it comes out of standby, which often causes problems with
3832 // (1) mixer threads without a fast mixer (which has its own warm-up)
3833 // (2) minimum buffer sized tracks (even if the track is full,
3834 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003835 //
3836 // Total time spent in last processing cycle equals time spent in
3837 // 1. threadLoop_write, as well as time spent in
3838 // 2. threadLoop_mix (significant for heavy mixing, especially
3839 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003840
Andy Hung446f4df2019-02-21 12:26:41 -08003841 // it's OK if deltaMs is an overestimate.
3842
3843 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003844
Ivan Lozanoea04d392017-11-07 14:37:07 -08003845 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003846 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3847 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003848 // notify of throttle start on verbose log
3849 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3850 "mixer(%p) throttle begin:"
3851 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003852 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003853 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003854 // Throttle must be attributed to the previous mixer loop's write time
3855 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003856 // This also ensures proper timing statistics.
3857 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003858 } else {
3859 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3860 if (diff > 0) {
3861 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003862 // but prevent spamming for bluetooth
jiabin10d86fd2019-10-31 17:20:42 -07003863 ALOGD_IF(!isSingleDeviceType(
3864 outDeviceTypes(), audio_is_a2dp_out_device) &&
3865 !isSingleDeviceType(
3866 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003867 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003868 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3869 }
Andy Hung08fb1742015-05-31 23:22:10 -07003870 }
3871 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003872 }
Eric Laurent81784c32012-11-19 14:55:58 -08003873
Eric Laurentbfb1b832013-01-07 09:53:42 -08003874 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003875 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003876 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003877 // suspended requires accurate metering of sleep time.
3878 if (isSuspended()) {
3879 // advance by expected sleepTime
3880 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3881 const nsecs_t nowNs = systemTime();
3882
3883 // compute expected next time vs current time.
3884 // (negative deltas are treated as delays).
3885 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3886 if (deltaNs < -kMaxNextBufferDelayNs) {
3887 // Delays longer than the max allowed trigger a reset.
3888 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3889 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3890 timeLoopNextNs = nowNs + deltaNs;
3891 } else if (deltaNs < 0) {
3892 // Delays within the max delay allowed: zero the delta/sleepTime
3893 // to help the system catch up in the next iteration(s)
3894 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3895 deltaNs = 0;
3896 }
3897 // update sleep time (which is >= 0)
3898 mSleepTimeUs = deltaNs / 1000;
3899 }
Eric Laurente93cc032016-05-05 10:15:10 -07003900 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3901 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003902 }
Glenn Kastene7754022014-10-31 12:11:26 -07003903 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003904 }
Eric Laurent81784c32012-11-19 14:55:58 -08003905 }
3906
3907 // Finally let go of removed track(s), without the lock held
3908 // since we can't guarantee the destructors won't acquire that
3909 // same lock. This will also mutate and push a new fast mixer state.
3910 threadLoop_removeTracks(tracksToRemove);
3911 tracksToRemove.clear();
3912
3913 // FIXME I don't understand the need for this here;
3914 // it was in the original code but maybe the
3915 // assignment in saveOutputTracks() makes this unnecessary?
3916 clearOutputTracks();
3917
3918 // Effect chains will be actually deleted here if they were removed from
3919 // mEffectChains list during mixing or effects processing
3920 effectChains.clear();
3921
3922 // FIXME Note that the above .clear() is no longer necessary since effectChains
3923 // is now local to this block, but will keep it for now (at least until merge done).
3924 }
3925
Eric Laurentbfb1b832013-01-07 09:53:42 -08003926 threadLoop_exit();
3927
Eric Laurentcf817a22014-08-04 20:36:31 -07003928 if (!mStandby) {
3929 threadLoop_standby();
3930 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003931 }
3932
3933 releaseWakeLock();
3934
3935 ALOGV("Thread %p type %d exiting", this, mType);
3936 return false;
3937}
3938
Eric Laurentbfb1b832013-01-07 09:53:42 -08003939// removeTracks_l() must be called with ThreadBase::mLock held
3940void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3941{
Andy Hungfe726a62018-09-27 15:17:25 -07003942 for (const auto& track : tracksToRemove) {
3943 mActiveTracks.remove(track);
3944 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3945 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3946 if (chain != 0) {
3947 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3948 __func__, track->id(), chain.get(), track->sessionId());
3949 chain->decActiveTrackCnt();
3950 }
3951 // If an external client track, inform APM we're no longer active, and remove if needed.
3952 // We do this under lock so that the state is consistent if the Track is destroyed.
3953 if (track->isExternalTrack()) {
3954 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003955 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003956 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003957 }
3958 }
Andy Hungfe726a62018-09-27 15:17:25 -07003959 if (track->isTerminated()) {
3960 // remove from our tracks vector
3961 removeTrack_l(track);
3962 }
jiabin57303cc2018-12-18 15:45:57 -08003963 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3964 && mHapticChannelCount > 0) {
3965 mLock.unlock();
3966 // Unlock due to VibratorService will lock for this call and will
3967 // call Tracks.mute/unmute which also require thread's lock.
3968 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3969 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003970 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003971 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003972}
Eric Laurent81784c32012-11-19 14:55:58 -08003973
Eric Laurentaccc1472013-09-20 09:36:34 -07003974status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3975{
3976 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003977 ExtendedTimestamp ets;
3978 status_t status = mNormalSink->getTimestamp(ets);
3979 if (status == NO_ERROR) {
3980 status = ets.getBestTimestamp(&timestamp);
3981 }
3982 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003983 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003984 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003985 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003986 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003987 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003988 if (mDownstreamLatencyStatMs.getN() > 0) {
3989 const uint32_t positionOffset =
3990 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3991 if (positionOffset > timestamp.mPosition) {
3992 timestamp.mPosition = 0;
3993 } else {
3994 timestamp.mPosition -= positionOffset;
3995 }
3996 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003997 return NO_ERROR;
3998 }
3999 }
4000 return INVALID_OPERATION;
4001}
Eric Laurent1c333e22014-05-20 10:48:17 -07004002
Eric Laurenteab90452019-06-24 15:17:46 -07004003// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4004// still applied by the mixer.
4005// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4006// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4007// if more than one track are active
4008status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4009{
4010 status_t result = NO_ERROR;
4011 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4012 if (*volume != mLeftVolFloat) {
4013 result = mOutput->stream->setVolume(*volume, *volume);
4014 ALOGE_IF(result != OK,
4015 "Error when setting output stream volume: %d", result);
4016 if (result == NO_ERROR) {
4017 mLeftVolFloat = *volume;
4018 }
4019 }
4020 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4021 // remove stream volume contribution from software volume.
4022 if (mLeftVolFloat == *volume) {
4023 *volume = 1.0f;
4024 }
4025 }
4026 return result;
4027}
4028
Eric Laurent054d9d32015-04-24 08:48:48 -07004029status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4030 audio_patch_handle_t *handle)
4031{
Andy Hungf60abce2016-08-26 11:37:54 -07004032 status_t status;
4033 if (property_get_bool("af.patch_park", false /* default_value */)) {
4034 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4035 // or if HAL does not properly lock against access.
4036 AutoPark<FastMixer> park(mFastMixer);
4037 status = PlaybackThread::createAudioPatch_l(patch, handle);
4038 } else {
4039 status = PlaybackThread::createAudioPatch_l(patch, handle);
4040 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004041 return status;
4042}
4043
Eric Laurent1c333e22014-05-20 10:48:17 -07004044status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4045 audio_patch_handle_t *handle)
4046{
4047 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004048
4049 // store new device and send to effects
4050 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabin10d86fd2019-10-31 17:20:42 -07004051 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004052 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07004053 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4054 && !mOutput->audioHwDev->supportsAudioPatches(),
4055 "Enumerated device type(%#x) must not be used "
4056 "as it does not support audio patches",
4057 patch->sinks[i].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004058 type |= patch->sinks[i].ext.device.type;
jiabin10d86fd2019-10-31 17:20:42 -07004059 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4060 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004061 }
4062
François Gaffie0c280aa2018-07-25 10:02:15 +02004063 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004064#ifdef ADD_BATTERY_DATA
4065 // when changing the audio output device, call addBatteryData to notify
4066 // the change
jiabin10d86fd2019-10-31 17:20:42 -07004067 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004068 uint32_t params = 0;
4069 // check whether speaker is on
jiabin10d86fd2019-10-31 17:20:42 -07004070 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004071 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004072 }
4073
Eric Laurent054d9d32015-04-24 08:48:48 -07004074 // check if any other device (except speaker) is on
jiabin10d86fd2019-10-31 17:20:42 -07004075 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004076 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4077 }
4078
4079 if (params != 0) {
4080 addBatteryData(params);
4081 }
4082 }
4083#endif
4084
4085 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08004086 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004087 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004088
jiabin10d86fd2019-10-31 17:20:42 -07004089 // mPatch.num_sinks is not set when the thread is created so that
4090 // the first patch creation triggers an ioConfigChanged callback
4091 bool configChanged = (mPatch.num_sinks == 0) ||
4092 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004093 mPatch = *patch;
jiabin10d86fd2019-10-31 17:20:42 -07004094 mOutDeviceTypeAddrs = deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004095
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004096 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004097 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4098 status = hwDevice->createAudioPatch(patch->num_sources,
4099 patch->sources,
4100 patch->num_sinks,
4101 patch->sinks,
4102 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004103 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004104 char *address;
4105 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4106 //FIXME: we only support address on first sink with HAL version < 3.0
4107 address = audio_device_address_to_parameter(
4108 patch->sinks[0].ext.device.type,
4109 patch->sinks[0].ext.device.address);
4110 } else {
4111 address = (char *)calloc(1, 1);
4112 }
4113 AudioParameter param = AudioParameter(String8(address));
4114 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004115 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004116 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004117 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004118 }
Eric Laurente8726fe2015-06-26 09:39:24 -07004119 if (configChanged) {
4120 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4121 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004122 return status;
4123}
4124
Eric Laurent054d9d32015-04-24 08:48:48 -07004125status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4126{
Andy Hungf60abce2016-08-26 11:37:54 -07004127 status_t status;
4128 if (property_get_bool("af.patch_park", false /* default_value */)) {
4129 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4130 // or if HAL does not properly lock against access.
4131 AutoPark<FastMixer> park(mFastMixer);
4132 status = PlaybackThread::releaseAudioPatch_l(handle);
4133 } else {
4134 status = PlaybackThread::releaseAudioPatch_l(handle);
4135 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004136 return status;
4137}
4138
Eric Laurent1c333e22014-05-20 10:48:17 -07004139status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4140{
4141 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004142
jiabin10d86fd2019-10-31 17:20:42 -07004143 mPatch = audio_patch{};
4144 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004145
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004146 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004147 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4148 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004149 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004150 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004151 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004152 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004153 }
4154 return status;
4155}
4156
Eric Laurent83b88082014-06-20 18:31:16 -07004157void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4158{
4159 Mutex::Autolock _l(mLock);
4160 mTracks.add(track);
4161}
4162
4163void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4164{
4165 Mutex::Autolock _l(mLock);
4166 destroyTrack_l(track);
4167}
4168
Mikhail Naganovdc769682018-05-04 15:34:08 -07004169void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004170{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004171 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004172 config->role = AUDIO_PORT_ROLE_SOURCE;
4173 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4174 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004175 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4176 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4177 config->flags.output = mOutput->flags;
4178 }
Eric Laurent83b88082014-06-20 18:31:16 -07004179}
4180
Eric Laurent81784c32012-11-19 14:55:58 -08004181// ----------------------------------------------------------------------------
4182
4183AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabin10d86fd2019-10-31 17:20:42 -07004184 audio_io_handle_t id, bool systemReady, type_t type)
4185 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004186 // mAudioMixer below
4187 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004188 mFastMixerFutex(0),
4189 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004190 // mOutputSink below
4191 // mPipeSink below
4192 // mNormalSink below
4193{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004194 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabin10d86fd2019-10-31 17:20:42 -07004195 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004196 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004197 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004198 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4199 mNormalFrameCount);
4200 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4201
Andy Hungfbfc3952015-01-15 13:33:51 -08004202 if (type == DUPLICATING) {
4203 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4204 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4205 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4206 return;
4207 }
Eric Laurent81784c32012-11-19 14:55:58 -08004208 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004209 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004210 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004211 const NBAIO_Format offers[1] = {Format_from_SR_C(
4212 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004213#if !LOG_NDEBUG
4214 ssize_t index =
4215#else
4216 (void)
4217#endif
4218 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004219 ALOG_ASSERT(index == 0);
4220
4221 // initialize fast mixer depending on configuration
4222 bool initFastMixer;
4223 switch (kUseFastMixer) {
4224 case FastMixer_Never:
4225 initFastMixer = false;
4226 break;
4227 case FastMixer_Always:
4228 initFastMixer = true;
4229 break;
4230 case FastMixer_Static:
4231 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004232 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4233 // where the period is less than an experimentally determined threshold that can be
4234 // scheduled reliably with CFS. However, the BT A2DP HAL is
4235 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4236 initFastMixer = mFrameCount < mNormalFrameCount
jiabin10d86fd2019-10-31 17:20:42 -07004237 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004238 break;
4239 }
Andy Hungfda69402017-02-15 14:33:12 -08004240 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4241 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4242 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004243 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004244 audio_format_t fastMixerFormat;
4245 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4246 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4247 } else {
4248 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4249 }
4250 if (mFormat != fastMixerFormat) {
4251 // change our Sink format to accept our intermediate precision
4252 mFormat = fastMixerFormat;
4253 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004254 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004255 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4256 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4257 }
Eric Laurent81784c32012-11-19 14:55:58 -08004258
4259 // create a MonoPipe to connect our submix to FastMixer
4260 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004261
Andy Hung1258c1a2014-05-23 21:22:17 -07004262 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004263 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004264 format.mFormat = fastMixerFormat;
4265 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4266
Eric Laurent81784c32012-11-19 14:55:58 -08004267 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4268 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4269 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4270 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4271 const NBAIO_Format offers[1] = {format};
4272 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004273#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004274 ssize_t index =
4275#else
4276 (void)
4277#endif
4278 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004279 ALOG_ASSERT(index == 0);
4280 monoPipe->setAvgFrames((mScreenState & 1) ?
4281 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4282 mPipeSink = monoPipe;
4283
Eric Laurent81784c32012-11-19 14:55:58 -08004284 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004285 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004286 FastMixerStateQueue *sq = mFastMixer->sq();
4287#ifdef STATE_QUEUE_DUMP
4288 sq->setObserverDump(&mStateQueueObserverDump);
4289 sq->setMutatorDump(&mStateQueueMutatorDump);
4290#endif
4291 FastMixerState *state = sq->begin();
4292 FastTrack *fastTrack = &state->mFastTracks[0];
4293 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4294 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4295 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004296 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4297 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004298 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004299 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004300 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004301 fastTrack->mGeneration++;
4302 state->mFastTracksGen++;
4303 state->mTrackMask = 1;
4304 // fast mixer will use the HAL output sink
4305 state->mOutputSink = mOutputSink.get();
4306 state->mOutputSinkGen++;
4307 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004308 // specify sink channel mask when haptic channel mask present as it can not
4309 // be calculated directly from channel count
4310 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4311 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004312 state->mCommand = FastMixerState::COLD_IDLE;
4313 // already done in constructor initialization list
4314 //mFastMixerFutex = 0;
4315 state->mColdFutexAddr = &mFastMixerFutex;
4316 state->mColdGen++;
4317 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004318 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4319 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004320 sq->end();
4321 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4322
Eric Tan0513b5d2018-09-17 10:32:48 -07004323 NBLog::thread_info_t info;
4324 info.id = mId;
4325 info.type = NBLog::FASTMIXER;
4326 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4327
Eric Laurent81784c32012-11-19 14:55:58 -08004328 // start the fast mixer
4329 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4330 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004331 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004332 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004333
4334#ifdef AUDIO_WATCHDOG
4335 // create and start the watchdog
4336 mAudioWatchdog = new AudioWatchdog();
4337 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4338 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4339 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004340 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004341#endif
Andy Hung8946a282018-04-19 20:04:56 -07004342 } else {
4343#ifdef TEE_SINK
4344 // Only use the MixerThread tee if there is no FastMixer.
4345 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4346 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4347#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004348 }
4349
4350 switch (kUseFastMixer) {
4351 case FastMixer_Never:
4352 case FastMixer_Dynamic:
4353 mNormalSink = mOutputSink;
4354 break;
4355 case FastMixer_Always:
4356 mNormalSink = mPipeSink;
4357 break;
4358 case FastMixer_Static:
4359 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4360 break;
4361 }
4362}
4363
4364AudioFlinger::MixerThread::~MixerThread()
4365{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004366 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004367 FastMixerStateQueue *sq = mFastMixer->sq();
4368 FastMixerState *state = sq->begin();
4369 if (state->mCommand == FastMixerState::COLD_IDLE) {
4370 int32_t old = android_atomic_inc(&mFastMixerFutex);
4371 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004372 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004373 }
4374 }
4375 state->mCommand = FastMixerState::EXIT;
4376 sq->end();
4377 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4378 mFastMixer->join();
4379 // Though the fast mixer thread has exited, it's state queue is still valid.
4380 // We'll use that extract the final state which contains one remaining fast track
4381 // corresponding to our sub-mix.
4382 state = sq->begin();
4383 ALOG_ASSERT(state->mTrackMask == 1);
4384 FastTrack *fastTrack = &state->mFastTracks[0];
4385 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4386 delete fastTrack->mBufferProvider;
4387 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004388 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004389#ifdef AUDIO_WATCHDOG
4390 if (mAudioWatchdog != 0) {
4391 mAudioWatchdog->requestExit();
4392 mAudioWatchdog->requestExitAndWait();
4393 mAudioWatchdog.clear();
4394 }
4395#endif
4396 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004397 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004398 delete mAudioMixer;
4399}
4400
4401
4402uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4403{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004404 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004405 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4406 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4407 }
4408 return latency;
4409}
4410
Eric Laurentbfb1b832013-01-07 09:53:42 -08004411ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004412{
4413 // FIXME we should only do one push per cycle; confirm this is true
4414 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004415 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004416 FastMixerStateQueue *sq = mFastMixer->sq();
4417 FastMixerState *state = sq->begin();
4418 if (state->mCommand != FastMixerState::MIX_WRITE &&
4419 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4420 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004421
4422 // FIXME workaround for first HAL write being CPU bound on some devices
4423 ATRACE_BEGIN("write");
4424 mOutput->write((char *)mSinkBuffer, 0);
4425 ATRACE_END();
4426
Eric Laurent81784c32012-11-19 14:55:58 -08004427 int32_t old = android_atomic_inc(&mFastMixerFutex);
4428 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004429 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004430 }
4431#ifdef AUDIO_WATCHDOG
4432 if (mAudioWatchdog != 0) {
4433 mAudioWatchdog->resume();
4434 }
4435#endif
4436 }
4437 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004438#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004439 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004440 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004441#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004442 sq->end();
4443 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4444 if (kUseFastMixer == FastMixer_Dynamic) {
4445 mNormalSink = mPipeSink;
4446 }
4447 } else {
4448 sq->end(false /*didModify*/);
4449 }
4450 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004451 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004452}
4453
4454void AudioFlinger::MixerThread::threadLoop_standby()
4455{
4456 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004457 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004458 FastMixerStateQueue *sq = mFastMixer->sq();
4459 FastMixerState *state = sq->begin();
4460 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004461 // Report any frames trapped in the Monopipe
4462 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4463 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4464 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4465 "monoPipeWritten:%lld monoPipeLeft:%lld",
4466 (long long)mFramesWritten, (long long)mSuspendedFrames,
4467 (long long)mPipeSink->framesWritten(), pipeFrames);
4468 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4469
Eric Laurent81784c32012-11-19 14:55:58 -08004470 state->mCommand = FastMixerState::COLD_IDLE;
4471 state->mColdFutexAddr = &mFastMixerFutex;
4472 state->mColdGen++;
4473 mFastMixerFutex = 0;
4474 sq->end();
4475 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4476 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4477 if (kUseFastMixer == FastMixer_Dynamic) {
4478 mNormalSink = mOutputSink;
4479 }
4480#ifdef AUDIO_WATCHDOG
4481 if (mAudioWatchdog != 0) {
4482 mAudioWatchdog->pause();
4483 }
4484#endif
4485 } else {
4486 sq->end(false /*didModify*/);
4487 }
4488 }
4489 PlaybackThread::threadLoop_standby();
4490}
4491
Eric Laurentbfb1b832013-01-07 09:53:42 -08004492bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4493{
4494 return false;
4495}
4496
4497bool AudioFlinger::PlaybackThread::shouldStandby_l()
4498{
4499 return !mStandby;
4500}
4501
4502bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4503{
4504 Mutex::Autolock _l(mLock);
4505 return waitingAsyncCallback_l();
4506}
4507
Eric Laurent81784c32012-11-19 14:55:58 -08004508// shared by MIXER and DIRECT, overridden by DUPLICATING
4509void AudioFlinger::PlaybackThread::threadLoop_standby()
4510{
4511 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004512 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004513 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004514 // discard any pending drain or write ack by incrementing sequence
4515 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4516 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004517 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004518 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4519 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004520 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004521 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004522}
4523
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004524void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4525{
4526 ALOGV("signal playback thread");
4527 broadcast_l();
4528}
4529
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004530void AudioFlinger::PlaybackThread::onAsyncError()
4531{
4532 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4533 invalidateTracks((audio_stream_type_t)i);
4534 }
4535}
4536
Eric Laurent81784c32012-11-19 14:55:58 -08004537void AudioFlinger::MixerThread::threadLoop_mix()
4538{
Eric Laurent81784c32012-11-19 14:55:58 -08004539 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004540 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004541 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004542 // increase sleep time progressively when application underrun condition clears.
4543 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4544 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4545 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004546 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004547 sleepTimeShift--;
4548 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004549 mSleepTimeUs = 0;
4550 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004551 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004552
Eric Laurent81784c32012-11-19 14:55:58 -08004553}
4554
4555void AudioFlinger::MixerThread::threadLoop_sleepTime()
4556{
4557 // If no tracks are ready, sleep once for the duration of an output
4558 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004559 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004560 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004561 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4562 // Using the Monopipe availableToWrite, we estimate the
4563 // sleep time to retry for more data (before we underrun).
4564 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4565 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4566 const size_t pipeFrames = monoPipe->maxFrames();
4567 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4568 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4569 const size_t framesDelay = std::min(
4570 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4571 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4572 pipeFrames, framesLeft, framesDelay);
4573 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4574 } else {
4575 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4576 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4577 mSleepTimeUs = kMinThreadSleepTimeUs;
4578 }
4579 // reduce sleep time in case of consecutive application underruns to avoid
4580 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4581 // duration we would end up writing less data than needed by the audio HAL if
4582 // the condition persists.
4583 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4584 sleepTimeShift++;
4585 }
Eric Laurent81784c32012-11-19 14:55:58 -08004586 }
4587 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004588 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004589 }
4590 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004591 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4592 // before effects processing or output.
4593 if (mMixerBufferValid) {
4594 memset(mMixerBuffer, 0, mMixerBufferSize);
4595 } else {
4596 memset(mSinkBuffer, 0, mSinkBufferSize);
4597 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004598 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004599 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4600 "anticipated start");
4601 }
4602 // TODO add standby time extension fct of effect tail
4603}
4604
4605// prepareTracks_l() must be called with ThreadBase::mLock held
4606AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4607 Vector< sp<Track> > *tracksToRemove)
4608{
Andy Hungc0691382018-09-12 18:01:57 -07004609 // clean up deleted track ids in AudioMixer before allocating new tracks
4610 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4611 // for each trackId, destroy it in the AudioMixer
4612 if (mAudioMixer->exists(trackId)) {
4613 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004614 }
4615 });
Andy Hungc0691382018-09-12 18:01:57 -07004616 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004617
4618 mixer_state mixerStatus = MIXER_IDLE;
4619 // find out which tracks need to be processed
4620 size_t count = mActiveTracks.size();
4621 size_t mixedTracks = 0;
4622 size_t tracksWithEffect = 0;
4623 // counts only _active_ fast tracks
4624 size_t fastTracks = 0;
4625 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4626
4627 float masterVolume = mMasterVolume;
4628 bool masterMute = mMasterMute;
4629
4630 if (masterMute) {
4631 masterVolume = 0;
4632 }
4633 // Delegate master volume control to effect in output mix effect chain if needed
4634 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4635 if (chain != 0) {
4636 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4637 chain->setVolume_l(&v, &v);
4638 masterVolume = (float)((v + (1 << 23)) >> 24);
4639 chain.clear();
4640 }
4641
4642 // prepare a new state to push
4643 FastMixerStateQueue *sq = NULL;
4644 FastMixerState *state = NULL;
4645 bool didModify = false;
4646 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004647 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004648 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004649 sq = mFastMixer->sq();
4650 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004651 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004652 }
4653
Andy Hung69aed5f2014-02-25 17:24:40 -08004654 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004655 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004656
Andy Hungbd3b2b02018-05-21 10:53:11 -07004657 // DeferredOperations handles statistics after setting mixerStatus.
4658 class DeferredOperations {
4659 public:
4660 DeferredOperations(mixer_state *mixerStatus)
4661 : mMixerStatus(mixerStatus) { }
4662
4663 // when leaving scope, tally frames properly.
4664 ~DeferredOperations() {
4665 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4666 // because that is when the underrun occurs.
4667 // We do not distinguish between FastTracks and NormalTracks here.
4668 if (*mMixerStatus == MIXER_TRACKS_READY) {
4669 for (const auto &underrun : mUnderrunFrames) {
4670 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4671 underrun.second);
4672 }
4673 }
4674 }
4675
4676 // tallyUnderrunFrames() is called to update the track counters
4677 // with the number of underrun frames for a particular mixer period.
4678 // We defer tallying until we know the final mixer status.
4679 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4680 mUnderrunFrames.emplace_back(track, underrunFrames);
4681 }
4682
4683 private:
4684 const mixer_state * const mMixerStatus;
4685 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4686 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4687
jiabin245cdd92018-12-07 17:55:15 -08004688 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004689 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004690 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004691
4692 // this const just means the local variable doesn't change
4693 Track* const track = t.get();
4694
4695 // process fast tracks
4696 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004697 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4698 "%s(%d): FastTrack(%d) present without FastMixer",
4699 __func__, id(), track->id());
4700
jiabin245cdd92018-12-07 17:55:15 -08004701 if (track->getHapticPlaybackEnabled()) {
4702 noFastHapticTrack = false;
4703 }
Eric Laurent81784c32012-11-19 14:55:58 -08004704
4705 // It's theoretically possible (though unlikely) for a fast track to be created
4706 // and then removed within the same normal mix cycle. This is not a problem, as
4707 // the track never becomes active so it's fast mixer slot is never touched.
4708 // The converse, of removing an (active) track and then creating a new track
4709 // at the identical fast mixer slot within the same normal mix cycle,
4710 // is impossible because the slot isn't marked available until the end of each cycle.
4711 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004712 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004713 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4714 FastTrack *fastTrack = &state->mFastTracks[j];
4715
4716 // Determine whether the track is currently in underrun condition,
4717 // and whether it had a recent underrun.
4718 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4719 FastTrackUnderruns underruns = ftDump->mUnderruns;
4720 uint32_t recentFull = (underruns.mBitFields.mFull -
4721 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4722 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4723 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4724 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4725 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4726 uint32_t recentUnderruns = recentPartial + recentEmpty;
4727 track->mObservedUnderruns = underruns;
4728 // don't count underruns that occur while stopping or pausing
4729 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004730 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004731 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4732 recentUnderruns > 0) {
4733 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004734 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004735 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004736 // Immediately account for FastTrack underruns.
4737 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004738
4739 // This is similar to the state machine for normal tracks,
4740 // with a few modifications for fast tracks.
4741 bool isActive = true;
4742 switch (track->mState) {
4743 case TrackBase::STOPPING_1:
4744 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004745 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004746 track->mState = TrackBase::STOPPING_2;
4747 }
4748 break;
4749 case TrackBase::PAUSING:
4750 // ramp down is not yet implemented
4751 track->setPaused();
4752 break;
4753 case TrackBase::RESUMING:
4754 // ramp up is not yet implemented
4755 track->mState = TrackBase::ACTIVE;
4756 break;
4757 case TrackBase::ACTIVE:
4758 if (recentFull > 0 || recentPartial > 0) {
4759 // track has provided at least some frames recently: reset retry count
4760 track->mRetryCount = kMaxTrackRetries;
4761 }
4762 if (recentUnderruns == 0) {
4763 // no recent underruns: stay active
4764 break;
4765 }
4766 // there has recently been an underrun of some kind
4767 if (track->sharedBuffer() == 0) {
4768 // were any of the recent underruns "empty" (no frames available)?
4769 if (recentEmpty == 0) {
4770 // no, then ignore the partial underruns as they are allowed indefinitely
4771 break;
4772 }
4773 // there has recently been an "empty" underrun: decrement the retry counter
4774 if (--(track->mRetryCount) > 0) {
4775 break;
4776 }
4777 // indicate to client process that the track was disabled because of underrun;
4778 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004779 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004780 // remove from active list, but state remains ACTIVE [confusing but true]
4781 isActive = false;
4782 break;
4783 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004784 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004785 case TrackBase::STOPPING_2:
4786 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004787 case TrackBase::STOPPED:
4788 case TrackBase::FLUSHED: // flush() while active
4789 // Check for presentation complete if track is inactive
4790 // We have consumed all the buffers of this track.
4791 // This would be incomplete if we auto-paused on underrun
4792 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004793 uint32_t latency = 0;
4794 status_t result = mOutput->stream->getLatency(&latency);
4795 ALOGE_IF(result != OK,
4796 "Error when retrieving output stream latency: %d", result);
4797 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004798 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004799 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4800 // track stays in active list until presentation is complete
4801 break;
4802 }
4803 }
4804 if (track->isStopping_2()) {
4805 track->mState = TrackBase::STOPPED;
4806 }
4807 if (track->isStopped()) {
4808 // Can't reset directly, as fast mixer is still polling this track
4809 // track->reset();
4810 // So instead mark this track as needing to be reset after push with ack
4811 resetMask |= 1 << i;
4812 }
4813 isActive = false;
4814 break;
4815 case TrackBase::IDLE:
4816 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004817 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004818 }
4819
4820 if (isActive) {
4821 // was it previously inactive?
4822 if (!(state->mTrackMask & (1 << j))) {
4823 ExtendedAudioBufferProvider *eabp = track;
4824 VolumeProvider *vp = track;
4825 fastTrack->mBufferProvider = eabp;
4826 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004827 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004828 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004829 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004830 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004831 fastTrack->mGeneration++;
4832 state->mTrackMask |= 1 << j;
4833 didModify = true;
4834 // no acknowledgement required for newly active tracks
4835 }
Kevin Rocard12381092018-04-11 09:19:59 -07004836 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07004837 float volume;
4838 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
4839 volume = 0.f;
4840 } else {
4841 volume = masterVolume * mStreamTypes[track->streamType()].volume;
4842 }
4843
4844 handleVoipVolume_l(&volume);
4845
Eric Laurent81784c32012-11-19 14:55:58 -08004846 // cache the combined master volume and stream type volume for fast mixer; this
4847 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004848 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07004849 proxy->framesReleased()).first;
4850 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004851 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004852 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4853 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4854 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07004855
Kevin Rocard12381092018-04-11 09:19:59 -07004856 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004857 ++fastTracks;
4858 } else {
4859 // was it previously active?
4860 if (state->mTrackMask & (1 << j)) {
4861 fastTrack->mBufferProvider = NULL;
4862 fastTrack->mGeneration++;
4863 state->mTrackMask &= ~(1 << j);
4864 didModify = true;
4865 // If any fast tracks were removed, we must wait for acknowledgement
4866 // because we're about to decrement the last sp<> on those tracks.
4867 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4868 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004869 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4870 // AudioTrack may start (which may not be with a start() but with a write()
4871 // after underrun) and immediately paused or released. In that case the
4872 // FastTrack state hasn't had time to update.
4873 // TODO Remove the ALOGW when this theory is confirmed.
4874 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004875 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4876 j, track->mState, state->mTrackMask, recentUnderruns,
4877 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004878 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004879 }
4880 tracksToRemove->add(track);
4881 // Avoids a misleading display in dumpsys
4882 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4883 }
jiabin245cdd92018-12-07 17:55:15 -08004884 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4885 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4886 didModify = true;
4887 }
Eric Laurent81784c32012-11-19 14:55:58 -08004888 continue;
4889 }
4890
4891 { // local variable scope to avoid goto warning
4892
4893 audio_track_cblk_t* cblk = track->cblk();
4894
4895 // The first time a track is added we wait
4896 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004897 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004898
4899 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004900 // use the trackId as the AudioMixer name.
4901 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004902 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004903 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004904 track->mChannelMask,
4905 track->mFormat,
4906 track->mSessionId);
4907 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004908 ALOGW("%s(): AudioMixer cannot create track(%d)"
4909 " mask %#x, format %#x, sessionId %d",
4910 __func__, trackId,
4911 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004912 tracksToRemove->add(track);
4913 track->invalidate(); // consider it dead.
4914 continue;
4915 }
4916 }
4917
Eric Laurent81784c32012-11-19 14:55:58 -08004918 // make sure that we have enough frames to mix one full buffer.
4919 // enforce this condition only once to enable draining the buffer in case the client
4920 // app does not call stop() and relies on underrun to stop:
4921 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4922 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004923 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004924 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004925 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004926
4927 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004928 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004929 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4930 // add frames already consumed but not yet released by the resampler
4931 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004932 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004933
Eric Laurent81784c32012-11-19 14:55:58 -08004934 uint32_t minFrames = 1;
4935 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4936 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004937 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004938 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004939
4940 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004941 if (ATRACE_ENABLED()) {
4942 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004943 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004944 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004945 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004946 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004947 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004948 !track->isPaused() && !track->isTerminated())
4949 {
Andy Hungc0691382018-09-12 18:01:57 -07004950 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004951
4952 mixedTracks++;
4953
Andy Hung69aed5f2014-02-25 17:24:40 -08004954 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4955 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004956 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004957 if (track->mainBuffer() != mSinkBuffer &&
4958 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004959 if (mEffectBufferEnabled) {
4960 mEffectBufferValid = true; // Later can set directly.
4961 }
Eric Laurent81784c32012-11-19 14:55:58 -08004962 chain = getEffectChain_l(track->sessionId());
4963 // Delegate volume control to effect in track effect chain if needed
4964 if (chain != 0) {
4965 tracksWithEffect++;
4966 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004967 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004968 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004969 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004970 }
4971 }
4972
4973
4974 int param = AudioMixer::VOLUME;
4975 if (track->mFillingUpStatus == Track::FS_FILLED) {
4976 // no ramp for the first volume setting
4977 track->mFillingUpStatus = Track::FS_ACTIVE;
4978 if (track->mState == TrackBase::RESUMING) {
4979 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08004980 // If a new track is paused immediately after start, do not ramp on resume.
4981 if (cblk->mServer != 0) {
4982 param = AudioMixer::RAMP_VOLUME;
4983 }
Eric Laurent81784c32012-11-19 14:55:58 -08004984 }
Andy Hungc0691382018-09-12 18:01:57 -07004985 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004986 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004987 // FIXME should not make a decision based on mServer
4988 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004989 // If the track is stopped before the first frame was mixed,
4990 // do not apply ramp
4991 param = AudioMixer::RAMP_VOLUME;
4992 }
4993
4994 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004995 uint32_t vl, vr; // in U8.24 integer format
4996 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004997 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07004998 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07004999 // Always fetch volumeshaper volume to ensure state is updated.
5000 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5001 const float vh = track->getVolumeHandler()->getVolume(
5002 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005003
Eric Laurenteab90452019-06-24 15:17:46 -07005004 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5005 v = 0;
5006 }
5007
5008 handleVoipVolume_l(&v);
5009
5010 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005011 vl = vr = 0;
5012 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005013 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005014 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005015 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005016 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5017 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005018 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005019 if (vlf > GAIN_FLOAT_UNITY) {
5020 ALOGV("Track left volume out of range: %.3g", vlf);
5021 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005022 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005023 if (vrf > GAIN_FLOAT_UNITY) {
5024 ALOGV("Track right volume out of range: %.3g", vrf);
5025 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005026 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005027 // now apply the master volume and stream type volume and shaper volume
5028 vlf *= v * vh;
5029 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005030 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005031 // then derive vl and vr as U8.24 versions for the effect chain
5032 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5033 vl = (uint32_t) (scaleto8_24 * vlf);
5034 vr = (uint32_t) (scaleto8_24 * vrf);
5035 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005036 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005037 // send level comes from shared memory and so may be corrupt
5038 if (sendLevel > MAX_GAIN_INT) {
5039 ALOGV("Track send level out of range: %04X", sendLevel);
5040 sendLevel = MAX_GAIN_INT;
5041 }
Andy Hung6be49402014-05-30 10:42:03 -07005042 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5043 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005044 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005045
Kevin Rocard12381092018-04-11 09:19:59 -07005046 track->setFinalVolume((vrf + vlf) / 2.f);
5047
Eric Laurent81784c32012-11-19 14:55:58 -08005048 // Delegate volume control to effect in track effect chain if needed
5049 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5050 // Do not ramp volume if volume is controlled by effect
5051 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005052 // Update remaining floating point volume levels
5053 vlf = (float)vl / (1 << 24);
5054 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005055 track->mHasVolumeController = true;
5056 } else {
5057 // force no volume ramp when volume controller was just disabled or removed
5058 // from effect chain to avoid volume spike
5059 if (track->mHasVolumeController) {
5060 param = AudioMixer::VOLUME;
5061 }
5062 track->mHasVolumeController = false;
5063 }
5064
Eric Laurent81784c32012-11-19 14:55:58 -08005065 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005066 mAudioMixer->setBufferProvider(trackId, track);
5067 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005068
Andy Hungc0691382018-09-12 18:01:57 -07005069 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5070 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5071 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005072 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005073 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005074 AudioMixer::TRACK,
5075 AudioMixer::FORMAT, (void *)track->format());
5076 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005077 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005078 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005079 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005080 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005081 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005082 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005083 AudioMixer::MIXER_CHANNEL_MASK,
5084 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005085 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005086 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005087 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005088 if (reqSampleRate == 0) {
5089 reqSampleRate = mSampleRate;
5090 } else if (reqSampleRate > maxSampleRate) {
5091 reqSampleRate = maxSampleRate;
5092 }
Eric Laurent81784c32012-11-19 14:55:58 -08005093 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005094 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005095 AudioMixer::RESAMPLE,
5096 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005097 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005098
Andy Hung333ab962019-05-28 20:23:35 -07005099 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005100 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005101 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005102 AudioMixer::TIMESTRETCH,
5103 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005104 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005105
Andy Hung69aed5f2014-02-25 17:24:40 -08005106 /*
5107 * Select the appropriate output buffer for the track.
5108 *
Andy Hung98ef9782014-03-04 14:46:50 -08005109 * Tracks with effects go into their own effects chain buffer
5110 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005111 *
5112 * Other tracks can use mMixerBuffer for higher precision
5113 * channel accumulation. If this buffer is enabled
5114 * (mMixerBufferEnabled true), then selected tracks will accumulate
5115 * into it.
5116 *
5117 */
5118 if (mMixerBufferEnabled
5119 && (track->mainBuffer() == mSinkBuffer
5120 || track->mainBuffer() == mMixerBuffer)) {
5121 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005122 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005123 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005124 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005125 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005126 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005127 AudioMixer::TRACK,
5128 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5129 // TODO: override track->mainBuffer()?
5130 mMixerBufferValid = true;
5131 } else {
5132 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005133 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005134 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005135 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005136 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005137 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005138 AudioMixer::TRACK,
5139 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5140 }
Eric Laurent81784c32012-11-19 14:55:58 -08005141 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005142 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005143 AudioMixer::TRACK,
5144 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005145 mAudioMixer->setParameter(
5146 trackId,
5147 AudioMixer::TRACK,
5148 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005149 mAudioMixer->setParameter(
5150 trackId,
5151 AudioMixer::TRACK,
5152 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005153
5154 // reset retry count
5155 track->mRetryCount = kMaxTrackRetries;
5156
5157 // If one track is ready, set the mixer ready if:
5158 // - the mixer was not ready during previous round OR
5159 // - no other track is not ready
5160 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5161 mixerStatus != MIXER_TRACKS_ENABLED) {
5162 mixerStatus = MIXER_TRACKS_READY;
5163 }
5164 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005165 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005166 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07005167 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
5168 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005169 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005170 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005171 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005172
Eric Laurent81784c32012-11-19 14:55:58 -08005173 // clear effect chain input buffer if an active track underruns to avoid sending
5174 // previous audio buffer again to effects
5175 chain = getEffectChain_l(track->sessionId());
5176 if (chain != 0) {
5177 chain->clearInputBuffer();
5178 }
5179
Andy Hungc0691382018-09-12 18:01:57 -07005180 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005181 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5182 track->isStopped() || track->isPaused()) {
5183 // We have consumed all the buffers of this track.
5184 // Remove it from the list of active tracks.
5185 // TODO: use actual buffer filling status instead of latency when available from
5186 // audio HAL
5187 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005188 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005189 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5190 if (track->isStopped()) {
5191 track->reset();
5192 }
5193 tracksToRemove->add(track);
5194 }
5195 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005196 // No buffers for this track. Give it a few chances to
5197 // fill a buffer, then remove it from active list.
5198 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005199 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5200 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005201 tracksToRemove->add(track);
5202 // indicate to client process that the track was disabled because of underrun;
5203 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005204 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005205 // If one track is not ready, mark the mixer also not ready if:
5206 // - the mixer was ready during previous round OR
5207 // - no other track is ready
5208 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5209 mixerStatus != MIXER_TRACKS_READY) {
5210 mixerStatus = MIXER_TRACKS_ENABLED;
5211 }
5212 }
Andy Hungc0691382018-09-12 18:01:57 -07005213 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005214 }
5215
5216 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005217
5218 }
5219
jiabin245cdd92018-12-07 17:55:15 -08005220 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5221 // When there is no fast track playing haptic and FastMixer exists,
5222 // enabling the first FastTrack, which provides mixed data from normal
5223 // tracks, to play haptic data.
5224 FastTrack *fastTrack = &state->mFastTracks[0];
5225 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5226 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5227 didModify = true;
5228 }
5229 }
5230
Eric Laurent81784c32012-11-19 14:55:58 -08005231 // Push the new FastMixer state if necessary
5232 bool pauseAudioWatchdog = false;
5233 if (didModify) {
5234 state->mFastTracksGen++;
5235 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5236 if (kUseFastMixer == FastMixer_Dynamic &&
5237 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5238 state->mCommand = FastMixerState::COLD_IDLE;
5239 state->mColdFutexAddr = &mFastMixerFutex;
5240 state->mColdGen++;
5241 mFastMixerFutex = 0;
5242 if (kUseFastMixer == FastMixer_Dynamic) {
5243 mNormalSink = mOutputSink;
5244 }
5245 // If we go into cold idle, need to wait for acknowledgement
5246 // so that fast mixer stops doing I/O.
5247 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5248 pauseAudioWatchdog = true;
5249 }
Eric Laurent81784c32012-11-19 14:55:58 -08005250 }
5251 if (sq != NULL) {
5252 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005253 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5254 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5255 // when bringing the output sink into standby.)
5256 //
5257 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5258 //
5259 // This occurs with BT suspend when we idle the FastMixer with
5260 // active tracks, which may be added or removed.
5261 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005262 }
5263#ifdef AUDIO_WATCHDOG
5264 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5265 mAudioWatchdog->pause();
5266 }
5267#endif
5268
5269 // Now perform the deferred reset on fast tracks that have stopped
5270 while (resetMask != 0) {
5271 size_t i = __builtin_ctz(resetMask);
5272 ALOG_ASSERT(i < count);
5273 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005274 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005275 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5276 track->reset();
5277 }
5278
Andy Hung80d03d22018-04-10 10:32:11 -07005279 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5280 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5281 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5282 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5283 // See also the implementation of destroyTrack_l().
5284 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005285 const int trackId = track->id();
5286 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5287 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005288 }
5289 }
5290
Eric Laurent81784c32012-11-19 14:55:58 -08005291 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005292 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005293
Eric Laurent97d547d2014-09-02 14:45:53 -07005294 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5295 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005296 }
5297
5298 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005299 // as long as there are effects we should clear the effects buffer, to avoid
5300 // passing a non-clean buffer to the effect chain
5301 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005302 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005303 // sink or mix buffer must be cleared if all tracks are connected to an
5304 // effect chain as in this case the mixer will not write to the sink or mix buffer
5305 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5307 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005308 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005309 if (mMixerBufferValid) {
5310 memset(mMixerBuffer, 0, mMixerBufferSize);
5311 // TODO: In testing, mSinkBuffer below need not be cleared because
5312 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5313 // after mixing.
5314 //
5315 // To enforce this guarantee:
5316 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5317 // (mixedTracks == 0 && fastTracks > 0))
5318 // must imply MIXER_TRACKS_READY.
5319 // Later, we may clear buffers regardless, and skip much of this logic.
5320 }
Andy Hung98ef9782014-03-04 14:46:50 -08005321 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005322 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005323 }
5324
5325 // if any fast tracks, then status is ready
5326 mMixerStatusIgnoringFastTracks = mixerStatus;
5327 if (fastTracks > 0) {
5328 mixerStatus = MIXER_TRACKS_READY;
5329 }
5330 return mixerStatus;
5331}
5332
Eric Laurentad7dd962016-09-22 12:38:37 -07005333// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005334uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005335{
5336 uint32_t trackCount = 0;
5337 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005338 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005339 trackCount++;
5340 }
5341 }
5342 return trackCount;
5343}
5344
Andy Hung1bc088a2018-02-09 15:57:31 -08005345// isTrackAllowed_l() must be called with ThreadBase::mLock held
5346bool AudioFlinger::MixerThread::isTrackAllowed_l(
5347 audio_channel_mask_t channelMask, audio_format_t format,
5348 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005349{
Andy Hung1bc088a2018-02-09 15:57:31 -08005350 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5351 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005352 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005353 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005354 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005355 ALOGW("%s: invalid format: %#x", __func__, format);
5356 return false;
5357 }
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005358 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005359 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5360 return false;
5361 }
5362 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005363}
5364
Eric Laurent10351942014-05-08 18:49:52 -07005365// checkForNewParameter_l() must be called with ThreadBase::mLock held
5366bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5367 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005368{
Eric Laurent81784c32012-11-19 14:55:58 -08005369 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005370 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005371
Eric Laurent10351942014-05-08 18:49:52 -07005372 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005373
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005374 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005375
Eric Laurent10351942014-05-08 18:49:52 -07005376 AudioParameter param = AudioParameter(keyValuePair);
5377 int value;
5378 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5379 reconfig = true;
5380 }
5381 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005382 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005383 status = BAD_VALUE;
5384 } else {
5385 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005386 reconfig = true;
5387 }
Eric Laurent10351942014-05-08 18:49:52 -07005388 }
5389 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005390 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005391 status = BAD_VALUE;
5392 } else {
5393 // no need to save value, since it's constant
5394 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005395 }
Eric Laurent10351942014-05-08 18:49:52 -07005396 }
5397 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5398 // do not accept frame count changes if tracks are open as the track buffer
5399 // size depends on frame count and correct behavior would not be guaranteed
5400 // if frame count is changed after track creation
5401 if (!mTracks.isEmpty()) {
5402 status = INVALID_OPERATION;
5403 } else {
5404 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005405 }
Eric Laurent10351942014-05-08 18:49:52 -07005406 }
5407 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07005408 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005409 }
Eric Laurent81784c32012-11-19 14:55:58 -08005410
Eric Laurent10351942014-05-08 18:49:52 -07005411 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005412 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005413 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005414 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005415 mStandby = true;
5416 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005417 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005418 }
Eric Laurent10351942014-05-08 18:49:52 -07005419 if (status == NO_ERROR && reconfig) {
5420 readOutputParameters_l();
5421 delete mAudioMixer;
5422 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005423 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005424 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005425 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005426 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005427 track->mChannelMask,
5428 track->mFormat,
5429 track->mSessionId);
5430 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005431 "%s(): AudioMixer cannot create track(%d)"
5432 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005433 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005434 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005435 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005436 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005437 }
Eric Laurent81784c32012-11-19 14:55:58 -08005438 }
5439
Eric Laurent42537be2016-01-08 17:16:42 -08005440 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005441}
5442
5443
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005444void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005445{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005446 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005447 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005448 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005449 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005450 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5451 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5452 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005453 if (hasFastMixer()) {
5454 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5455
5456 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5457 // while we are dumping it. It may be inconsistent, but it won't mutate!
5458 // This is a large object so we place it on the heap.
5459 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005460 const std::unique_ptr<FastMixerDumpState> copy =
5461 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005462 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005463
5464#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005465 // Similar for state queue
5466 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5467 observerCopy.dump(fd);
5468 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5469 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005470#endif
5471
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005472#ifdef AUDIO_WATCHDOG
5473 if (mAudioWatchdog != 0) {
5474 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5475 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5476 wdCopy.dump(fd);
5477 }
5478#endif
5479
5480 } else {
5481 dprintf(fd, " No FastMixer\n");
5482 }
Eric Laurent81784c32012-11-19 14:55:58 -08005483}
5484
5485uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5486{
5487 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5488}
5489
5490uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5491{
5492 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5493}
5494
5495void AudioFlinger::MixerThread::cacheParameters_l()
5496{
5497 PlaybackThread::cacheParameters_l();
5498
5499 // FIXME: Relaxed timing because of a certain device that can't meet latency
5500 // Should be reduced to 2x after the vendor fixes the driver issue
5501 // increase threshold again due to low power audio mode. The way this warning
5502 // threshold is calculated and its usefulness should be reconsidered anyway.
5503 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5504}
5505
5506// ----------------------------------------------------------------------------
5507
5508AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07005509 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5510 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005511{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005512 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005513}
5514
Eric Laurent81784c32012-11-19 14:55:58 -08005515AudioFlinger::DirectOutputThread::~DirectOutputThread()
5516{
5517}
5518
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005519void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005520{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005521 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005522 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5523 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5524}
5525
5526void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5527{
5528 Mutex::Autolock _l(mLock);
5529 if (mMasterBalance != balance) {
5530 mMasterBalance.store(balance);
5531 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5532 broadcast_l();
5533 }
5534}
5535
Eric Laurent5850c4c2016-11-10 13:04:31 -08005536void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005537{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005538 float left, right;
5539
Andy Hung333ab962019-05-28 20:23:35 -07005540 // Ensure volumeshaper state always advances even when muted.
5541 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5542 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5543 proxy->framesReleased());
5544 mVolumeShaperActive = shaperActive;
5545
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005546 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005547 left = right = 0;
5548 } else {
5549 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005550 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005551
Glenn Kastenc56f3422014-03-21 17:53:17 -07005552 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5553 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5554 if (left > GAIN_FLOAT_UNITY) {
5555 left = GAIN_FLOAT_UNITY;
5556 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005557 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005558 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5559 if (right > GAIN_FLOAT_UNITY) {
5560 right = GAIN_FLOAT_UNITY;
5561 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005562 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005563 }
5564
5565 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005566 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567 if (left != mLeftVolFloat || right != mRightVolFloat) {
5568 mLeftVolFloat = left;
5569 mRightVolFloat = right;
5570
Eric Laurentbfb1b832013-01-07 09:53:42 -08005571 // Delegate volume control to effect in track effect chain if needed
5572 // only one effect chain can be present on DirectOutputThread, so if
5573 // there is one, the track is connected to it
5574 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005575 // if effect chain exists, volume is handled by it.
5576 // Convert volumes from float to 8.24
5577 uint32_t vl = (uint32_t)(left * (1 << 24));
5578 uint32_t vr = (uint32_t)(right * (1 << 24));
5579 // Direct/Offload effect chains set output volume in setVolume_l().
5580 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5581 } else {
5582 // otherwise we directly set the volume.
5583 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005584 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005585 }
5586 }
5587}
5588
Phil Burk43b4dcc2015-06-09 16:53:44 -07005589void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5590{
5591 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005592 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005593
Eric Laurent0f0631e2015-07-06 18:01:25 -07005594 if (previousTrack != 0 && latestTrack != 0) {
5595 if (mType == DIRECT) {
5596 if (previousTrack.get() != latestTrack.get()) {
5597 mFlushPending = true;
5598 }
5599 } else /* mType == OFFLOAD */ {
5600 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5601 mFlushPending = true;
5602 }
5603 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005604 } else if (previousTrack == 0) {
5605 // there could be an old track added back during track transition for direct
5606 // output, so always issues flush to flush data of the previous track if it
5607 // was already destroyed with HAL paused, then flush can resume the playback
5608 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005609 }
5610 PlaybackThread::onAddNewTrack_l();
5611}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005612
Eric Laurent81784c32012-11-19 14:55:58 -08005613AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5614 Vector< sp<Track> > *tracksToRemove
5615)
5616{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005617 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005618 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005619 bool doHwPause = false;
5620 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005621
5622 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005623 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005624 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005625 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005626 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005627 continue;
5628 }
5629
Eric Laurent5850c4c2016-11-10 13:04:31 -08005630 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005631#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005632 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005633#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005634 // Only consider last track started for volume and mixer state control.
5635 // In theory an older track could underrun and restart after the new one starts
5636 // but as we only care about the transition phase between two tracks on a
5637 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005638 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005639 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005640
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005641 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005642 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005643 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005644 doHwPause = true;
5645 mHwPaused = true;
5646 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005647 } else if (track->isFlushPending()) {
5648 track->flushAck();
5649 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005650 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005651 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005652 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005653 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005654 if (last) {
5655 mLeftVolFloat = mRightVolFloat = -1.0;
5656 if (mHwPaused) {
5657 doHwResume = true;
5658 mHwPaused = false;
5659 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005660 }
5661 }
5662
Eric Laurent81784c32012-11-19 14:55:58 -08005663 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005664 // for all its buffers to be filled before processing it.
5665 // Allow draining the buffer in case the client
5666 // app does not call stop() and relies on underrun to stop:
5667 // hence the test on (track->mRetryCount > 1).
5668 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005669 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005670 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005671 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005672 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005673 minFrames = mNormalFrameCount;
5674 } else {
5675 minFrames = 1;
5676 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005677
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005678 const size_t framesReady = track->framesReady();
5679 const int trackId = track->id();
5680 if (ATRACE_ENABLED()) {
5681 std::string traceName("nRdy");
5682 traceName += std::to_string(trackId);
5683 ATRACE_INT(traceName.c_str(), framesReady);
5684 }
5685 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005686 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005687 {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005688 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005689
5690 if (track->mFillingUpStatus == Track::FS_FILLED) {
5691 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005692 if (last) {
5693 // make sure processVolume_l() will apply new volume even if 0
5694 mLeftVolFloat = mRightVolFloat = -1.0;
5695 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005696 if (!mHwSupportsPause) {
5697 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005698 }
5699 }
5700
5701 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005702 processVolume_l(track, last);
5703 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005704 sp<Track> previousTrack = mPreviousTrack.promote();
5705 if (previousTrack != 0) {
5706 if (track != previousTrack.get()) {
5707 // Flush any data still being written from last track
5708 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005709 // Invalidate previous track to force a seek when resuming.
5710 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005711 }
5712 }
5713 mPreviousTrack = track;
5714
Eric Laurentd595b7c2013-04-03 17:27:56 -07005715 // reset retry count
5716 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005717 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005718 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005719 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005720 doHwResume = true;
5721 mHwPaused = false;
5722 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005723 }
Eric Laurent81784c32012-11-19 14:55:58 -08005724 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005725 // clear effect chain input buffer if the last active track started underruns
5726 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005727 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005728 mEffectChains[0]->clearInputBuffer();
5729 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005730 if (track->isStopping_1()) {
5731 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005732 if (last && mHwPaused) {
5733 doHwResume = true;
5734 mHwPaused = false;
5735 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005736 }
5737 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5738 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005739 // We have consumed all the buffers of this track.
5740 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005741 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005742 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005743 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5744 } else {
5745 audioHALFrames = 0;
5746 }
5747
Andy Hung818e7a32016-02-16 18:08:07 -08005748 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005749 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005750 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005751 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005752 if (track->isStopping_2()) {
5753 track->mState = TrackBase::STOPPED;
5754 }
Eric Laurent81784c32012-11-19 14:55:58 -08005755 if (track->isStopped()) {
5756 track->reset();
5757 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005758 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005759 }
5760 } else {
5761 // No buffers for this track. Give it a few chances to
5762 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005763 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005764 if (--(track->mRetryCount) <= 0) {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005765 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005766 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005767 // indicate to client process that the track was disabled because of underrun;
5768 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005769 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005770 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005771 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5772 "minFrames = %u, mFormat = %#x",
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005773 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005774 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005775 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005776 doHwPause = true;
5777 mHwPaused = true;
5778 }
Eric Laurent81784c32012-11-19 14:55:58 -08005779 }
5780 }
5781 }
5782 }
5783
Eric Laurentd1f69b02014-12-15 14:33:13 -08005784 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005785 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005786 for (size_t i = 0; i < mTracks.size(); i++) {
5787 if (mTracks[i]->isFlushPending()) {
5788 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005789 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005790 }
5791 }
5792 }
5793
5794 // make sure the pause/flush/resume sequence is executed in the right order.
5795 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5796 // before flush and then resume HW. This can happen in case of pause/flush/resume
5797 // if resume is received before pause is executed.
5798 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005799 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005800 status_t result = mOutput->stream->pause();
5801 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005802 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005803 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005804 flushHw_l();
5805 }
5806 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005807 status_t result = mOutput->stream->resume();
5808 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005809 }
Eric Laurent81784c32012-11-19 14:55:58 -08005810 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005811 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005812
5813 return mixerStatus;
5814}
5815
5816void AudioFlinger::DirectOutputThread::threadLoop_mix()
5817{
Eric Laurent81784c32012-11-19 14:55:58 -08005818 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005819 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005820 // output audio to hardware
5821 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005822 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005823 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005824 status_t status = mActiveTrack->getNextBuffer(&buffer);
5825 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005826 // no need to pad with 0 for compressed audio
5827 if (audio_has_proportional_frames(mFormat)) {
5828 memset(curBuf, 0, frameCount * mFrameSize);
5829 }
Eric Laurent81784c32012-11-19 14:55:58 -08005830 break;
5831 }
5832 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5833 frameCount -= buffer.frameCount;
5834 curBuf += buffer.frameCount * mFrameSize;
5835 mActiveTrack->releaseBuffer(&buffer);
5836 }
Andy Hung2098f272014-02-27 14:00:06 -08005837 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005838 mSleepTimeUs = 0;
5839 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005840 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005841}
5842
5843void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5844{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005845 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005846 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005847 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005848 return;
5849 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005850 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005851 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005852 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005853 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005854 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005855 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005856 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005857 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005858 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005859 }
5860}
5861
Eric Laurentd1f69b02014-12-15 14:33:13 -08005862void AudioFlinger::DirectOutputThread::threadLoop_exit()
5863{
5864 {
5865 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005866 for (size_t i = 0; i < mTracks.size(); i++) {
5867 if (mTracks[i]->isFlushPending()) {
5868 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005869 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005870 }
5871 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005872 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005873 flushHw_l();
5874 }
5875 }
5876 PlaybackThread::threadLoop_exit();
5877}
5878
5879// must be called with thread mutex locked
5880bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5881{
5882 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005883 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005884
vivek mehta9cd7ad12016-03-17 00:18:29 -07005885 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5886 return !mStandby;
5887 }
5888
Eric Laurentd1f69b02014-12-15 14:33:13 -08005889 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5890 // after a timeout and we will enter standby then.
5891 if (mTracks.size() > 0) {
5892 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005893 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5894 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005895 }
5896
Eric Laurent5cff4032015-05-26 13:49:58 -07005897 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005898}
5899
Eric Laurent10351942014-05-08 18:49:52 -07005900// checkForNewParameter_l() must be called with ThreadBase::mLock held
5901bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5902 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005903{
5904 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005905 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005906
Eric Laurent10351942014-05-08 18:49:52 -07005907 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005908
Eric Laurent10351942014-05-08 18:49:52 -07005909 AudioParameter param = AudioParameter(keyValuePair);
5910 int value;
5911 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07005912 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08005913 }
Eric Laurent10351942014-05-08 18:49:52 -07005914 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5915 // do not accept frame count changes if tracks are open as the track buffer
5916 // size depends on frame count and correct behavior would not be garantied
5917 // if frame count is changed after track creation
5918 if (!mTracks.isEmpty()) {
5919 status = INVALID_OPERATION;
5920 } else {
5921 reconfig = true;
5922 }
5923 }
5924 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005925 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005926 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005927 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005928 mStandby = true;
5929 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005930 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005931 }
5932 if (status == NO_ERROR && reconfig) {
5933 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005934 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005935 }
5936 }
5937
Eric Laurent42537be2016-01-08 17:16:42 -08005938 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005939}
5940
5941uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5942{
5943 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005944 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005945 time = PlaybackThread::activeSleepTimeUs();
5946 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005947 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005948 }
5949 return time;
5950}
5951
5952uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5953{
5954 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005955 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005956 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5957 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005958 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005959 }
5960 return time;
5961}
5962
5963uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5964{
5965 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005966 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005967 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5968 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005969 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005970 }
5971 return time;
5972}
5973
5974void AudioFlinger::DirectOutputThread::cacheParameters_l()
5975{
5976 PlaybackThread::cacheParameters_l();
5977
5978 // use shorter standby delay as on normal output to release
5979 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005980 // no delay on outputs with HW A/V sync
5981 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005982 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005983 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005984 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005985 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005986 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005987 }
Eric Laurent81784c32012-11-19 14:55:58 -08005988}
5989
Eric Laurente659ef42014-09-29 13:06:46 -07005990void AudioFlinger::DirectOutputThread::flushHw_l()
5991{
Phil Burk062e67a2015-02-11 13:40:50 -08005992 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005993 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005994 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005995 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005996}
5997
Andy Hung10cbff12017-02-21 17:30:14 -08005998int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5999 // If a VolumeShaper is active, we must wake up periodically to update volume.
6000 const int64_t NS_PER_MS = 1000000;
6001 return mVolumeShaperActive ?
6002 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6003}
6004
Eric Laurent81784c32012-11-19 14:55:58 -08006005// ----------------------------------------------------------------------------
6006
Eric Laurentbfb1b832013-01-07 09:53:42 -08006007AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006008 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006009 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006010 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006011 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006012 mDrainSequence(0),
6013 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006014{
6015}
6016
6017AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6018{
6019}
6020
6021void AudioFlinger::AsyncCallbackThread::onFirstRef()
6022{
6023 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6024}
6025
6026bool AudioFlinger::AsyncCallbackThread::threadLoop()
6027{
6028 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006029 uint32_t writeAckSequence;
6030 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006031 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006032
6033 {
6034 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006035 while (!((mWriteAckSequence & 1) ||
6036 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006037 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006038 exitPending())) {
6039 mWaitWorkCV.wait(mLock);
6040 }
6041
Eric Laurentbfb1b832013-01-07 09:53:42 -08006042 if (exitPending()) {
6043 break;
6044 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006045 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6046 mWriteAckSequence, mDrainSequence);
6047 writeAckSequence = mWriteAckSequence;
6048 mWriteAckSequence &= ~1;
6049 drainSequence = mDrainSequence;
6050 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006051 asyncError = mAsyncError;
6052 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006053 }
6054 {
Eric Laurent4de95592013-09-26 15:28:21 -07006055 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6056 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006057 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006058 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006059 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006060 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006061 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006062 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006063 if (asyncError) {
6064 playbackThread->onAsyncError();
6065 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006066 }
6067 }
6068 }
6069 return false;
6070}
6071
6072void AudioFlinger::AsyncCallbackThread::exit()
6073{
6074 ALOGV("AsyncCallbackThread::exit");
6075 Mutex::Autolock _l(mLock);
6076 requestExit();
6077 mWaitWorkCV.broadcast();
6078}
6079
Eric Laurent3b4529e2013-09-05 18:09:19 -07006080void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006081{
6082 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006083 // bit 0 is cleared
6084 mWriteAckSequence = sequence << 1;
6085}
6086
6087void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6088{
6089 Mutex::Autolock _l(mLock);
6090 // ignore unexpected callbacks
6091 if (mWriteAckSequence & 2) {
6092 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006093 mWaitWorkCV.signal();
6094 }
6095}
6096
Eric Laurent3b4529e2013-09-05 18:09:19 -07006097void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006098{
6099 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006100 // bit 0 is cleared
6101 mDrainSequence = sequence << 1;
6102}
6103
6104void AudioFlinger::AsyncCallbackThread::resetDraining()
6105{
6106 Mutex::Autolock _l(mLock);
6107 // ignore unexpected callbacks
6108 if (mDrainSequence & 2) {
6109 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006110 mWaitWorkCV.signal();
6111 }
6112}
6113
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006114void AudioFlinger::AsyncCallbackThread::setAsyncError()
6115{
6116 Mutex::Autolock _l(mLock);
6117 mAsyncError = true;
6118 mWaitWorkCV.signal();
6119}
6120
Eric Laurentbfb1b832013-01-07 09:53:42 -08006121
6122// ----------------------------------------------------------------------------
6123AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07006124 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6125 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006126 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6127 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006128{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006129 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006130 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006131 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006132}
6133
Eric Laurentbfb1b832013-01-07 09:53:42 -08006134void AudioFlinger::OffloadThread::threadLoop_exit()
6135{
6136 if (mFlushPending || mHwPaused) {
6137 // If a flush is pending or track was paused, just discard buffered data
6138 flushHw_l();
6139 } else {
6140 mMixerStatus = MIXER_DRAIN_ALL;
6141 threadLoop_drain();
6142 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006143 if (mUseAsyncWrite) {
6144 ALOG_ASSERT(mCallbackThread != 0);
6145 mCallbackThread->exit();
6146 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006147 PlaybackThread::threadLoop_exit();
6148}
6149
6150AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6151 Vector< sp<Track> > *tracksToRemove
6152)
6153{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006154 size_t count = mActiveTracks.size();
6155
6156 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006157 bool doHwPause = false;
6158 bool doHwResume = false;
6159
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006160 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006161
Eric Laurentbfb1b832013-01-07 09:53:42 -08006162 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006163 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006164 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006165#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006166 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006167#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006168 // Only consider last track started for volume and mixer state control.
6169 // In theory an older track could underrun and restart after the new one starts
6170 // but as we only care about the transition phase between two tracks on a
6171 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006172 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006173 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006174
Haynes Mathew George7844f672014-01-15 12:32:55 -08006175 if (track->isInvalid()) {
6176 ALOGW("An invalidated track shouldn't be in active list");
6177 tracksToRemove->add(track);
6178 continue;
6179 }
6180
6181 if (track->mState == TrackBase::IDLE) {
6182 ALOGW("An idle track shouldn't be in active list");
6183 continue;
6184 }
6185
Eric Laurentbfb1b832013-01-07 09:53:42 -08006186 if (track->isPausing()) {
6187 track->setPaused();
6188 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006189 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006190 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006191 mHwPaused = true;
6192 }
6193 // If we were part way through writing the mixbuffer to
6194 // the HAL we must save this until we resume
6195 // BUG - this will be wrong if a different track is made active,
6196 // in that case we want to discard the pending data in the
6197 // mixbuffer and tell the client to present it again when the
6198 // track is resumed
6199 mPausedWriteLength = mCurrentWriteLength;
6200 mPausedBytesRemaining = mBytesRemaining;
6201 mBytesRemaining = 0; // stop writing
6202 }
6203 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006204 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006205 if (track->isStopping_1()) {
6206 track->mRetryCount = kMaxTrackStopRetriesOffload;
6207 } else {
6208 track->mRetryCount = kMaxTrackRetriesOffload;
6209 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006210 track->flushAck();
6211 if (last) {
6212 mFlushPending = true;
6213 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006214 } else if (track->isResumePending()){
6215 track->resumeAck();
6216 if (last) {
6217 if (mPausedBytesRemaining) {
6218 // Need to continue write that was interrupted
6219 mCurrentWriteLength = mPausedWriteLength;
6220 mBytesRemaining = mPausedBytesRemaining;
6221 mPausedBytesRemaining = 0;
6222 }
6223 if (mHwPaused) {
6224 doHwResume = true;
6225 mHwPaused = false;
6226 // threadLoop_mix() will handle the case that we need to
6227 // resume an interrupted write
6228 }
6229 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006230 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006231
Eric Laurent3df841a2016-07-15 15:15:40 -07006232 mLeftVolFloat = mRightVolFloat = -1.0;
6233
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006234 // Do not handle new data in this iteration even if track->framesReady()
6235 mixerStatus = MIXER_TRACKS_ENABLED;
6236 }
6237 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006238 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006239 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006240 if (track->mFillingUpStatus == Track::FS_FILLED) {
6241 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006242 if (last) {
6243 // make sure processVolume_l() will apply new volume even if 0
6244 mLeftVolFloat = mRightVolFloat = -1.0;
6245 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006246 }
6247
6248 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006249 sp<Track> previousTrack = mPreviousTrack.promote();
6250 if (previousTrack != 0) {
6251 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006252 // Flush any data still being written from last track
6253 mBytesRemaining = 0;
6254 if (mPausedBytesRemaining) {
6255 // Last track was paused so we also need to flush saved
6256 // mixbuffer state and invalidate track so that it will
6257 // re-submit that unwritten data when it is next resumed
6258 mPausedBytesRemaining = 0;
6259 // Invalidate is a bit drastic - would be more efficient
6260 // to have a flag to tell client that some of the
6261 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006262 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006263 }
6264 // flush data already sent to the DSP if changing audio session as audio
6265 // comes from a different source. Also invalidate previous track to force a
6266 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006267 if (previousTrack->sessionId() != track->sessionId()) {
6268 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006269 }
6270 }
6271 }
6272 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006273 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006274 if (track->isStopping_1()) {
6275 track->mRetryCount = kMaxTrackStopRetriesOffload;
6276 } else {
6277 track->mRetryCount = kMaxTrackRetriesOffload;
6278 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006279 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006280 mixerStatus = MIXER_TRACKS_READY;
6281 }
6282 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006283 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006284 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006285 if (--(track->mRetryCount) <= 0) {
6286 // Hardware buffer can hold a large amount of audio so we must
6287 // wait for all current track's data to drain before we say
6288 // that the track is stopped.
6289 if (mBytesRemaining == 0) {
6290 // Only start draining when all data in mixbuffer
6291 // has been written
6292 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6293 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6294 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6295 if (last && !mStandby) {
6296 // do not modify drain sequence if we are already draining. This happens
6297 // when resuming from pause after drain.
6298 if ((mDrainSequence & 1) == 0) {
6299 mSleepTimeUs = 0;
6300 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6301 mixerStatus = MIXER_DRAIN_TRACK;
6302 mDrainSequence += 2;
6303 }
6304 if (mHwPaused) {
6305 // It is possible to move from PAUSED to STOPPING_1 without
6306 // a resume so we must ensure hardware is running
6307 doHwResume = true;
6308 mHwPaused = false;
6309 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006310 }
6311 }
Eric Laurente93cc032016-05-05 10:15:10 -07006312 } else if (last) {
6313 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6314 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006315 }
6316 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006317 // Drain has completed or we are in standby, signal presentation complete
6318 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006319 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006320 uint32_t latency = 0;
6321 status_t result = mOutput->stream->getLatency(&latency);
6322 ALOGE_IF(result != OK,
6323 "Error when retrieving output stream latency: %d", result);
6324 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006325 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006326 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006327 track->presentationComplete(framesWritten, audioHALFrames);
6328 track->reset();
6329 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006330 // DIRECT and OFFLOADED stop resets frame counts.
6331 if (!mUseAsyncWrite) {
6332 // If we don't get explicit drain notification we must
6333 // register discontinuity regardless of whether this is
6334 // the previous (!last) or the upcoming (last) track
6335 // to avoid skipping the discontinuity.
6336 mTimestampVerifier.discontinuity();
6337 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006338 }
6339 } else {
6340 // No buffers for this track. Give it a few chances to
6341 // fill a buffer, then remove it from active list.
6342 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006343 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006344 uint64_t position = 0;
6345 struct timespec unused;
6346 // The running check restarts the retry counter at least once.
6347 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6348 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6349 running = true;
6350 mOffloadUnderrunPosition = position;
6351 }
6352 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006353 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6354 (long long)position, (long long)mOffloadUnderrunPosition);
6355 }
6356 if (running) { // still running, give us more time.
6357 track->mRetryCount = kMaxTrackRetriesOffload;
6358 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006359 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6360 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006361 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006362 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006363 // it will then automatically call start() when data is available
6364 track->disable();
6365 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006366 } else if (last){
6367 mixerStatus = MIXER_TRACKS_ENABLED;
6368 }
6369 }
6370 }
6371 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006372 if (track->isReady()) { // check ready to prevent premature start.
6373 processVolume_l(track, last);
6374 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006375 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006376
Eric Laurentea0fade2013-10-04 16:23:48 -07006377 // make sure the pause/flush/resume sequence is executed in the right order.
6378 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6379 // before flush and then resume HW. This can happen in case of pause/flush/resume
6380 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006381 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006382 status_t result = mOutput->stream->pause();
6383 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006384 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006385 if (mFlushPending) {
6386 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006387 }
Eric Laurentfd477972013-10-25 18:10:40 -07006388 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006389 status_t result = mOutput->stream->resume();
6390 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006391 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006392
Eric Laurentbfb1b832013-01-07 09:53:42 -08006393 // remove all the tracks that need to be...
6394 removeTracks_l(*tracksToRemove);
6395
6396 return mixerStatus;
6397}
6398
Eric Laurentbfb1b832013-01-07 09:53:42 -08006399// must be called with thread mutex locked
6400bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6401{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006402 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6403 mWriteAckSequence, mDrainSequence);
6404 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006405 return true;
6406 }
6407 return false;
6408}
6409
Eric Laurentbfb1b832013-01-07 09:53:42 -08006410bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6411{
6412 Mutex::Autolock _l(mLock);
6413 return waitingAsyncCallback_l();
6414}
6415
6416void AudioFlinger::OffloadThread::flushHw_l()
6417{
Eric Laurente659ef42014-09-29 13:06:46 -07006418 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006419 // Flush anything still waiting in the mixbuffer
6420 mCurrentWriteLength = 0;
6421 mBytesRemaining = 0;
6422 mPausedWriteLength = 0;
6423 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006424 // reset bytes written count to reflect that DSP buffers are empty after flush.
6425 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006426 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006427
Eric Laurentbfb1b832013-01-07 09:53:42 -08006428 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006429 // discard any pending drain or write ack by incrementing sequence
6430 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6431 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006432 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006433 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6434 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006435 }
6436}
6437
Haynes Mathew George05317d22016-05-03 16:34:26 -07006438void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6439{
6440 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006441 if (PlaybackThread::invalidateTracks_l(streamType)) {
6442 mFlushPending = true;
6443 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006444}
6445
Eric Laurentbfb1b832013-01-07 09:53:42 -08006446// ----------------------------------------------------------------------------
6447
Eric Laurent81784c32012-11-19 14:55:58 -08006448AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006449 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabin10d86fd2019-10-31 17:20:42 -07006450 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006451 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006452 mWaitTimeMs(UINT_MAX)
6453{
6454 addOutputTrack(mainThread);
6455}
6456
6457AudioFlinger::DuplicatingThread::~DuplicatingThread()
6458{
6459 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6460 mOutputTracks[i]->destroy();
6461 }
6462}
6463
6464void AudioFlinger::DuplicatingThread::threadLoop_mix()
6465{
6466 // mix buffers...
6467 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006468 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006469 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006470 if (mMixerBufferValid) {
6471 memset(mMixerBuffer, 0, mMixerBufferSize);
6472 } else {
6473 memset(mSinkBuffer, 0, mSinkBufferSize);
6474 }
Eric Laurent81784c32012-11-19 14:55:58 -08006475 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006476 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006477 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006478 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006479 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006480}
6481
6482void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6483{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006484 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006485 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006486 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006487 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006488 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006489 }
6490 } else if (mBytesWritten != 0) {
6491 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6492 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006493 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006494 } else {
6495 // flush remaining overflow buffers in output tracks
6496 writeFrames = 0;
6497 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006498 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006499 }
6500}
6501
Eric Laurentbfb1b832013-01-07 09:53:42 -08006502ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006503{
6504 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006505 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6506
6507 // Consider the first OutputTrack for timestamp and frame counting.
6508
6509 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6510 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6511 // we always claim success.
6512 if (i == 0) {
6513 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6514 ALOGD_IF(correction != 0 && writeFrames != 0,
6515 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6516 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6517 mFramesWritten -= correction;
6518 }
6519
6520 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006521 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006522 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006523 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006524}
6525
6526void AudioFlinger::DuplicatingThread::threadLoop_standby()
6527{
6528 // DuplicatingThread implements standby by stopping all tracks
6529 for (size_t i = 0; i < outputTracks.size(); i++) {
6530 outputTracks[i]->stop();
6531 }
6532}
6533
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006534void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006535{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006536 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006537
6538 std::stringstream ss;
6539 const size_t numTracks = mOutputTracks.size();
6540 ss << " " << numTracks << " OutputTracks";
6541 if (numTracks > 0) {
6542 ss << ":";
6543 for (const auto &track : mOutputTracks) {
6544 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006545 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006546 if (thread.get() != nullptr) {
6547 ss << thread.get() << ", " << thread->id();
6548 } else {
6549 ss << "null";
6550 }
6551 ss << ")";
6552 }
6553 }
6554 ss << "\n";
6555 std::string result = ss.str();
6556 write(fd, result.c_str(), result.size());
6557}
6558
Eric Laurent81784c32012-11-19 14:55:58 -08006559void AudioFlinger::DuplicatingThread::saveOutputTracks()
6560{
6561 outputTracks = mOutputTracks;
6562}
6563
6564void AudioFlinger::DuplicatingThread::clearOutputTracks()
6565{
6566 outputTracks.clear();
6567}
6568
6569void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6570{
6571 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006572 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6573 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6574 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6575 const size_t frameCount =
6576 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6577 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6578 // from different OutputTracks and their associated MixerThreads (e.g. one may
6579 // nearly empty and the other may be dropping data).
6580
6581 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006582 this,
6583 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006584 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006585 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006586 frameCount,
6587 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006588 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6589 if (status != NO_ERROR) {
6590 ALOGE("addOutputTrack() initCheck failed %d", status);
6591 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006592 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006593 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6594 mOutputTracks.add(outputTrack);
6595 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6596 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006597}
6598
6599void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6600{
6601 Mutex::Autolock _l(mLock);
6602 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6603 if (mOutputTracks[i]->thread() == thread) {
6604 mOutputTracks[i]->destroy();
6605 mOutputTracks.removeAt(i);
6606 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006607 if (thread->getOutput() == mOutput) {
6608 mOutput = NULL;
6609 }
Eric Laurent81784c32012-11-19 14:55:58 -08006610 return;
6611 }
6612 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006613 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006614}
6615
6616// caller must hold mLock
6617void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6618{
6619 mWaitTimeMs = UINT_MAX;
6620 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6621 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6622 if (strong != 0) {
6623 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6624 if (waitTimeMs < mWaitTimeMs) {
6625 mWaitTimeMs = waitTimeMs;
6626 }
6627 }
6628 }
6629}
6630
6631
6632bool AudioFlinger::DuplicatingThread::outputsReady(
6633 const SortedVector< sp<OutputTrack> > &outputTracks)
6634{
6635 for (size_t i = 0; i < outputTracks.size(); i++) {
6636 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6637 if (thread == 0) {
6638 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6639 outputTracks[i].get());
6640 return false;
6641 }
6642 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6643 // see note at standby() declaration
6644 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6645 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6646 thread.get());
6647 return false;
6648 }
6649 }
6650 return true;
6651}
6652
Kevin Rocard12381092018-04-11 09:19:59 -07006653void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6654 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006655{
Kevin Rocard12381092018-04-11 09:19:59 -07006656 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6657 outputTrack->setMetadatas(metadata.tracks);
6658 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006659}
6660
Eric Laurent81784c32012-11-19 14:55:58 -08006661uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6662{
6663 return (mWaitTimeMs * 1000) / 2;
6664}
6665
6666void AudioFlinger::DuplicatingThread::cacheParameters_l()
6667{
6668 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6669 updateWaitTime_l();
6670
6671 MixerThread::cacheParameters_l();
6672}
6673
Eric Laurent6acd1d42017-01-04 14:23:29 -08006674
Eric Laurent81784c32012-11-19 14:55:58 -08006675// ----------------------------------------------------------------------------
6676// Record
6677// ----------------------------------------------------------------------------
6678
6679AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6680 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006681 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006682 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006683 ) :
jiabin10d86fd2019-10-31 17:20:42 -07006684 ThreadBase(audioFlinger, id, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006685 mInput(input),
Mikhail Naganovaf288872019-09-25 13:05:02 -07006686 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006687 mActiveTracks(&this->mLocalLog),
6688 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006689 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006690 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006691 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6692 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006693 // mFastCapture below
6694 , mFastCaptureFutex(0)
6695 // mInputSource
6696 // mPipeSink
6697 // mPipeSource
6698 , mPipeFramesP2(0)
6699 // mPipeMemory
6700 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006701 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006702 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006703{
Glenn Kastend7dca052015-03-05 16:05:54 -08006704 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6705 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006706
Andy Hungc8fddf32018-08-08 18:32:37 -07006707 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6708 mIsMsdDevice = strcmp(
6709 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6710 }
6711
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006712 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006713
Andy Hungc8fddf32018-08-08 18:32:37 -07006714 // TODO: We may also match on address as well as device type for
6715 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabin10d86fd2019-10-31 17:20:42 -07006716 // TODO: This property should be ensure that only contains one single device type.
6717 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6718 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006719 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6720 : AUDIO_DEVICE_NONE));
6721
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006722 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006723 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006724 size_t numCounterOffers = 0;
6725 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006726#if !LOG_NDEBUG
6727 ssize_t index =
6728#else
6729 (void)
6730#endif
6731 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006732 ALOG_ASSERT(index == 0);
6733
6734 // initialize fast capture depending on configuration
6735 bool initFastCapture;
6736 switch (kUseFastCapture) {
6737 case FastCapture_Never:
6738 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006739 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006740 break;
6741 case FastCapture_Always:
6742 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006743 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006744 break;
6745 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006746 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006747 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6748 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6749 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006750 break;
6751 // case FastCapture_Dynamic:
6752 }
6753
6754 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006755 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006756 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006757 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6758 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006759 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006760 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006761 const sp<MemoryDealer> roHeap(readOnlyHeap());
6762 sp<IMemory> pipeMemory;
6763 if ((roHeap == 0) ||
6764 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006765 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6766 ALOGE("not enough memory for pipe buffer size=%zu; "
6767 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6768 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6769 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006770 goto failed;
6771 }
6772 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6773 memset(pipeBuffer, 0, pipeSize);
6774 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6775 const NBAIO_Format offers[1] = {format};
6776 size_t numCounterOffers = 0;
6777 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6778 ALOG_ASSERT(index == 0);
6779 mPipeSink = pipe;
6780 PipeReader *pipeReader = new PipeReader(*pipe);
6781 numCounterOffers = 0;
6782 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6783 ALOG_ASSERT(index == 0);
6784 mPipeSource = pipeReader;
6785 mPipeFramesP2 = pipeFramesP2;
6786 mPipeMemory = pipeMemory;
6787
6788 // create fast capture
6789 mFastCapture = new FastCapture();
6790 FastCaptureStateQueue *sq = mFastCapture->sq();
6791#ifdef STATE_QUEUE_DUMP
6792 // FIXME
6793#endif
6794 FastCaptureState *state = sq->begin();
6795 state->mCblk = NULL;
6796 state->mInputSource = mInputSource.get();
6797 state->mInputSourceGen++;
6798 state->mPipeSink = pipe;
6799 state->mPipeSinkGen++;
6800 state->mFrameCount = mFrameCount;
6801 state->mCommand = FastCaptureState::COLD_IDLE;
6802 // already done in constructor initialization list
6803 //mFastCaptureFutex = 0;
6804 state->mColdFutexAddr = &mFastCaptureFutex;
6805 state->mColdGen++;
6806 state->mDumpState = &mFastCaptureDumpState;
6807#ifdef TEE_SINK
6808 // FIXME
6809#endif
6810 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6811 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6812 sq->end();
6813 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6814
6815 // start the fast capture
6816 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6817 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006818 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006819 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006820#ifdef AUDIO_WATCHDOG
6821 // FIXME
6822#endif
6823
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006824 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006825 }
Andy Hung8946a282018-04-19 20:04:56 -07006826#ifdef TEE_SINK
6827 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6828 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6829#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006830failed: ;
6831
6832 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006833}
6834
Eric Laurent81784c32012-11-19 14:55:58 -08006835AudioFlinger::RecordThread::~RecordThread()
6836{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006837 if (mFastCapture != 0) {
6838 FastCaptureStateQueue *sq = mFastCapture->sq();
6839 FastCaptureState *state = sq->begin();
6840 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6841 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6842 if (old == -1) {
6843 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6844 }
6845 }
6846 state->mCommand = FastCaptureState::EXIT;
6847 sq->end();
6848 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6849 mFastCapture->join();
6850 mFastCapture.clear();
6851 }
6852 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006853 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006854 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006855}
6856
6857void AudioFlinger::RecordThread::onFirstRef()
6858{
Glenn Kastend7dca052015-03-05 16:05:54 -08006859 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006860}
6861
Eric Laurent555530a2017-02-07 18:17:24 -08006862void AudioFlinger::RecordThread::preExit()
6863{
6864 ALOGV(" preExit()");
6865 Mutex::Autolock _l(mLock);
6866 for (size_t i = 0; i < mTracks.size(); i++) {
6867 sp<RecordTrack> track = mTracks[i];
6868 track->invalidate();
6869 }
6870 mActiveTracks.clear();
6871 mStartStopCond.broadcast();
6872}
6873
Eric Laurent81784c32012-11-19 14:55:58 -08006874bool AudioFlinger::RecordThread::threadLoop()
6875{
Eric Laurent81784c32012-11-19 14:55:58 -08006876 nsecs_t lastWarning = 0;
6877
6878 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006879
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006880reacquire_wakelock:
6881 sp<RecordTrack> activeTrack;
6882 {
6883 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006884 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006885 }
6886
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006887 // used to request a deferred sleep, to be executed later while mutex is unlocked
6888 uint32_t sleepUs = 0;
6889
Andy Hung446f4df2019-02-21 12:26:41 -08006890 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
6891
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006892 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08006893 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006894 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006895
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006896 // activeTracks accumulates a copy of a subset of mActiveTracks
6897 Vector< sp<RecordTrack> > activeTracks;
6898
Glenn Kasten735f45f2014-08-18 15:51:59 -07006899 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006900 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006901
Glenn Kasten735f45f2014-08-18 15:51:59 -07006902 // reference to a fast track which is about to be removed
6903 sp<RecordTrack> fastTrackToRemove;
6904
Eric Laurent81784c32012-11-19 14:55:58 -08006905 { // scope for mLock
6906 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006907
Eric Laurent021cf962014-05-13 10:18:14 -07006908 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006909
Eric Laurent000a4192014-01-29 15:17:32 -08006910 // check exitPending here because checkForNewParameters_l() and
6911 // checkForNewParameters_l() can temporarily release mLock
6912 if (exitPending()) {
6913 break;
6914 }
6915
Eric Laurent5c25d562016-07-13 17:17:45 -07006916 // sleep with mutex unlocked
6917 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006918 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006919 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6920 ATRACE_END();
6921 sleepUs = 0;
6922 continue;
6923 }
6924
Glenn Kasten2b806402013-11-20 16:37:38 -08006925 // if no active track(s), then standby and release wakelock
6926 size_t size = mActiveTracks.size();
6927 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006928 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006929 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006930 releaseWakeLock_l();
6931 ALOGV("RecordThread: loop stopping");
6932 // go to sleep
6933 mWaitWorkCV.wait(mLock);
6934 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006935 goto reacquire_wakelock;
6936 }
6937
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006938 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006939 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006940 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006941
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006942 activeTrack = mActiveTracks[i];
6943 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006944 if (activeTrack->isFastTrack()) {
6945 ALOG_ASSERT(fastTrackToRemove == 0);
6946 fastTrackToRemove = activeTrack;
6947 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006948 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006949 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006950 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006951 continue;
6952 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006953
6954 TrackBase::track_state activeTrackState = activeTrack->mState;
6955 switch (activeTrackState) {
6956
6957 case TrackBase::PAUSING:
6958 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006959 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006960 doBroadcast = true;
6961 size--;
6962 continue;
6963
6964 case TrackBase::STARTING_1:
6965 sleepUs = 10000;
6966 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006967 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006968 continue;
6969
6970 case TrackBase::STARTING_2:
6971 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006972 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006973 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006974 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006975 break;
6976
6977 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006978 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006979 break;
6980
Andy Hungce685402018-10-05 17:23:27 -07006981 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6982 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6983 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006984 default:
Andy Hungce685402018-10-05 17:23:27 -07006985 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6986 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006987 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006988
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006989 activeTracks.add(activeTrack);
6990 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006991
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006992 if (activeTrack->isFastTrack()) {
6993 ALOG_ASSERT(!mFastTrackAvail);
6994 ALOG_ASSERT(fastTrack == 0);
6995 fastTrack = activeTrack;
6996 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006997 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006998
Andy Hungdae27702016-10-31 14:01:16 -07006999 mActiveTracks.updatePowerState(this);
7000
Kevin Rocard069c2712018-03-29 19:09:14 -07007001 updateMetadata_l();
7002
Eric Laurent5c25d562016-07-13 17:17:45 -07007003 if (allStopped) {
7004 standbyIfNotAlreadyInStandby();
7005 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007006 if (doBroadcast) {
7007 mStartStopCond.broadcast();
7008 }
7009
7010 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007011 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007012 if (sleepUs == 0) {
7013 sleepUs = kRecordThreadSleepUs;
7014 }
7015 continue;
7016 }
7017 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007018
Eric Laurent81784c32012-11-19 14:55:58 -08007019 lockEffectChains_l(effectChains);
7020 }
7021
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007022 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007023
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007024 size_t size = effectChains.size();
7025 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007026 // thread mutex is not locked, but effect chain is locked
7027 effectChains[i]->process_l();
7028 }
7029
Glenn Kasten735f45f2014-08-18 15:51:59 -07007030 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007031 if (mFastCapture != 0) {
7032 FastCaptureStateQueue *sq = mFastCapture->sq();
7033 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007034 bool didModify = false;
7035 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007036 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7037 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7038 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7039 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7040 if (old == -1) {
7041 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7042 }
7043 }
7044 state->mCommand = FastCaptureState::READ_WRITE;
7045#if 0 // FIXME
7046 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007047 FastThreadDumpState::kSamplingNforLowRamDevice :
7048 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007049#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007050 didModify = true;
7051 }
7052 audio_track_cblk_t *cblkOld = state->mCblk;
7053 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7054 if (cblkNew != cblkOld) {
7055 state->mCblk = cblkNew;
7056 // block until acked if removing a fast track
7057 if (cblkOld != NULL) {
7058 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7059 }
7060 didModify = true;
7061 }
jiabin01c8f562018-07-19 17:47:28 -07007062 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7063 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7064 if (state->mFastPatchRecordBufferProvider != abp) {
7065 state->mFastPatchRecordBufferProvider = abp;
7066 state->mFastPatchRecordFormat = fastTrack == 0 ?
7067 AUDIO_FORMAT_INVALID : fastTrack->format();
7068 didModify = true;
7069 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007070 sq->end(didModify);
7071 if (didModify) {
7072 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007073#if 0
7074 if (kUseFastCapture == FastCapture_Dynamic) {
7075 mNormalSource = mPipeSource;
7076 }
7077#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007078 }
7079 }
7080
Glenn Kasten735f45f2014-08-18 15:51:59 -07007081 // now run the fast track destructor with thread mutex unlocked
7082 fastTrackToRemove.clear();
7083
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007084 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7085 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7086 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7087 // If destination is non-contiguous, first read past the nominal end of buffer, then
7088 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007089
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007090 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007091 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007092 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007093
7094 // If an NBAIO source is present, use it to read the normal capture's data
7095 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007096 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007097
7098 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7099 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7100 // we immediately retry the read() to get data and prevent another overflow.
7101 for (int retries = 0; retries <= 2; ++retries) {
7102 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7103 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7104 framesToRead);
7105 if (framesRead != OVERRUN) break;
7106 }
7107
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007108 const ssize_t availableToRead = mPipeSource->availableToRead();
7109 if (availableToRead >= 0) {
7110 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
7111 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7112 "more frames to read than fifo size, %zd > %zu",
7113 availableToRead, mPipeFramesP2);
7114 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7115 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7116 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7117 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007118 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7119 }
7120 if (framesRead < 0) {
7121 status_t status = (status_t) framesRead;
7122 switch (status) {
7123 case OVERRUN:
7124 ALOGW("overrun on read from pipe");
7125 framesRead = 0;
7126 break;
7127 case NEGOTIATE:
7128 ALOGE("re-negotiation is needed");
7129 framesRead = -1; // Will cause an attempt to recover.
7130 break;
7131 default:
7132 ALOGE("unknown error %d on read from pipe", status);
7133 break;
7134 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007135 }
7136 // otherwise use the HAL / AudioStreamIn directly
7137 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007138 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007139 size_t bytesRead;
Mikhail Naganovaf288872019-09-25 13:05:02 -07007140 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007141 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007142 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007143 if (result < 0) {
7144 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007145 } else {
7146 framesRead = bytesRead / mFrameSize;
7147 }
7148 }
7149
Andy Hung446f4df2019-02-21 12:26:41 -08007150 const int64_t lastIoEndNs = systemTime(); // end IO timing
7151
Andy Hung3f0c9022016-01-15 17:49:46 -08007152 // Update server timestamp with server stats
7153 // systemTime() is optional if the hardware supports timestamps.
7154 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007155 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
Andy Hung3f0c9022016-01-15 17:49:46 -08007156
7157 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007158 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007159 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007160 if (mStandby) {
7161 mTimestampVerifier.discontinuity();
Mikhail Naganovaf288872019-09-25 13:05:02 -07007162 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007163 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7164
7165 mTimestampVerifier.add(position, time, mSampleRate);
7166
7167 // Correct timestamps
7168 if (isTimestampCorrectionEnabled()) {
7169 ALOGV("TS_BEFORE: %d %lld %lld",
7170 id(), (long long)time, (long long)position);
7171 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7172 position = correctedTimestamp.mFrames;
7173 time = correctedTimestamp.mTimeNs;
7174 ALOGV("TS_AFTER: %d %lld %lld",
7175 id(), (long long)time, (long long)position);
7176 }
7177
Andy Hung3f0c9022016-01-15 17:49:46 -08007178 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7179 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7180 // Note: In general record buffers should tend to be empty in
7181 // a properly running pipeline.
7182 //
7183 // Also, it is not advantageous to call get_presentation_position during the read
7184 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007185 } else {
7186 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007187 }
7188 }
Andy Hunge6c37112019-02-26 17:38:10 -08007189
7190 // From the timestamp, input read latency is negative output write latency.
7191 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7192 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7193 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7194 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7195 mLatencyMs.add(latencyMs);
7196 }
7197
Andy Hung3f0c9022016-01-15 17:49:46 -08007198 // Use this to track timestamp information
7199 // ALOGD("%s", mTimestamp.toString().c_str());
7200
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007201 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007202 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007203 // Force input into standby so that it tries to recover at next read attempt
7204 inputStandBy();
7205 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007206 }
7207 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007208 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007209 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007210 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007211 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007212
Andy Hung8946a282018-04-19 20:04:56 -07007213#ifdef TEE_SINK
7214 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7215#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007216 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007217 {
7218 size_t part1 = mRsmpInFramesP2 - rear;
7219 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007220 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007221 (framesRead - part1) * mFrameSize);
7222 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007223 }
7224 rear = mRsmpInRear += framesRead;
7225
7226 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007227
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007228 // loop over each active track
7229 for (size_t i = 0; i < size; i++) {
7230 activeTrack = activeTracks[i];
7231
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007232 // skip fast tracks, as those are handled directly by FastCapture
7233 if (activeTrack->isFastTrack()) {
7234 continue;
7235 }
7236
Andy Hung73c02e42015-03-29 01:13:58 -07007237 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007238 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7239
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007240 enum {
7241 OVERRUN_UNKNOWN,
7242 OVERRUN_TRUE,
7243 OVERRUN_FALSE
7244 } overrun = OVERRUN_UNKNOWN;
7245
7246 // loop over getNextBuffer to handle circular sink
7247 for (;;) {
7248
7249 activeTrack->mSink.frameCount = ~0;
7250 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7251 size_t framesOut = activeTrack->mSink.frameCount;
7252 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7253
Andy Hung73c02e42015-03-29 01:13:58 -07007254 // check available frames and handle overrun conditions
7255 // if the record track isn't draining fast enough.
7256 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007257 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007258 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7259 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007260 overrun = OVERRUN_TRUE;
7261 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007262 if (framesOut == 0 || framesIn == 0) {
7263 break;
7264 }
7265
Andy Hung6770c6f2015-04-07 13:43:36 -07007266 // Don't allow framesOut to be larger than what is possible with resampling
7267 // from framesIn.
7268 // This isn't strictly necessary but helps limit buffer resizing in
7269 // RecordBufferConverter. TODO: remove when no longer needed.
7270 framesOut = min(framesOut,
7271 destinationFramesPossible(
7272 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007273
7274 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007275 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007276 // straight from RecordThread buffer to RecordTrack buffer.
7277 AudioBufferProvider::Buffer buffer;
7278 buffer.frameCount = framesOut;
7279 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7280 if (status == OK && buffer.frameCount != 0) {
7281 ALOGV_IF(buffer.frameCount != framesOut,
7282 "%s() read less than expected (%zu vs %zu)",
7283 __func__, buffer.frameCount, framesOut);
7284 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007285 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007286 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7287 } else {
7288 framesOut = 0;
7289 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7290 __func__, status, buffer.frameCount);
7291 }
7292 } else {
7293 // process frames from the RecordThread buffer provider to the RecordTrack
7294 // buffer
7295 framesOut = activeTrack->mRecordBufferConverter->convert(
7296 activeTrack->mSink.raw,
7297 activeTrack->mResamplerBufferProvider,
7298 framesOut);
7299 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007300
7301 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7302 overrun = OVERRUN_FALSE;
7303 }
7304
7305 if (activeTrack->mFramesToDrop == 0) {
7306 if (framesOut > 0) {
7307 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007308 // Sanitize before releasing if the track has no access to the source data
7309 // An idle UID receives silence from non virtual devices until active
7310 if (activeTrack->isSilenced()) {
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007311 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007312 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007313 activeTrack->releaseBuffer(&activeTrack->mSink);
7314 }
7315 } else {
7316 // FIXME could do a partial drop of framesOut
7317 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007318 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007319 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007320 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007321 }
7322 } else {
7323 activeTrack->mFramesToDrop += framesOut;
7324 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7325 activeTrack->mSyncStartEvent->isCancelled()) {
7326 ALOGW("Synced record %s, session %d, trigger session %d",
7327 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7328 activeTrack->sessionId(),
7329 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007330 activeTrack->mSyncStartEvent->triggerSession() :
7331 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007332 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007333 }
7334 }
7335 }
7336
7337 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007338 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007339 }
7340 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007341
7342 switch (overrun) {
7343 case OVERRUN_TRUE:
7344 // client isn't retrieving buffers fast enough
7345 if (!activeTrack->setOverflow()) {
7346 nsecs_t now = systemTime();
7347 // FIXME should lastWarning per track?
7348 if ((now - lastWarning) > kWarningThrottleNs) {
7349 ALOGW("RecordThread: buffer overflow");
7350 lastWarning = now;
7351 }
7352 }
7353 break;
7354 case OVERRUN_FALSE:
7355 activeTrack->clearOverflow();
7356 break;
7357 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007358 break;
7359 }
7360
Andy Hung3f0c9022016-01-15 17:49:46 -08007361 // update frame information and push timestamp out
7362 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007363 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007364 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7365 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007366 }
7367
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007368unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007369 // enable changes in effect chain
7370 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007371 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007372 if (audio_has_proportional_frames(mFormat)
7373 && loopCount == lastLoopCountRead + 1) {
7374 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7375 const double jitterMs =
7376 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7377 {framesRead, readPeriodNs},
7378 {0, 0} /* lastTimestamp */, mSampleRate);
7379 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7380
7381 Mutex::Autolock _l(mLock);
7382 mIoJitterMs.add(jitterMs);
7383 mProcessTimeMs.add(processMs);
7384 }
7385 // update timing info.
7386 mLastIoBeginNs = lastIoBeginNs;
7387 mLastIoEndNs = lastIoEndNs;
7388 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007389 }
7390
Glenn Kasten93e471f2013-08-19 08:40:07 -07007391 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007392
7393 {
7394 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007395 for (size_t i = 0; i < mTracks.size(); i++) {
7396 sp<RecordTrack> track = mTracks[i];
7397 track->invalidate();
7398 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007399 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007400 mStartStopCond.broadcast();
7401 }
7402
7403 releaseWakeLock();
7404
7405 ALOGV("RecordThread %p exiting", this);
7406 return false;
7407}
7408
Glenn Kasten93e471f2013-08-19 08:40:07 -07007409void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007410{
7411 if (!mStandby) {
7412 inputStandBy();
7413 mStandby = true;
7414 }
7415}
7416
7417void AudioFlinger::RecordThread::inputStandBy()
7418{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007419 // Idle the fast capture if it's currently running
7420 if (mFastCapture != 0) {
7421 FastCaptureStateQueue *sq = mFastCapture->sq();
7422 FastCaptureState *state = sq->begin();
7423 if (!(state->mCommand & FastCaptureState::IDLE)) {
7424 state->mCommand = FastCaptureState::COLD_IDLE;
7425 state->mColdFutexAddr = &mFastCaptureFutex;
7426 state->mColdGen++;
7427 mFastCaptureFutex = 0;
7428 sq->end();
7429 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7430 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7431#if 0
7432 if (kUseFastCapture == FastCapture_Dynamic) {
7433 // FIXME
7434 }
7435#endif
7436#ifdef AUDIO_WATCHDOG
7437 // FIXME
7438#endif
7439 } else {
7440 sq->end(false /*didModify*/);
7441 }
7442 }
Mikhail Naganovaf288872019-09-25 13:05:02 -07007443 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007444 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007445
7446 // If going into standby, flush the pipe source.
7447 if (mPipeSource.get() != nullptr) {
7448 const ssize_t flushed = mPipeSource->flush();
7449 if (flushed > 0) {
7450 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7451 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7452 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7453 }
7454 }
Eric Laurent81784c32012-11-19 14:55:58 -08007455}
7456
Glenn Kasten05997e22014-03-13 15:08:33 -07007457// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007458sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007459 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007460 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007461 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007462 audio_format_t format,
7463 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007464 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007465 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007466 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007467 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007468 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007469 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007470 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007471 status_t *status,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007472 audio_port_handle_t portId,
7473 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007474{
Glenn Kasten74935e42013-12-19 08:56:45 -08007475 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007476 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007477 sp<RecordTrack> track;
7478 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007479 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007480 audio_input_flags_t requestedFlags = *flags;
7481 uint32_t sampleRate;
7482
7483 lStatus = initCheck();
7484 if (lStatus != NO_ERROR) {
7485 ALOGE("createRecordTrack_l() audio driver not initialized");
7486 goto Exit;
7487 }
7488
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007489 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7490 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7491 lStatus = BAD_VALUE;
7492 goto Exit;
7493 }
7494
Eric Laurentf14db3c2017-12-08 14:20:36 -08007495 if (*pSampleRate == 0) {
7496 *pSampleRate = mSampleRate;
7497 }
7498 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007499
7500 // special case for FAST flag considered OK if fast capture is present
7501 if (hasFastCapture()) {
7502 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7503 }
7504
Eric Laurentf14db3c2017-12-08 14:20:36 -08007505 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007506 if ((*flags & inputFlags) != *flags) {
7507 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7508 " input flags (%08x)",
7509 *flags, inputFlags);
7510 *flags = (audio_input_flags_t)(*flags & inputFlags);
7511 }
Eric Laurent81784c32012-11-19 14:55:58 -08007512
Glenn Kasten90e58b12013-07-31 16:16:02 -07007513 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007514 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007515 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007516 // we formerly checked for a callback handler (non-0 tid),
7517 // but that is no longer required for TRANSFER_OBTAIN mode
7518 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007519 // Frame count is not specified (0), or is less than or equal the pipe depth.
7520 // It is OK to provide a higher capacity than requested.
7521 // We will force it to mPipeFramesP2 below.
7522 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007523 // PCM data
7524 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007525 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007526 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007527 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007528 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007529 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007530 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007531 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007532 hasFastCapture() &&
7533 // there are sufficient fast track slots available
7534 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007535 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007536 // check compatibility with audio effects.
7537 Mutex::Autolock _l(mLock);
7538 // Do not accept FAST flag if the session has software effects
7539 sp<EffectChain> chain = getEffectChain_l(sessionId);
7540 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007541 audio_input_flags_t old = *flags;
7542 chain->checkInputFlagCompatibility(flags);
7543 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007544 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7545 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007546 }
7547 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007548 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007549 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7550 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007551 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007552 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7553 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007554 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007555 this, frameCount, mFrameCount, mPipeFramesP2,
7556 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007557 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007558 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007559 }
7560 }
7561
Eric Laurentf14db3c2017-12-08 14:20:36 -08007562 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7563 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7564 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7565 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7566 lStatus = BAD_TYPE;
7567 goto Exit;
7568 }
7569
Glenn Kasten74105912014-07-03 12:28:53 -07007570 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007571 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007572 // fast track: frame count is exactly the pipe depth
7573 frameCount = mPipeFramesP2;
7574 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007575 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007576 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007577 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7578 // or 20 ms if there is a fast capture
7579 // TODO This could be a roundupRatio inline, and const
7580 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7581 * sampleRate + mSampleRate - 1) / mSampleRate;
7582 // minimum number of notification periods is at least kMinNotifications,
7583 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7584 static const size_t kMinNotifications = 3;
7585 static const uint32_t kMinMs = 30;
7586 // TODO This could be a roundupRatio inline
7587 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7588 // TODO This could be a roundupRatio inline
7589 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7590 maxNotificationFrames;
7591 const size_t minFrameCount = maxNotificationFrames *
7592 max(kMinNotifications, minNotificationsByMs);
7593 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007594 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7595 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007596 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007597 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007598 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007599 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007600
7601 { // scope for mLock
7602 Mutex::Autolock _l(mLock);
7603
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007604 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007605 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007606 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007607 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007608
Glenn Kasten03003332013-08-06 15:40:54 -07007609 lStatus = track->initCheck();
7610 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007611 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007612 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007613 goto Exit;
7614 }
7615 mTracks.add(track);
7616
Eric Laurent05067782016-06-01 18:27:28 -07007617 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007618 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7619 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7620 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007621 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007622 }
Eric Laurent81784c32012-11-19 14:55:58 -08007623 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007624
Eric Laurent81784c32012-11-19 14:55:58 -08007625 lStatus = NO_ERROR;
7626
7627Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007628 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007629 return track;
7630}
7631
7632status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7633 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007634 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007635{
7636 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7637 sp<ThreadBase> strongMe = this;
7638 status_t status = NO_ERROR;
7639
7640 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007641 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007642 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007643 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007644 triggerSession,
7645 recordTrack->sessionId(),
7646 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007647 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007648 // Sync event can be cancelled by the trigger session if the track is not in a
7649 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007650 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007651 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007652 } else {
7653 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007654 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007655 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007656 }
7657 }
7658
7659 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007660 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007661 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007662 if (recordTrack->isInvalid()) {
7663 recordTrack->clearSyncStartEvent();
7664 return INVALID_OPERATION;
7665 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007666 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7667 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007668 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7669 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007670 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007671 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007672 } else {
7673 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007674 }
7675 return status;
7676 }
7677
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007678 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7679 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7680 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007681 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007682 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007683 status_t status = NO_ERROR;
7684 if (recordTrack->isExternalTrack()) {
7685 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007686 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007687 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007688 if (recordTrack->isInvalid()) {
7689 recordTrack->clearSyncStartEvent();
7690 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7691 recordTrack->mState = TrackBase::STARTING_2;
7692 // STARTING_2 forces destroy to call stopInput.
7693 }
7694 return INVALID_OPERATION;
7695 }
7696 if (recordTrack->mState != TrackBase::STARTING_1) {
7697 ALOGW("%s(%d): unsynchronized mState:%d change",
7698 __func__, recordTrack->id(), recordTrack->mState);
7699 // Someone else has changed state, let them take over,
7700 // leave mState in the new state.
7701 recordTrack->clearSyncStartEvent();
7702 return INVALID_OPERATION;
7703 }
7704 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007705 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007706 ALOGW("%s(%d): startInput failed, status %d",
7707 __func__, recordTrack->id(), status);
7708 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7709 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007710 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007711 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007712 return status;
7713 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007714 sendIoConfigEvent_l(
7715 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007716 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007717 // Catch up with current buffer indices if thread is already running.
7718 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7719 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7720 // see previously buffered data before it called start(), but with greater risk of overrun.
7721
Andy Hung73c02e42015-03-29 01:13:58 -07007722 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007723 if (!recordTrack->isDirect()) {
7724 // clear any converter state as new data will be discontinuous
7725 recordTrack->mRecordBufferConverter->reset();
7726 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007727 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007728 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007729 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007730 return status;
7731 }
Eric Laurent81784c32012-11-19 14:55:58 -08007732}
7733
Eric Laurent81784c32012-11-19 14:55:58 -08007734void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7735{
7736 sp<SyncEvent> strongEvent = event.promote();
7737
7738 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007739 sp<RefBase> ptr = strongEvent->cookie().promote();
7740 if (ptr != 0) {
7741 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7742 recordTrack->handleSyncStartEvent(strongEvent);
7743 }
Eric Laurent81784c32012-11-19 14:55:58 -08007744 }
7745}
7746
Glenn Kastena8356f62013-07-25 14:37:52 -07007747bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007748 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007749 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007750 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007751 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007752 return false;
7753 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007754 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007755 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007756
Andy Hungabfab202019-03-07 19:45:54 -08007757 // NOTE: Waiting here is important to keep stop synchronous.
7758 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07007759 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7760 mWaitWorkCV.broadcast(); // signal thread to stop
7761 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007762 }
Andy Hungce685402018-10-05 17:23:27 -07007763
7764 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007765 ALOGV("Record stopped OK");
7766 return true;
7767 }
Andy Hungce685402018-10-05 17:23:27 -07007768
7769 // don't handle anything - we've been invalidated or restarted and in a different state
7770 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7771 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007772 return false;
7773}
7774
Glenn Kasten0f11b512014-01-31 16:18:54 -08007775bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007776{
7777 return false;
7778}
7779
Glenn Kasten0f11b512014-01-31 16:18:54 -08007780status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007781{
7782#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7783 if (!isValidSyncEvent(event)) {
7784 return BAD_VALUE;
7785 }
7786
Glenn Kastend848eb42016-03-08 13:42:11 -08007787 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007788 status_t ret = NAME_NOT_FOUND;
7789
7790 Mutex::Autolock _l(mLock);
7791
7792 for (size_t i = 0; i < mTracks.size(); i++) {
7793 sp<RecordTrack> track = mTracks[i];
7794 if (eventSession == track->sessionId()) {
7795 (void) track->setSyncEvent(event);
7796 ret = NO_ERROR;
7797 }
7798 }
7799 return ret;
7800#else
7801 return BAD_VALUE;
7802#endif
7803}
7804
jiabin653cc0a2018-01-17 17:54:10 -08007805status_t AudioFlinger::RecordThread::getActiveMicrophones(
7806 std::vector<media::MicrophoneInfo>* activeMicrophones)
7807{
7808 ALOGV("RecordThread::getActiveMicrophones");
7809 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007810 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7811 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007812}
7813
Paul McLean12340082019-03-19 09:35:05 -06007814status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
7815 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007816{
Paul McLean12340082019-03-19 09:35:05 -06007817 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007818 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007819 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007820}
7821
Paul McLean12340082019-03-19 09:35:05 -06007822status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007823{
Paul McLean12340082019-03-19 09:35:05 -06007824 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007825 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007826 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007827}
7828
Kevin Rocard069c2712018-03-29 19:09:14 -07007829void AudioFlinger::RecordThread::updateMetadata_l()
7830{
7831 if (mInput == nullptr || mInput->stream == nullptr ||
7832 !mActiveTracks.readAndClearHasChanged()) {
7833 return;
7834 }
7835 StreamInHalInterface::SinkMetadata metadata;
7836 for (const sp<RecordTrack> &track : mActiveTracks) {
7837 // No track is invalid as this is called after prepareTrack_l in the same critical section
7838 metadata.tracks.push_back({
7839 .source = track->attributes().source,
7840 .gain = 1, // capture tracks do not have volumes
7841 });
7842 }
7843 mInput->stream->updateSinkMetadata(metadata);
7844}
7845
Eric Laurent81784c32012-11-19 14:55:58 -08007846// destroyTrack_l() must be called with ThreadBase::mLock held
7847void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7848{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007849 track->terminate();
7850 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007851 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007852 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007853 removeTrack_l(track);
7854 }
7855}
7856
7857void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7858{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007859 String8 result;
7860 track->appendDump(result, false /* active */);
7861 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7862
Eric Laurent81784c32012-11-19 14:55:58 -08007863 mTracks.remove(track);
7864 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007865 if (track->isFastTrack()) {
7866 ALOG_ASSERT(!mFastTrackAvail);
7867 mFastTrackAvail = true;
7868 }
Eric Laurent81784c32012-11-19 14:55:58 -08007869}
7870
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007871void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007872{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007873 AudioStreamIn *input = mInput;
7874 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7875 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08007876 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007877 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007878 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007879 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007880 }
Andy Hungbfa64962017-06-12 14:43:19 -07007881
7882 if (input != nullptr) {
7883 dprintf(fd, " Hal stream dump:\n");
7884 (void)input->stream->dump(fd);
7885 }
7886
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007887 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007888 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007889
Glenn Kasten2f90c512015-12-02 11:40:09 -08007890 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7891 // while we are dumping it. It may be inconsistent, but it won't mutate!
7892 // This is a large object so we place it on the heap.
7893 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007894 const std::unique_ptr<FastCaptureDumpState> copy =
7895 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007896 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007897}
7898
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007899void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007900{
Eric Laurent81784c32012-11-19 14:55:58 -08007901 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007902 size_t numtracks = mTracks.size();
7903 size_t numactive = mActiveTracks.size();
7904 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007905 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007906 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007907 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007908 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007909 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007910 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007911 for (size_t i = 0; i < numtracks ; ++i) {
7912 sp<RecordTrack> track = mTracks[i];
7913 if (track != 0) {
7914 bool active = mActiveTracks.indexOf(track) >= 0;
7915 if (active) {
7916 numactiveseen++;
7917 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007918 result.append(prefix);
7919 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007920 }
Eric Laurent81784c32012-11-19 14:55:58 -08007921 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007922 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007923 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007924 }
7925
Marco Nelissenb2208842014-02-07 14:00:50 -08007926 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007927 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007928 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007929 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007930 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007931 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007932 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007933 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007934 result.append(prefix);
7935 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007936 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007937 }
Eric Laurent81784c32012-11-19 14:55:58 -08007938
7939 }
7940 write(fd, result.string(), result.size());
7941}
7942
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007943void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7944{
7945 Mutex::Autolock _l(mLock);
7946 for (size_t i = 0; i < mTracks.size() ; i++) {
7947 sp<RecordTrack> track = mTracks[i];
7948 if (track != 0 && track->uid() == uid) {
7949 track->setSilenced(silenced);
7950 }
7951 }
7952}
Andy Hung73c02e42015-03-29 01:13:58 -07007953
7954void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7955{
7956 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7957 RecordThread *recordThread = (RecordThread *) threadBase.get();
7958 mRsmpInFront = recordThread->mRsmpInRear;
7959 mRsmpInUnrel = 0;
7960}
7961
7962void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7963 size_t *framesAvailable, bool *hasOverrun)
7964{
7965 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7966 RecordThread *recordThread = (RecordThread *) threadBase.get();
7967 const int32_t rear = recordThread->mRsmpInRear;
7968 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07007969 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07007970
7971 size_t framesIn;
7972 bool overrun = false;
7973 if (filled < 0) {
7974 // should not happen, but treat like a massive overrun and re-sync
7975 framesIn = 0;
7976 mRsmpInFront = rear;
7977 overrun = true;
7978 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7979 framesIn = (size_t) filled;
7980 } else {
7981 // client is not keeping up with server, but give it latest data
7982 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07007983 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
7984 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07007985 overrun = true;
7986 }
7987 if (framesAvailable != NULL) {
7988 *framesAvailable = framesIn;
7989 }
7990 if (hasOverrun != NULL) {
7991 *hasOverrun = overrun;
7992 }
7993}
7994
Eric Laurent81784c32012-11-19 14:55:58 -08007995// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007996status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007997 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007998{
Andy Hung73c02e42015-03-29 01:13:58 -07007999 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008000 if (threadBase == 0) {
8001 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008002 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008003 return NOT_ENOUGH_DATA;
8004 }
8005 RecordThread *recordThread = (RecordThread *) threadBase.get();
8006 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008007 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008008 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008009 // FIXME should not be P2 (don't want to increase latency)
8010 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008011 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008012 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008013 front &= recordThread->mRsmpInFramesP2 - 1;
8014 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008015 if (part1 > (size_t) filled) {
8016 part1 = filled;
8017 }
8018 size_t ask = buffer->frameCount;
8019 ALOG_ASSERT(ask > 0);
8020 if (part1 > ask) {
8021 part1 = ask;
8022 }
8023 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008024 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008025 buffer->raw = NULL;
8026 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008027 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008028 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008029 }
8030
Andy Hung57446612015-04-19 23:56:46 -07008031 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008032 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008033 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008034 return NO_ERROR;
8035}
8036
8037// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008038void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8039 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008040{
Hongwei Wang95e37682019-04-12 11:13:36 -07008041 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008042 if (stepCount == 0) {
8043 return;
8044 }
Andy Hung73c02e42015-03-29 01:13:58 -07008045 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8046 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008047 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008048 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008049 buffer->frameCount = 0;
8050}
8051
Eric Laurentd8365c52017-07-16 15:27:05 -07008052void AudioFlinger::RecordThread::checkBtNrec()
8053{
8054 Mutex::Autolock _l(mLock);
8055 checkBtNrec_l();
8056}
8057
8058void AudioFlinger::RecordThread::checkBtNrec_l()
8059{
8060 // disable AEC and NS if the device is a BT SCO headset supporting those
8061 // pre processings
jiabin10d86fd2019-10-31 17:20:42 -07008062 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008063 mAudioFlinger->btNrecIsOff();
8064 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8065 for (size_t i = 0; i < mEffectChains.size(); i++) {
8066 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8067 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8068 }
8069 }
8070}
8071
Andy Hung97a893e2015-03-29 01:03:07 -07008072
Eric Laurent10351942014-05-08 18:49:52 -07008073bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8074 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008075{
8076 bool reconfig = false;
8077
Eric Laurent10351942014-05-08 18:49:52 -07008078 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008079
Eric Laurent10351942014-05-08 18:49:52 -07008080 audio_format_t reqFormat = mFormat;
8081 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008082 // 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 -07008083 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8084
8085 AudioParameter param = AudioParameter(keyValuePair);
8086 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008087
8088 // scope for AutoPark extends to end of method
8089 AutoPark<FastCapture> park(mFastCapture);
8090
Eric Laurent10351942014-05-08 18:49:52 -07008091 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8092 // channel count change can be requested. Do we mandate the first client defines the
8093 // HAL sampling rate and channel count or do we allow changes on the fly?
8094 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8095 samplingRate = value;
8096 reconfig = true;
8097 }
8098 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008099 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008100 status = BAD_VALUE;
8101 } else {
8102 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008103 reconfig = true;
8104 }
Eric Laurent10351942014-05-08 18:49:52 -07008105 }
8106 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8107 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008108 if (!audio_is_input_channel(mask) ||
8109 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008110 status = BAD_VALUE;
8111 } else {
8112 channelMask = mask;
8113 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008114 }
Eric Laurent10351942014-05-08 18:49:52 -07008115 }
8116 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8117 // do not accept frame count changes if tracks are open as the track buffer
8118 // size depends on frame count and correct behavior would not be guaranteed
8119 // if frame count is changed after track creation
8120 if (mActiveTracks.size() > 0) {
8121 status = INVALID_OPERATION;
8122 } else {
8123 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008124 }
Eric Laurent10351942014-05-08 18:49:52 -07008125 }
8126 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07008127 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008128 }
8129 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8130 mAudioSource != (audio_source_t)value) {
jiabin10d86fd2019-10-31 17:20:42 -07008131 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008132 }
Glenn Kastene198c362013-08-13 09:13:36 -07008133
Eric Laurent10351942014-05-08 18:49:52 -07008134 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008135 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008136 if (status == INVALID_OPERATION) {
8137 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008138 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008139 }
8140 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008141 if (status == BAD_VALUE) {
8142 uint32_t sRate;
8143 audio_channel_mask_t channelMask;
8144 audio_format_t format;
8145 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8146 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8147 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8148 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8149 status = NO_ERROR;
8150 }
Eric Laurent81784c32012-11-19 14:55:58 -08008151 }
Eric Laurent10351942014-05-08 18:49:52 -07008152 if (status == NO_ERROR) {
8153 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008154 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008155 }
8156 }
Eric Laurent81784c32012-11-19 14:55:58 -08008157 }
Eric Laurent10351942014-05-08 18:49:52 -07008158
Eric Laurent81784c32012-11-19 14:55:58 -08008159 return reconfig;
8160}
8161
8162String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8163{
Eric Laurent81784c32012-11-19 14:55:58 -08008164 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008165 if (initCheck() == NO_ERROR) {
8166 String8 out_s8;
8167 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8168 return out_s8;
8169 }
Eric Laurent81784c32012-11-19 14:55:58 -08008170 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008171 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008172}
8173
Eric Laurent09f1ed22019-04-24 17:45:17 -07008174void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8175 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008176 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8177
8178 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008179
8180 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008181 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008182 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008183 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008184 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008185 desc->mChannelMask = mChannelMask;
8186 desc->mSamplingRate = mSampleRate;
8187 desc->mFormat = mFormat;
8188 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008189 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008190 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008191 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008192 case AUDIO_CLIENT_STARTED:
8193 desc->mPatch = mPatch;
8194 desc->mPortId = portId;
8195 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008196 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008197 default:
8198 break;
8199 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008200 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008201}
8202
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008203void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008204{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008205 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8206 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008207 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008208 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8209 if (audio_is_linear_pcm(mFormat)) {
8210 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8211 mChannelCount, FCC_8);
8212 } else {
8213 // Can have more that FCC_8 channels in encoded streams.
8214 ALOGI("HAL format %#x is not linear pcm", mFormat);
8215 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008216 result = mInput->stream->getFrameSize(&mFrameSize);
8217 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8218 result = mInput->stream->getBufferSize(&mBufferSize);
8219 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008220 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008221 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8222 "mBufferSize=%lld, mFrameCount=%lld",
8223 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8224 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008225 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008226 // 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 -07008227 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008228 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008229 // A larger value should allow more old data to be read after a track calls start(),
8230 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008231 //
8232 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008233 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008234 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008235 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008236 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008237
8238 // TODO optimize audio capture buffer sizes ...
8239 // Here we calculate the size of the sliding buffer used as a source
8240 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8241 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8242 // be better to have it derived from the pipe depth in the long term.
8243 // The current value is higher than necessary. However it should not add to latency.
8244
Glenn Kasten85948432013-08-19 12:09:05 -07008245 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008246 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8247 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008248 // if posix_memalign fails, will segv here.
8249 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008250
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008251 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8252 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008253}
8254
Glenn Kasten5f972c02014-01-13 09:59:31 -08008255uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008256{
8257 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008258 uint32_t result;
8259 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8260 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008261 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008262 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008263}
8264
Glenn Kastend848eb42016-03-08 13:42:11 -08008265KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008266{
Glenn Kastend848eb42016-03-08 13:42:11 -08008267 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008268 Mutex::Autolock _l(mLock);
8269 for (size_t j = 0; j < mTracks.size(); ++j) {
8270 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008271 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008272 if (ids.indexOfKey(sessionId) < 0) {
8273 ids.add(sessionId, true);
8274 }
8275 }
8276 return ids;
8277}
8278
8279AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8280{
8281 Mutex::Autolock _l(mLock);
8282 AudioStreamIn *input = mInput;
8283 mInput = NULL;
8284 return input;
8285}
8286
8287// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008288sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008289{
8290 if (mInput == NULL) {
8291 return NULL;
8292 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008293 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008294}
8295
8296status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8297{
Eric Laurent81784c32012-11-19 14:55:58 -08008298 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008299 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008300 chain->setInBuffer(NULL);
8301 chain->setOutBuffer(NULL);
8302
8303 checkSuspendOnAddEffectChain_l(chain);
8304
Eric Laurent1b928682014-10-02 19:41:47 -07008305 // make sure enabled pre processing effects state is communicated to the HAL as we
8306 // just moved them to a new input stream.
8307 chain->syncHalEffectsState();
8308
Eric Laurent81784c32012-11-19 14:55:58 -08008309 mEffectChains.add(chain);
8310
8311 return NO_ERROR;
8312}
8313
8314size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8315{
8316 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008317
8318 for (size_t i = 0; i < mEffectChains.size(); i++) {
8319 if (chain == mEffectChains[i]) {
8320 mEffectChains.removeAt(i);
8321 break;
8322 }
Eric Laurent81784c32012-11-19 14:55:58 -08008323 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008324 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008325}
8326
Eric Laurent1c333e22014-05-20 10:48:17 -07008327status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8328 audio_patch_handle_t *handle)
8329{
8330 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008331
8332 // store new device and send to effects
jiabin10d86fd2019-10-31 17:20:42 -07008333 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8334 mInDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
François Gaffie0c280aa2018-07-25 10:02:15 +02008335 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008336 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008337 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008338 }
8339
Eric Laurentd8365c52017-07-16 15:27:05 -07008340 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008341
8342 // store new source and send to effects
8343 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8344 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008345 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008346 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008347 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008348 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008349
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008350 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008351 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8352 status = hwDevice->createAudioPatch(patch->num_sources,
8353 patch->sources,
8354 patch->num_sinks,
8355 patch->sinks,
8356 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008357 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008358 char *address;
8359 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8360 address = audio_device_address_to_parameter(
8361 patch->sources[0].ext.device.type,
8362 patch->sources[0].ext.device.address);
8363 } else {
8364 address = (char *)calloc(1, 1);
8365 }
8366 AudioParameter param = AudioParameter(String8(address));
8367 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008368 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008369 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008370 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008371 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008372 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008373 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008374 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008375
jiabin10d86fd2019-10-31 17:20:42 -07008376 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008377 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabin10d86fd2019-10-31 17:20:42 -07008378 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008379 }
Eric Laurent296fb132015-05-01 11:38:42 -07008380
Eric Laurent1c333e22014-05-20 10:48:17 -07008381 return status;
8382}
8383
8384status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8385{
8386 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008387
jiabin10d86fd2019-10-31 17:20:42 -07008388 mPatch = audio_patch{};
8389 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008390
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008391 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008392 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8393 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008394 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008395 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008396 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008397 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008398 }
8399 return status;
8400}
8401
jiabin10d86fd2019-10-31 17:20:42 -07008402void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8403{
8404 mOutDevices = outDevices;
8405 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8406 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008407 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabin10d86fd2019-10-31 17:20:42 -07008408 }
8409}
8410
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008411void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008412{
8413 Mutex::Autolock _l(mLock);
8414 mTracks.add(record);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008415 if (record->getSource()) {
8416 mSource = record->getSource();
8417 }
Eric Laurent83b88082014-06-20 18:31:16 -07008418}
8419
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008420void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008421{
8422 Mutex::Autolock _l(mLock);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008423 if (mSource == record->getSource()) {
8424 mSource = mInput;
8425 }
Eric Laurent83b88082014-06-20 18:31:16 -07008426 destroyTrack_l(record);
8427}
8428
Mikhail Naganovdc769682018-05-04 15:34:08 -07008429void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008430{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008431 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008432 config->role = AUDIO_PORT_ROLE_SINK;
8433 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8434 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008435 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8436 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8437 config->flags.input = mInput->flags;
8438 }
Eric Laurent83b88082014-06-20 18:31:16 -07008439}
Eric Laurent1c333e22014-05-20 10:48:17 -07008440
Eric Laurent6acd1d42017-01-04 14:23:29 -08008441// ----------------------------------------------------------------------------
8442// Mmap
8443// ----------------------------------------------------------------------------
8444
8445AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8446 : mThread(thread)
8447{
Phil Burk9fabbf82017-08-03 12:02:00 -07008448 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008449}
8450
8451AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8452{
Phil Burk9fabbf82017-08-03 12:02:00 -07008453 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008454}
8455
8456status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8457 struct audio_mmap_buffer_info *info)
8458{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008459 return mThread->createMmapBuffer(minSizeFrames, info);
8460}
8461
8462status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8463{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008464 return mThread->getMmapPosition(position);
8465}
8466
Eric Laurenta54f1282017-07-01 19:39:32 -07008467status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008468 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008469
8470{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008471 return mThread->start(client, handle);
8472}
8473
8474status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8475{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008476 return mThread->stop(handle);
8477}
8478
Eric Laurent18b57012017-02-13 16:23:52 -08008479status_t AudioFlinger::MmapThreadHandle::standby()
8480{
Eric Laurent18b57012017-02-13 16:23:52 -08008481 return mThread->standby();
8482}
8483
Eric Laurent6acd1d42017-01-04 14:23:29 -08008484
8485AudioFlinger::MmapThread::MmapThread(
8486 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07008487 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady)
8488 : ThreadBase(audioFlinger, id, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008489 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008490 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008491 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008492 mActiveTracks(&this->mLocalLog),
8493 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8494 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008495{
Eric Laurent18b57012017-02-13 16:23:52 -08008496 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008497 readHalParameters_l();
8498}
8499
8500AudioFlinger::MmapThread::~MmapThread()
8501{
Eric Laurent18b57012017-02-13 16:23:52 -08008502 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008503}
8504
8505void AudioFlinger::MmapThread::onFirstRef()
8506{
8507 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8508}
8509
8510void AudioFlinger::MmapThread::disconnect()
8511{
Eric Laurent331679c2018-04-16 17:03:16 -07008512 ActiveTracks<MmapTrack> activeTracks;
8513 {
8514 Mutex::Autolock _l(mLock);
8515 for (const sp<MmapTrack> &t : mActiveTracks) {
8516 activeTracks.add(t);
8517 }
8518 }
8519 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008520 stop(t->portId());
8521 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008522 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008523 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008524 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008525 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008526 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008527 }
8528}
8529
8530
8531void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8532 audio_stream_type_t streamType __unused,
8533 audio_session_t sessionId,
8534 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008535 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008536 audio_port_handle_t portId)
8537{
8538 mAttr = *attr;
8539 mSessionId = sessionId;
8540 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008541 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 mPortId = portId;
8543}
8544
8545status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8546 struct audio_mmap_buffer_info *info)
8547{
8548 if (mHalStream == 0) {
8549 return NO_INIT;
8550 }
Eric Laurent18b57012017-02-13 16:23:52 -08008551 mStandby = true;
8552 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008553 return mHalStream->createMmapBuffer(minSizeFrames, info);
8554}
8555
8556status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8557{
8558 if (mHalStream == 0) {
8559 return NO_INIT;
8560 }
8561 return mHalStream->getMmapPosition(position);
8562}
8563
Eric Laurent331679c2018-04-16 17:03:16 -07008564status_t AudioFlinger::MmapThread::exitStandby()
8565{
8566 status_t ret = mHalStream->start();
8567 if (ret != NO_ERROR) {
8568 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8569 return ret;
8570 }
8571 mStandby = false;
8572 return NO_ERROR;
8573}
8574
Eric Laurenta54f1282017-07-01 19:39:32 -07008575status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008576 audio_port_handle_t *handle)
8577{
Eric Laurenta54f1282017-07-01 19:39:32 -07008578 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8579 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008580 if (mHalStream == 0) {
8581 return NO_INIT;
8582 }
8583
8584 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008585
Eric Laurenta54f1282017-07-01 19:39:32 -07008586 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008587 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008588 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008589 }
8590
8591 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8592
8593 audio_io_handle_t io = mId;
8594 if (isOutput()) {
8595 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8596 config.sample_rate = mSampleRate;
8597 config.channel_mask = mChannelMask;
8598 config.format = mFormat;
8599 audio_stream_type_t stream = streamType();
8600 audio_output_flags_t flags =
8601 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008602 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008603 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008604 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8605 mSessionId,
8606 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008607 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008608 client.clientUid,
8609 &config,
8610 flags,
8611 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008612 &portId,
8613 &secondaryOutputs);
8614 ALOGD_IF(!secondaryOutputs.empty(),
8615 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008616 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008617 audio_config_base_t config;
8618 config.sample_rate = mSampleRate;
8619 config.channel_mask = mChannelMask;
8620 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008621 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008622 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008623 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008624 mSessionId,
8625 client.clientPid,
8626 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008627 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008628 &config,
8629 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8630 &deviceId,
8631 &portId);
8632 }
8633 // APM should not chose a different input or output stream for the same set of attributes
8634 // and audo configuration
8635 if (ret != NO_ERROR || io != mId) {
8636 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8637 __FUNCTION__, ret, io, mId);
8638 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008639 }
8640
8641 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008642 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008643 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008644 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008645 }
8646
Eric Laurent331679c2018-04-16 17:03:16 -07008647 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008648 // abort if start is rejected by audio policy manager
8649 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008650 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008651 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008652 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008653 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008654 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008655 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008656 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008657 }
Eric Laurent331679c2018-04-16 17:03:16 -07008658 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008659 } else {
8660 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008661 }
8662 return PERMISSION_DENIED;
8663 }
8664
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008665 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8666 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008667 isOutput(), client.clientUid, client.clientPid,
8668 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008669
Eric Laurent4eb58f12018-12-07 16:41:02 -08008670 if (isOutput()) {
8671 // force volume update when a new track is added
8672 mHalVolFloat = -1.0f;
8673 } else if (!track->isSilenced_l()) {
8674 for (const sp<MmapTrack> &t : mActiveTracks) {
8675 if (t->isSilenced_l() && t->uid() != client.clientUid)
8676 t->invalidate();
8677 }
8678 }
8679
8680
Eric Laurent6acd1d42017-01-04 14:23:29 -08008681 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008682 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008683 if (chain != 0) {
8684 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8685 chain->incTrackCnt();
8686 chain->incActiveTrackCnt();
8687 }
8688
8689 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008690 broadcast_l();
8691
Eric Laurenta54f1282017-07-01 19:39:32 -07008692 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008693
8694 return NO_ERROR;
8695}
8696
8697status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8698{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008699 ALOGV("%s handle %d", __FUNCTION__, handle);
8700
8701 if (mHalStream == 0) {
8702 return NO_INIT;
8703 }
8704
Eric Laurenta54f1282017-07-01 19:39:32 -07008705 if (handle == mPortId) {
8706 mHalStream->stop();
8707 return NO_ERROR;
8708 }
8709
Eric Laurent331679c2018-04-16 17:03:16 -07008710 Mutex::Autolock _l(mLock);
8711
Eric Laurent6acd1d42017-01-04 14:23:29 -08008712 sp<MmapTrack> track;
8713 for (const sp<MmapTrack> &t : mActiveTracks) {
8714 if (handle == t->portId()) {
8715 track = t;
8716 break;
8717 }
8718 }
8719 if (track == 0) {
8720 return BAD_VALUE;
8721 }
8722
8723 mActiveTracks.remove(track);
8724
Eric Laurent331679c2018-04-16 17:03:16 -07008725 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008726 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008727 AudioSystem::stopOutput(track->portId());
8728 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008729 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008730 AudioSystem::stopInput(track->portId());
8731 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008732 }
Eric Laurent331679c2018-04-16 17:03:16 -07008733 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008734
8735 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8736 if (chain != 0) {
8737 chain->decActiveTrackCnt();
8738 chain->decTrackCnt();
8739 }
8740
8741 broadcast_l();
8742
Eric Laurent6acd1d42017-01-04 14:23:29 -08008743 return NO_ERROR;
8744}
8745
Eric Laurent18b57012017-02-13 16:23:52 -08008746status_t AudioFlinger::MmapThread::standby()
8747{
8748 ALOGV("%s", __FUNCTION__);
8749
8750 if (mHalStream == 0) {
8751 return NO_INIT;
8752 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008753 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008754 return INVALID_OPERATION;
8755 }
8756 mHalStream->standby();
8757 mStandby = true;
8758 releaseWakeLock();
8759 return NO_ERROR;
8760}
8761
Eric Laurent6acd1d42017-01-04 14:23:29 -08008762
8763void AudioFlinger::MmapThread::readHalParameters_l()
8764{
8765 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8766 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8767 mFormat = mHALFormat;
8768 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8769 result = mHalStream->getFrameSize(&mFrameSize);
8770 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8771 result = mHalStream->getBufferSize(&mBufferSize);
8772 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8773 mFrameCount = mBufferSize / mFrameSize;
8774}
8775
8776bool AudioFlinger::MmapThread::threadLoop()
8777{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008778 checkSilentMode_l();
8779
8780 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8781
8782 while (!exitPending())
8783 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008784 Vector< sp<EffectChain> > effectChains;
8785
Andy Hung13850be2019-03-14 11:33:09 -07008786 { // under Thread lock
8787 Mutex::Autolock _l(mLock);
8788
Eric Laurent6acd1d42017-01-04 14:23:29 -08008789 if (mSignalPending) {
8790 // A signal was raised while we were unlocked
8791 mSignalPending = false;
8792 } else {
8793 if (mConfigEvents.isEmpty()) {
8794 // we're about to wait, flush the binder command buffer
8795 IPCThreadState::self()->flushCommands();
8796
8797 if (exitPending()) {
8798 break;
8799 }
8800
Eric Laurent6acd1d42017-01-04 14:23:29 -08008801 // wait until we have something to do...
8802 ALOGV("%s going to sleep", myName.string());
8803 mWaitWorkCV.wait(mLock);
8804 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008805
8806 checkSilentMode_l();
8807
8808 continue;
8809 }
8810 }
8811
8812 processConfigEvents_l();
8813
8814 processVolume_l();
8815
8816 checkInvalidTracks_l();
8817
8818 mActiveTracks.updatePowerState(this);
8819
Kevin Rocard069c2712018-03-29 19:09:14 -07008820 updateMetadata_l();
8821
Eric Laurent6acd1d42017-01-04 14:23:29 -08008822 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07008823 } // release Thread lock
8824
Eric Laurent6acd1d42017-01-04 14:23:29 -08008825 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07008826 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08008827 }
Andy Hung13850be2019-03-14 11:33:09 -07008828
8829 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008830 unlockEffectChains(effectChains);
8831 // Effect chains will be actually deleted here if they were removed from
8832 // mEffectChains list during mixing or effects processing
8833 }
8834
8835 threadLoop_exit();
8836
8837 if (!mStandby) {
8838 threadLoop_standby();
8839 mStandby = true;
8840 }
8841
Eric Laurent6acd1d42017-01-04 14:23:29 -08008842 ALOGV("Thread %p type %d exiting", this, mType);
8843 return false;
8844}
8845
8846// checkForNewParameter_l() must be called with ThreadBase::mLock held
8847bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8848 status_t& status)
8849{
8850 AudioParameter param = AudioParameter(keyValuePair);
8851 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008852 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008853 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07008854 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008855 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008856 if (sendToHal) {
8857 status = mHalStream->setParameters(keyValuePair);
8858 } else {
8859 status = NO_ERROR;
8860 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008861
8862 return false;
8863}
8864
8865String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8866{
8867 Mutex::Autolock _l(mLock);
8868 String8 out_s8;
8869 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8870 return out_s8;
8871 }
8872 return String8();
8873}
8874
Eric Laurent09f1ed22019-04-24 17:45:17 -07008875void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8876 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008877 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8878
8879 desc->mIoHandle = mId;
8880
8881 switch (event) {
8882 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008883 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008884 case AUDIO_INPUT_CONFIG_CHANGED:
8885 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008886 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008887 case AUDIO_OUTPUT_CONFIG_CHANGED:
8888 desc->mPatch = mPatch;
8889 desc->mChannelMask = mChannelMask;
8890 desc->mSamplingRate = mSampleRate;
8891 desc->mFormat = mFormat;
8892 desc->mFrameCount = mFrameCount;
8893 desc->mFrameCountHAL = mFrameCount;
8894 desc->mLatency = 0;
8895 break;
8896
8897 case AUDIO_INPUT_CLOSED:
8898 case AUDIO_OUTPUT_CLOSED:
8899 default:
8900 break;
8901 }
8902 mAudioFlinger->ioConfigChanged(event, desc, pid);
8903}
8904
8905status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8906 audio_patch_handle_t *handle)
8907{
8908 status_t status = NO_ERROR;
8909
8910 // store new device and send to effects
8911 audio_devices_t type = AUDIO_DEVICE_NONE;
8912 audio_port_handle_t deviceId;
jiabin10d86fd2019-10-31 17:20:42 -07008913 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
8914 AudioDeviceTypeAddr sourceDeviceTypeAddr;
8915 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008916 if (isOutput()) {
8917 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07008918 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
8919 && !mAudioHwDev->supportsAudioPatches(),
8920 "Enumerated device type(%#x) must not be used "
8921 "as it does not support audio patches",
8922 patch->sinks[i].ext.device.type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008923 type |= patch->sinks[i].ext.device.type;
jiabin10d86fd2019-10-31 17:20:42 -07008924 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
8925 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08008926 }
8927 deviceId = patch->sinks[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07008928 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008929 } else {
8930 type = patch->sources[0].ext.device.type;
8931 deviceId = patch->sources[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07008932 numDevices = mPatch.num_sources;
8933 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8934 sourceDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008935 }
8936
8937 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008938 if (isOutput()) {
8939 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
8940 } else {
8941 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
8942 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008943 }
8944
jiabin10d86fd2019-10-31 17:20:42 -07008945 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008946 // store new source and send to effects
8947 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8948 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8949 for (size_t i = 0; i < mEffectChains.size(); i++) {
8950 mEffectChains[i]->setAudioSource_l(mAudioSource);
8951 }
8952 }
8953 }
8954
8955 if (mAudioHwDev->supportsAudioPatches()) {
8956 status = mHalDevice->createAudioPatch(patch->num_sources,
8957 patch->sources,
8958 patch->num_sinks,
8959 patch->sinks,
8960 handle);
8961 } else {
8962 char *address;
8963 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8964 //FIXME: we only support address on first sink with HAL version < 3.0
8965 address = audio_device_address_to_parameter(
8966 patch->sinks[0].ext.device.type,
8967 patch->sinks[0].ext.device.address);
8968 } else {
8969 address = (char *)calloc(1, 1);
8970 }
8971 AudioParameter param = AudioParameter(String8(address));
8972 free(address);
8973 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8974 if (!isOutput()) {
8975 param.addInt(String8(AudioParameter::keyInputSource),
8976 (int)patch->sinks[0].ext.mix.usecase.source);
8977 }
8978 status = mHalStream->setParameters(param.toString());
8979 *handle = AUDIO_PATCH_HANDLE_NONE;
8980 }
8981
jiabin10d86fd2019-10-31 17:20:42 -07008982 if (numDevices == 0 || mDeviceId != deviceId) {
8983 if (isOutput()) {
8984 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
8985 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
8986 } else {
8987 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8988 mInDeviceTypeAddr = sourceDeviceTypeAddr;
8989 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08008990 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008991 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008992 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008993 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008994 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008995 }
jiabin10d86fd2019-10-31 17:20:42 -07008996 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008997 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008998 }
8999 return status;
9000}
9001
9002status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9003{
9004 status_t status = NO_ERROR;
9005
jiabin10d86fd2019-10-31 17:20:42 -07009006 mPatch = audio_patch{};
9007 mOutDeviceTypeAddrs.clear();
9008 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009009
9010 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9011 supportsAudioPatches : false;
9012
9013 if (supportsAudioPatches) {
9014 status = mHalDevice->releaseAudioPatch(handle);
9015 } else {
9016 AudioParameter param;
9017 param.addInt(String8(AudioParameter::keyRouting), 0);
9018 status = mHalStream->setParameters(param.toString());
9019 }
9020 return status;
9021}
9022
Mikhail Naganovdc769682018-05-04 15:34:08 -07009023void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009024{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009025 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009026 if (isOutput()) {
9027 config->role = AUDIO_PORT_ROLE_SOURCE;
9028 config->ext.mix.hw_module = mAudioHwDev->handle();
9029 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9030 } else {
9031 config->role = AUDIO_PORT_ROLE_SINK;
9032 config->ext.mix.hw_module = mAudioHwDev->handle();
9033 config->ext.mix.usecase.source = mAudioSource;
9034 }
9035}
9036
9037status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9038{
9039 audio_session_t session = chain->sessionId();
9040
9041 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9042 // Attach all tracks with same session ID to this chain.
9043 // indicate all active tracks in the chain
9044 for (const sp<MmapTrack> &track : mActiveTracks) {
9045 if (session == track->sessionId()) {
9046 chain->incTrackCnt();
9047 chain->incActiveTrackCnt();
9048 }
9049 }
9050
9051 chain->setThread(this);
9052 chain->setInBuffer(nullptr);
9053 chain->setOutBuffer(nullptr);
9054 chain->syncHalEffectsState();
9055
9056 mEffectChains.add(chain);
9057 checkSuspendOnAddEffectChain_l(chain);
9058 return NO_ERROR;
9059}
9060
9061size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9062{
9063 audio_session_t session = chain->sessionId();
9064
9065 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9066
9067 for (size_t i = 0; i < mEffectChains.size(); i++) {
9068 if (chain == mEffectChains[i]) {
9069 mEffectChains.removeAt(i);
9070 // detach all active tracks from the chain
9071 // detach all tracks with same session ID from this chain
9072 for (const sp<MmapTrack> &track : mActiveTracks) {
9073 if (session == track->sessionId()) {
9074 chain->decActiveTrackCnt();
9075 chain->decTrackCnt();
9076 }
9077 }
9078 break;
9079 }
9080 }
9081 return mEffectChains.size();
9082}
9083
Eric Laurent6acd1d42017-01-04 14:23:29 -08009084void AudioFlinger::MmapThread::threadLoop_standby()
9085{
9086 mHalStream->standby();
9087}
9088
9089void AudioFlinger::MmapThread::threadLoop_exit()
9090{
Phil Burk7dce7282017-09-27 13:51:41 -07009091 // Do not call callback->onTearDown() because it is redundant for thread exit
9092 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009093}
9094
9095status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9096{
9097 return BAD_VALUE;
9098}
9099
9100bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9101{
9102 return false;
9103}
9104
9105status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9106 const effect_descriptor_t *desc, audio_session_t sessionId)
9107{
9108 // No global effect sessions on mmap threads
Eric Laurenta20c4e92019-11-12 15:55:51 -08009109 if (audio_is_global_session(sessionId)) {
9110 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009111 desc->name, mThreadName);
9112 return BAD_VALUE;
9113 }
9114
9115 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9116 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9117 desc->name);
9118 return BAD_VALUE;
9119 }
9120 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009121 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9122 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009123 return BAD_VALUE;
9124 }
9125
9126 // Only allow effects without processing load or latency
9127 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9128 return BAD_VALUE;
9129 }
9130
9131 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009132}
9133
9134void AudioFlinger::MmapThread::checkInvalidTracks_l()
9135{
9136 for (const sp<MmapTrack> &track : mActiveTracks) {
9137 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009138 sp<MmapStreamCallback> callback = mCallback.promote();
9139 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009140 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009141 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009142 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009143 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9144 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9145 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009146 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009147 }
9148 }
9149}
9150
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009151void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009152{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009153 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9154 mAttr.content_type, mAttr.usage, mAttr.source);
9155 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009156 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009157 dprintf(fd, " No active clients\n");
9158 }
9159}
9160
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009161void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009162{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009163 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009164 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009165 dprintf(fd, " %zu Tracks\n", numtracks);
9166 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009167 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009168 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009169 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009170 for (size_t i = 0; i < numtracks ; ++i) {
9171 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009172 result.append(prefix);
9173 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009174 }
9175 } else {
9176 dprintf(fd, "\n");
9177 }
9178 write(fd, result.string(), result.size());
9179}
9180
9181AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9182 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009183 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
9184 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009185 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009186 mStreamVolume(1.0),
9187 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009188 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009189{
9190 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9191 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9192 mMasterVolume = audioFlinger->masterVolume_l();
9193 mMasterMute = audioFlinger->masterMute_l();
9194 if (mAudioHwDev) {
9195 if (mAudioHwDev->canSetMasterVolume()) {
9196 mMasterVolume = 1.0;
9197 }
9198
9199 if (mAudioHwDev->canSetMasterMute()) {
9200 mMasterMute = false;
9201 }
9202 }
9203}
9204
9205void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9206 audio_stream_type_t streamType,
9207 audio_session_t sessionId,
9208 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009209 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009210 audio_port_handle_t portId)
9211{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009212 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009213 mStreamType = streamType;
9214}
9215
9216AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9217{
9218 Mutex::Autolock _l(mLock);
9219 AudioStreamOut *output = mOutput;
9220 mOutput = NULL;
9221 return output;
9222}
9223
9224void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9225{
9226 Mutex::Autolock _l(mLock);
9227 // Don't apply master volume in SW if our HAL can do it for us.
9228 if (mAudioHwDev &&
9229 mAudioHwDev->canSetMasterVolume()) {
9230 mMasterVolume = 1.0;
9231 } else {
9232 mMasterVolume = value;
9233 }
9234}
9235
9236void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9237{
9238 Mutex::Autolock _l(mLock);
9239 // Don't apply master mute in SW if our HAL can do it for us.
9240 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9241 mMasterMute = false;
9242 } else {
9243 mMasterMute = muted;
9244 }
9245}
9246
9247void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9248{
9249 Mutex::Autolock _l(mLock);
9250 if (stream == mStreamType) {
9251 mStreamVolume = value;
9252 broadcast_l();
9253 }
9254}
9255
9256float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9257{
9258 Mutex::Autolock _l(mLock);
9259 if (stream == mStreamType) {
9260 return mStreamVolume;
9261 }
9262 return 0.0f;
9263}
9264
9265void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9266{
9267 Mutex::Autolock _l(mLock);
9268 if (stream == mStreamType) {
9269 mStreamMute= muted;
9270 broadcast_l();
9271 }
9272}
9273
9274void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9275{
9276 Mutex::Autolock _l(mLock);
9277 if (streamType == mStreamType) {
9278 for (const sp<MmapTrack> &track : mActiveTracks) {
9279 track->invalidate();
9280 }
9281 broadcast_l();
9282 }
9283}
9284
9285void AudioFlinger::MmapPlaybackThread::processVolume_l()
9286{
9287 float volume;
9288
9289 if (mMasterMute || mStreamMute) {
9290 volume = 0;
9291 } else {
9292 volume = mMasterVolume * mStreamVolume;
9293 }
9294
9295 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009296
9297 // Convert volumes from float to 8.24
9298 uint32_t vol = (uint32_t)(volume * (1 << 24));
9299
9300 // Delegate volume control to effect in track effect chain if needed
9301 // only one effect chain can be present on DirectOutputThread, so if
9302 // there is one, the track is connected to it
9303 if (!mEffectChains.isEmpty()) {
9304 mEffectChains[0]->setVolume_l(&vol, &vol);
9305 volume = (float)vol / (1 << 24);
9306 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009307 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009308 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9309 mHalVolFloat = volume; // HW volume control worked, so update value.
9310 mNoCallbackWarningCount = 0;
9311 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009312 sp<MmapStreamCallback> callback = mCallback.promote();
9313 if (callback != 0) {
9314 int channelCount;
9315 if (isOutput()) {
9316 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9317 } else {
9318 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9319 }
9320 Vector<float> values;
9321 for (int i = 0; i < channelCount; i++) {
9322 values.add(volume);
9323 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009324 mHalVolFloat = volume; // SW volume control worked, so update value.
9325 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009326 mLock.unlock();
9327 callback->onVolumeChanged(mChannelMask, values);
9328 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009329 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009330 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9331 ALOGW("Could not set MMAP stream volume: no volume callback!");
9332 mNoCallbackWarningCount++;
9333 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009334 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009335 }
9336 }
9337}
9338
Kevin Rocard069c2712018-03-29 19:09:14 -07009339void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9340{
9341 if (mOutput == nullptr || mOutput->stream == nullptr ||
9342 !mActiveTracks.readAndClearHasChanged()) {
9343 return;
9344 }
9345 StreamOutHalInterface::SourceMetadata metadata;
9346 for (const sp<MmapTrack> &track : mActiveTracks) {
9347 // No track is invalid as this is called after prepareTrack_l in the same critical section
9348 metadata.tracks.push_back({
9349 .usage = track->attributes().usage,
9350 .content_type = track->attributes().content_type,
9351 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9352 });
9353 }
9354 mOutput->stream->updateSourceMetadata(metadata);
9355}
9356
Eric Laurent6acd1d42017-01-04 14:23:29 -08009357void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9358{
9359 if (!mMasterMute) {
9360 char value[PROPERTY_VALUE_MAX];
9361 if (property_get("ro.audio.silent", value, "0") > 0) {
9362 char *endptr;
9363 unsigned long ul = strtoul(value, &endptr, 0);
9364 if (*endptr == '\0' && ul != 0) {
9365 ALOGD("Silence is golden");
9366 // The setprop command will not allow a property to be changed after
9367 // the first time it is set, so we don't have to worry about un-muting.
9368 setMasterMute_l(true);
9369 }
9370 }
9371 }
9372}
9373
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009374void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9375{
9376 MmapThread::toAudioPortConfig(config);
9377 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9378 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9379 config->flags.output = mOutput->flags;
9380 }
9381}
9382
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009383void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009384{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009385 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009386
Glenn Kastend3bb6452016-12-05 18:14:37 -08009387 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9388 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009389 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9390}
9391
9392AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9393 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009394 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
9395 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009396 mInput(input)
9397{
9398 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9399 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9400}
9401
Eric Laurent331679c2018-04-16 17:03:16 -07009402status_t AudioFlinger::MmapCaptureThread::exitStandby()
9403{
Phil Burkf054fc32018-12-06 09:45:59 -08009404 {
9405 // mInput might have been cleared by clearInput()
9406 Mutex::Autolock _l(mLock);
9407 if (mInput != nullptr && mInput->stream != nullptr) {
9408 mInput->stream->setGain(1.0f);
9409 }
9410 }
Eric Laurent331679c2018-04-16 17:03:16 -07009411 return MmapThread::exitStandby();
9412}
9413
Eric Laurent6acd1d42017-01-04 14:23:29 -08009414AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9415{
9416 Mutex::Autolock _l(mLock);
9417 AudioStreamIn *input = mInput;
9418 mInput = NULL;
9419 return input;
9420}
Kevin Rocard069c2712018-03-29 19:09:14 -07009421
Eric Laurent331679c2018-04-16 17:03:16 -07009422
9423void AudioFlinger::MmapCaptureThread::processVolume_l()
9424{
9425 bool changed = false;
9426 bool silenced = false;
9427
9428 sp<MmapStreamCallback> callback = mCallback.promote();
9429 if (callback == 0) {
9430 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9431 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9432 mNoCallbackWarningCount++;
9433 }
9434 }
9435
9436 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9437 // track is silenced and unmute otherwise
9438 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9439 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9440 changed = true;
9441 silenced = mActiveTracks[i]->isSilenced_l();
9442 }
9443 }
9444
9445 if (changed) {
9446 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9447 }
9448}
9449
Kevin Rocard069c2712018-03-29 19:09:14 -07009450void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9451{
9452 if (mInput == nullptr || mInput->stream == nullptr ||
9453 !mActiveTracks.readAndClearHasChanged()) {
9454 return;
9455 }
9456 StreamInHalInterface::SinkMetadata metadata;
9457 for (const sp<MmapTrack> &track : mActiveTracks) {
9458 // No track is invalid as this is called after prepareTrack_l in the same critical section
9459 metadata.tracks.push_back({
9460 .source = track->attributes().source,
9461 .gain = 1, // capture tracks do not have volumes
9462 });
9463 }
9464 mInput->stream->updateSinkMetadata(metadata);
9465}
9466
Eric Laurent331679c2018-04-16 17:03:16 -07009467void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9468{
9469 Mutex::Autolock _l(mLock);
9470 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9471 if (mActiveTracks[i]->uid() == uid) {
9472 mActiveTracks[i]->setSilenced_l(silenced);
9473 broadcast_l();
9474 }
9475 }
9476}
9477
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009478void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9479{
9480 MmapThread::toAudioPortConfig(config);
9481 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9482 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9483 config->flags.input = mInput->flags;
9484 }
9485}
9486
Glenn Kasten63238ef2015-03-02 15:50:29 -08009487} // namespace android