blob: fddd3de8b07291feba831ffa8d568640c3ff03a5 [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>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020054#include <system/audio_effects/effect_downmix.h>
55#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020056#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070057#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080058
59// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080061#include <media/nbaio/AudioStreamOutSink.h>
62#include <media/nbaio/MonoPipe.h>
63#include <media/nbaio/MonoPipeReader.h>
64#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
66#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068
Mikhail Naganov2996f672019-04-18 12:29:59 -070069#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070#include <powermanager/PowerManager.h>
71
Kevin Rocard7588ff42018-01-08 11:11:30 -080072#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070073#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080074
Eric Laurent81784c32012-11-19 14:55:58 -080075#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080076#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070077#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070078#include <mediautils/SchedulingPolicyService.h>
79#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080080
Eric Laurent81784c32012-11-19 14:55:58 -080081#ifdef ADD_BATTERY_DATA
82#include <media/IMediaPlayerService.h>
83#include <media/IMediaDeathNotifier.h>
84#endif
85
Eric Laurent81784c32012-11-19 14:55:58 -080086#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070087#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080088#include <cpustats/ThreadCpuUsage.h>
89#endif
90
Glenn Kastenc05b8d72016-03-24 09:48:17 -070091#include "AutoPark.h"
92
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080093#include <pthread.h>
94#include "TypedLogger.h"
95
Eric Laurent81784c32012-11-19 14:55:58 -080096// ----------------------------------------------------------------------------
97
98// Note: the following macro is used for extremely verbose logging message. In
99// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
100// 0; but one side effect of this is to turn all LOGV's as well. Some messages
101// are so verbose that we want to suppress them even when we have ALOG_ASSERT
102// turned on. Do not uncomment the #def below unless you really know what you
103// are doing and want to see all of the extremely verbose messages.
104//#define VERY_VERY_VERBOSE_LOGGING
105#ifdef VERY_VERY_VERBOSE_LOGGING
106#define ALOGVV ALOGV
107#else
108#define ALOGVV(a...) do { } while(0)
109#endif
110
Andy Hung6770c6f2015-04-07 13:43:36 -0700111// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700112#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700113
Andy Hung6770c6f2015-04-07 13:43:36 -0700114template <typename T>
115static inline T min(const T& a, const T& b)
116{
117 return a < b ? a : b;
118}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700119
Eric Laurent81784c32012-11-19 14:55:58 -0800120namespace android {
121
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700122using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000123using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700124
Eric Laurent81784c32012-11-19 14:55:58 -0800125// retry counts for buffer fill timeout
126// 50 * ~20msecs = 1 second
127static const int8_t kMaxTrackRetries = 50;
128static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// allow less retry attempts on direct output thread.
131// direct outputs can be a scarce resource in audio hardware and should
132// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700133// Notes:
134// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
135// in case the data write is bursty for the AudioTrack. The application
136// should endeavor to write at least once every kMaxTrackRetriesDirectMs
137// to prevent an underrun situation. If the data is bursty, then
138// the application can also throttle the data sent to be even.
139// 2) For compressed audio data, any data present in the AudioTrack buffer
140// will be sent and reset the retry count. This delivers data as
141// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
142// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
143// of data to be available, then any remaining data is delivered.
144// This is required to ensure the last bit of data is delivered before underrun.
145//
146// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
147// or the size of the HAL period for proportional / linear PCM tracks.
148static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800149
150// don't warn about blocked writes or record buffer overflows more often than this
151static const nsecs_t kWarningThrottleNs = seconds(5);
152
153// RecordThread loop sleep time upon application overrun or audio HAL read error
154static const int kRecordThreadSleepUs = 5000;
155
Eric Laurent10351942014-05-08 18:49:52 -0700156// maximum time to wait in sendConfigEvent_l() for a status to be received
157static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800158
159// minimum sleep time for the mixer thread loop when tracks are active but in underrun
160static const uint32_t kMinThreadSleepTimeUs = 5000;
161// maximum divider applied to the active sleep time in the mixer thread loop
162static const uint32_t kMaxThreadSleepTimeShift = 2;
163
Andy Hung09a50072014-02-27 14:30:47 -0800164// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700165// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800166static const uint32_t kMinNormalSinkBufferSizeMs = 20;
167// maximum normal sink buffer size
168static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800169
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
171// FIXME This should be based on experimentally observed scheduling jitter
172static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
173
Eric Laurent972a1732013-09-04 09:42:59 -0700174// Offloaded output thread standby delay: allows track transition without going to standby
175static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
176
Eric Laurent51716182016-02-29 18:00:56 -0800177// Direct output thread minimum sleep time in idle or active(underrun) state
178static const nsecs_t kDirectMinSleepTimeUs = 10000;
179
Glenn Kasten1b291842016-07-18 14:55:21 -0700180// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
181// balance between power consumption and latency, and allows threads to be scheduled reliably
182// by the CFS scheduler.
183// FIXME Express other hardcoded references to 20ms with references to this constant and move
184// it appropriately.
185#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800186
Eric Laurent81784c32012-11-19 14:55:58 -0800187// Whether to use fast mixer
188static const enum {
189 FastMixer_Never, // never initialize or use: for debugging only
190 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
191 // normal mixer multiplier is 1
192 FastMixer_Static, // initialize if needed, then use all the time if initialized,
193 // multiplier is calculated based on min & max normal mixer buffer size
194 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
195 // multiplier is calculated based on min & max normal mixer buffer size
196 // FIXME for FastMixer_Dynamic:
197 // Supporting this option will require fixing HALs that can't handle large writes.
198 // For example, one HAL implementation returns an error from a large write,
199 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
200 // We could either fix the HAL implementations, or provide a wrapper that breaks
201 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
202} kUseFastMixer = FastMixer_Static;
203
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700204// Whether to use fast capture
205static const enum {
206 FastCapture_Never, // never initialize or use: for debugging only
207 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
208 FastCapture_Static, // initialize if needed, then use all the time if initialized
209} kUseFastCapture = FastCapture_Static;
210
Eric Laurent81784c32012-11-19 14:55:58 -0800211// Priorities for requestPriority
212static const int kPriorityAudioApp = 2;
213static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800215
Glenn Kastenea38ee72016-04-18 11:08:01 -0700216// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
217// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
218// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700219
220// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800221static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800222
Glenn Kasten03490092014-05-27 12:30:54 -0700223// The minimum and maximum allowed values
224static const int kFastTrackMultiplierMin = 1;
225static const int kFastTrackMultiplierMax = 2;
226
227// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
228static int sFastTrackMultiplier = kFastTrackMultiplier;
229
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700230// See Thread::readOnlyHeap().
231// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
232// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
233// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700234static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700235
Eric Laurent81784c32012-11-19 14:55:58 -0800236// ----------------------------------------------------------------------------
237
Andy Hungb68f5eb2019-12-03 16:49:17 -0800238// TODO: move all toString helpers to audio.h
239// under #ifdef __cplusplus #endif
240static std::string patchSinksToString(const struct audio_patch *patch)
241{
242 std::stringstream ss;
243 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700244 if (i > 0) {
245 ss << "|";
246 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800247 ss << "(" << toString(patch->sinks[i].ext.device.type)
248 << ", " << patch->sinks[i].ext.device.address << ")";
249 }
250 return ss.str();
251}
252
253static std::string patchSourcesToString(const struct audio_patch *patch)
254{
255 std::stringstream ss;
256 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700257 if (i > 0) {
258 ss << "|";
259 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800260 ss << "(" << toString(patch->sources[i].ext.device.type)
261 << ", " << patch->sources[i].ext.device.address << ")";
262 }
263 return ss.str();
264}
265
Glenn Kasten03490092014-05-27 12:30:54 -0700266static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
267
268static void sFastTrackMultiplierInit()
269{
270 char value[PROPERTY_VALUE_MAX];
271 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
272 char *endptr;
273 unsigned long ul = strtoul(value, &endptr, 0);
274 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
275 sFastTrackMultiplier = (int) ul;
276 }
277 }
278}
279
280// ----------------------------------------------------------------------------
281
Eric Laurent81784c32012-11-19 14:55:58 -0800282#ifdef ADD_BATTERY_DATA
283// To collect the amplifier usage
284static void addBatteryData(uint32_t params) {
285 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
286 if (service == NULL) {
287 // it already logged
288 return;
289 }
290
291 service->addBatteryData(params);
292}
293#endif
294
Andy Hung3f0c9022016-01-15 17:49:46 -0800295// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
296struct {
297 // call when you acquire a partial wakelock
298 void acquire(const sp<IBinder> &wakeLockToken) {
299 pthread_mutex_lock(&mLock);
300 if (wakeLockToken.get() == nullptr) {
301 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
302 } else {
303 if (mCount == 0) {
304 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
305 }
306 ++mCount;
307 }
308 pthread_mutex_unlock(&mLock);
309 }
310
311 // call when you release a partial wakelock.
312 void release(const sp<IBinder> &wakeLockToken) {
313 if (wakeLockToken.get() == nullptr) {
314 return;
315 }
316 pthread_mutex_lock(&mLock);
317 if (--mCount < 0) {
318 ALOGE("negative wakelock count");
319 mCount = 0;
320 }
321 pthread_mutex_unlock(&mLock);
322 }
323
324 // retrieves the boottime timebase offset from monotonic.
325 int64_t getBoottimeOffset() {
326 pthread_mutex_lock(&mLock);
327 int64_t boottimeOffset = mBoottimeOffset;
328 pthread_mutex_unlock(&mLock);
329 return boottimeOffset;
330 }
331
332 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
333 // and the selected timebase.
334 // Currently only TIMEBASE_BOOTTIME is allowed.
335 //
336 // This only needs to be called upon acquiring the first partial wakelock
337 // after all other partial wakelocks are released.
338 //
339 // We do an empirical measurement of the offset rather than parsing
340 // /proc/timer_list since the latter is not a formal kernel ABI.
341 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
342 int clockbase;
343 switch (timebase) {
344 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
345 clockbase = SYSTEM_TIME_BOOTTIME;
346 break;
347 default:
348 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
349 break;
350 }
351 // try three times to get the clock offset, choose the one
352 // with the minimum gap in measurements.
353 const int tries = 3;
354 nsecs_t bestGap, measured;
355 for (int i = 0; i < tries; ++i) {
356 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
357 const nsecs_t tbase = systemTime(clockbase);
358 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
359 const nsecs_t gap = tmono2 - tmono;
360 if (i == 0 || gap < bestGap) {
361 bestGap = gap;
362 measured = tbase - ((tmono + tmono2) >> 1);
363 }
364 }
365
366 // to avoid micro-adjusting, we don't change the timebase
367 // unless it is significantly different.
368 //
369 // Assumption: It probably takes more than toleranceNs to
370 // suspend and resume the device.
371 static int64_t toleranceNs = 10000; // 10 us
372 if (llabs(*offset - measured) > toleranceNs) {
373 ALOGV("Adjusting timebase offset old: %lld new: %lld",
374 (long long)*offset, (long long)measured);
375 *offset = measured;
376 }
377 }
378
379 pthread_mutex_t mLock;
380 int32_t mCount;
381 int64_t mBoottimeOffset;
382} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800383
384// ----------------------------------------------------------------------------
385// CPU Stats
386// ----------------------------------------------------------------------------
387
388class CpuStats {
389public:
390 CpuStats();
391 void sample(const String8 &title);
392#ifdef DEBUG_CPU_USAGE
393private:
394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700395 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800396
Andy Hung16698b82018-08-01 10:48:38 -0700397 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800398
399 int mCpuNum; // thread's current CPU number
400 int mCpukHz; // frequency of thread's current CPU in kHz
401#endif
402};
403
404CpuStats::CpuStats()
405#ifdef DEBUG_CPU_USAGE
406 : mCpuNum(-1), mCpukHz(-1)
407#endif
408{
409}
410
Glenn Kasten0f11b512014-01-31 16:18:54 -0800411void CpuStats::sample(const String8 &title
412#ifndef DEBUG_CPU_USAGE
413 __unused
414#endif
415 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800416#ifdef DEBUG_CPU_USAGE
417 // get current thread's delta CPU time in wall clock ns
418 double wcNs;
419 bool valid = mCpuUsage.sampleAndEnable(wcNs);
420
421 // record sample for wall clock statistics
422 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700423 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800424 }
425
426 // get the current CPU number
427 int cpuNum = sched_getcpu();
428
429 // get the current CPU frequency in kHz
430 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
431
432 // check if either CPU number or frequency changed
433 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
434 mCpuNum = cpuNum;
435 mCpukHz = cpukHz;
436 // ignore sample for purposes of cycles
437 valid = false;
438 }
439
440 // if no change in CPU number or frequency, then record sample for cycle statistics
441 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700442 const double cycles = wcNs * cpukHz * 0.000001;
443 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800444 }
445
Eric Tan5b13ff82018-07-27 11:20:17 -0700446 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800447 // mCpuUsage.elapsed() is expensive, so don't call it every loop
448 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800450 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700451 const double perLoop = elapsed / (double) n;
452 const double perLoop100 = perLoop * 0.01;
453 const double perLoop1k = perLoop * 0.001;
454 const double mean = mWcStats.getMean();
455 const double stddev = mWcStats.getStdDev();
456 const double minimum = mWcStats.getMin();
457 const double maximum = mWcStats.getMax();
458 const double meanCycles = mHzStats.getMean();
459 const double stddevCycles = mHzStats.getStdDev();
460 const double minCycles = mHzStats.getMin();
461 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800462 mCpuUsage.resetElapsed();
463 mWcStats.reset();
464 mHzStats.reset();
465 ALOGD("CPU usage for %s over past %.1f secs\n"
466 " (%u mixer loops at %.1f mean ms per loop):\n"
467 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
468 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
469 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
470 title.string(),
471 elapsed * .000000001, n, perLoop * .000001,
472 mean * .001,
473 stddev * .001,
474 minimum * .001,
475 maximum * .001,
476 mean / perLoop100,
477 stddev / perLoop100,
478 minimum / perLoop100,
479 maximum / perLoop100,
480 meanCycles / perLoop1k,
481 stddevCycles / perLoop1k,
482 minCycles / perLoop1k,
483 maxCycles / perLoop1k);
484
485 }
486 }
487#endif
488};
489
490// ----------------------------------------------------------------------------
491// ThreadBase
492// ----------------------------------------------------------------------------
493
Glenn Kasten97b7b752014-09-28 13:04:24 -0700494// static
495const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
496{
497 switch (type) {
498 case MIXER:
499 return "MIXER";
500 case DIRECT:
501 return "DIRECT";
502 case DUPLICATING:
503 return "DUPLICATING";
504 case RECORD:
505 return "RECORD";
506 case OFFLOAD:
507 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700508 case MMAP_PLAYBACK:
509 return "MMAP_PLAYBACK";
510 case MMAP_CAPTURE:
511 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200512 case SPATIALIZER:
513 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700514 default:
515 return "unknown";
516 }
517}
518
Eric Laurent81784c32012-11-19 14:55:58 -0800519AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700520 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800521 : Thread(false /*canCallJava*/),
522 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700523 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700524 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
525 isOut),
526 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700527 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800528 // are set by PlaybackThread::readOutputParameters_l() or
529 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700530 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700531 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700532 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800533 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700534 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800535 mSystemReady(systemReady),
536 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800537{
Andy Hungcf10d742020-04-28 15:38:24 -0700538 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700539 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800540}
541
542AudioFlinger::ThreadBase::~ThreadBase()
543{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700544 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700545 mConfigEvents.clear();
546
Eric Laurent81784c32012-11-19 14:55:58 -0800547 // do not lock the mutex in destructor
548 releaseWakeLock_l();
549 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800550 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800551 binder->unlinkToDeath(mDeathRecipient);
552 }
Andy Hungd0979812019-02-21 15:51:44 -0800553
554 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800555}
556
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700557status_t AudioFlinger::ThreadBase::readyToRun()
558{
559 status_t status = initCheck();
560 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800561 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700562 } else {
563 ALOGE("No working audio driver found.");
564 }
565 return status;
566}
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568void AudioFlinger::ThreadBase::exit()
569{
570 ALOGV("ThreadBase::exit");
571 // do any cleanup required for exit to succeed
572 preExit();
573 {
574 // This lock prevents the following race in thread (uniprocessor for illustration):
575 // if (!exitPending()) {
576 // // context switch from here to exit()
577 // // exit() calls requestExit(), what exitPending() observes
578 // // exit() calls signal(), which is dropped since no waiters
579 // // context switch back from exit() to here
580 // mWaitWorkCV.wait(...);
581 // // now thread is hung
582 // }
583 AutoMutex lock(mLock);
584 requestExit();
585 mWaitWorkCV.broadcast();
586 }
587 // When Thread::requestExitAndWait is made virtual and this method is renamed to
588 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
589 requestExitAndWait();
590}
591
592status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
593{
Eric Laurent81784c32012-11-19 14:55:58 -0800594 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
595 Mutex::Autolock _l(mLock);
596
Eric Laurent10351942014-05-08 18:49:52 -0700597 return sendSetParameterConfigEvent_l(keyValuePairs);
598}
599
600// sendConfigEvent_l() must be called with ThreadBase::mLock held
601// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
602status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
603{
604 status_t status = NO_ERROR;
605
Eric Laurent72e3f392015-05-20 14:43:50 -0700606 if (event->mRequiresSystemReady && !mSystemReady) {
607 event->mWaitStatus = false;
608 mPendingConfigEvents.add(event);
609 return status;
610 }
Eric Laurent10351942014-05-08 18:49:52 -0700611 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700612 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800613 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700614 mLock.unlock();
615 {
616 Mutex::Autolock _l(event->mLock);
617 while (event->mWaitStatus) {
618 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
619 event->mStatus = TIMED_OUT;
620 event->mWaitStatus = false;
621 }
622 }
623 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800624 }
Eric Laurent10351942014-05-08 18:49:52 -0700625 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800626 return status;
627}
628
Eric Laurent09f1ed22019-04-24 17:45:17 -0700629void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
630 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
632 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700633 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800634}
635
636// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700637void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
638 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800639{
Andy Hungd0979812019-02-21 15:51:44 -0800640 // The audio statistics history is exponentially weighted to forget events
641 // about five or more seconds in the past. In order to have
642 // crisper statistics for mediametrics, we reset the statistics on
643 // an IoConfigEvent, to reflect different properties for a new device.
644 mIoJitterMs.reset();
645 mLatencyMs.reset();
646 mProcessTimeMs.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100647 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800648
Eric Laurent09f1ed22019-04-24 17:45:17 -0700649 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700650 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800651}
652
Mikhail Naganov83f04272017-02-07 10:45:09 -0800653void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700654{
655 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800656 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700657}
658
Eric Laurent81784c32012-11-19 14:55:58 -0800659// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800660void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
661 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800662{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800663 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700664 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800665}
666
Eric Laurent10351942014-05-08 18:49:52 -0700667// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
668status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800669{
Andy Hung2ddee192015-12-18 17:34:44 -0800670 sp<ConfigEvent> configEvent;
671 AudioParameter param(keyValuePair);
672 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700673 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800674 setMasterMono_l(value != 0);
675 if (param.size() == 1) {
676 return NO_ERROR; // should be a solo parameter - we don't pass down
677 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700678 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800679 configEvent = new SetParameterConfigEvent(param.toString());
680 } else {
681 configEvent = new SetParameterConfigEvent(keyValuePair);
682 }
Eric Laurent10351942014-05-08 18:49:52 -0700683 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700684}
685
Eric Laurent1c333e22014-05-20 10:48:17 -0700686status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
687 const struct audio_patch *patch,
688 audio_patch_handle_t *handle)
689{
690 Mutex::Autolock _l(mLock);
691 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
692 status_t status = sendConfigEvent_l(configEvent);
693 if (status == NO_ERROR) {
694 CreateAudioPatchConfigEventData *data =
695 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
696 *handle = data->mHandle;
697 }
698 return status;
699}
700
701status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
702 const audio_patch_handle_t handle)
703{
704 Mutex::Autolock _l(mLock);
705 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
706 return sendConfigEvent_l(configEvent);
707}
708
jiabinc52b1ff2019-10-31 17:20:42 -0700709status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
710 const DeviceDescriptorBaseVector& outDevices)
711{
712 if (type() != RECORD) {
713 // The update out device operation is only for record thread.
714 return INVALID_OPERATION;
715 }
716 Mutex::Autolock _l(mLock);
717 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
718 return sendConfigEvent_l(configEvent);
719}
720
Eric Laurentec376dc2021-04-08 20:41:22 +0200721void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
722{
723 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
724 sp<ConfigEvent> configEvent =
725 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
726 sendConfigEvent_l(configEvent);
727}
Eric Laurent1c333e22014-05-20 10:48:17 -0700728
Eric Laurentb3f315a2021-07-13 15:09:05 +0200729void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
730{
731 Mutex::Autolock _l(mLock);
732 sendCheckOutputStageEffectsEvent_l();
733}
734
735void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
736{
737 sp<ConfigEvent> configEvent =
738 (ConfigEvent *)new CheckOutputStageEffectsEvent();
739 sendConfigEvent_l(configEvent);
740}
741
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700742// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700743void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700744{
Eric Laurent10351942014-05-08 18:49:52 -0700745 bool configChanged = false;
746
Eric Laurent81784c32012-11-19 14:55:58 -0800747 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700748 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700749 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800750 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700751 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700752 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700753 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
754 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800755 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700756 true /*asynchronous*/);
757 if (err != 0) {
758 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700759 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700760 }
761 } break;
762 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700763 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700764 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700765 } break;
766 case CFG_EVENT_SET_PARAMETER: {
767 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
768 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
769 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700770 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
771 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700772 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700773 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700774 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700775 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700776 CreateAudioPatchConfigEventData *data =
777 (CreateAudioPatchConfigEventData *)event->mData.get();
778 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700779 const DeviceTypeSet newDevices = getDeviceTypes();
780 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
781 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
782 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700783 } break;
784 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700785 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700786 ReleaseAudioPatchConfigEventData *data =
787 (ReleaseAudioPatchConfigEventData *)event->mData.get();
788 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700789 const DeviceTypeSet newDevices = getDeviceTypes();
790 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
791 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
792 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
793 } break;
794 case CFG_EVENT_UPDATE_OUT_DEVICE: {
795 UpdateOutDevicesConfigEventData *data =
796 (UpdateOutDevicesConfigEventData *)event->mData.get();
797 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700798 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200799 case CFG_EVENT_RESIZE_BUFFER: {
800 ResizeBufferConfigEventData *data =
801 (ResizeBufferConfigEventData *)event->mData.get();
802 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
803 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200804
805 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
806 setCheckOutputStageEffects();
807 } break;
808
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700809 default:
Eric Laurent10351942014-05-08 18:49:52 -0700810 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700811 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800812 }
Eric Laurent10351942014-05-08 18:49:52 -0700813 {
814 Mutex::Autolock _l(event->mLock);
815 if (event->mWaitStatus) {
816 event->mWaitStatus = false;
817 event->mCond.signal();
818 }
819 }
820 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
821 }
822
823 if (configChanged) {
824 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800825 }
Eric Laurent81784c32012-11-19 14:55:58 -0800826}
827
Marco Nelissenb2208842014-02-07 14:00:50 -0800828String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
829 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700830 const audio_channel_representation_t representation =
831 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700832
833 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800834 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700835 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
836 if (output) {
837 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
838 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
839 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700840 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700841 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
842 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
843 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
844 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
845 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
846 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
847 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
848 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
849 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
850 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
851 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
852 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700853 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
854 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
855 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
856 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
857 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
858 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
859 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700860 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700861 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
862 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700863 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
864 } else {
865 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
866 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
867 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
868 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
869 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
870 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
871 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
872 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
873 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
874 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
875 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
876 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700877 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
878 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
879 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700880 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700881 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
882 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700883 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
884 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
885 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
886 }
887 const int len = s.length();
888 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700889 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700890 s.unlockBuffer(len - 2); // remove trailing ", "
891 }
892 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800893 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700894 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
895 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
896 return s;
897 default:
898 s.appendFormat("unknown mask, representation:%d bits:%#x",
899 representation, audio_channel_mask_get_bits(mask));
900 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800901 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800902}
903
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700904void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800905{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800906 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
907 this, mThreadName, getTid(), type(), threadTypeToString(type()));
908
Eric Laurent81784c32012-11-19 14:55:58 -0800909 bool locked = AudioFlinger::dumpTryLock(mLock);
910 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800911 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800912 }
913
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700914 dumpBase_l(fd, args);
915 dumpInternals_l(fd, args);
916 dumpTracks_l(fd, args);
917 dumpEffectChains_l(fd, args);
918
919 if (locked) {
920 mLock.unlock();
921 }
922
923 dprintf(fd, " Local log:\n");
924 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
925}
926
927void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
928{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700929 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700930 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700931 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700932 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700933 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700934 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700935 dprintf(fd, " Channel count: %u\n", mChannelCount);
936 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800937 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700938 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700939 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700940 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800941 size_t numConfig = mConfigEvents.size();
942 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700943 const size_t SIZE = 256;
944 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800945 for (size_t i = 0; i < numConfig; i++) {
946 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700947 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800948 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700949 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800950 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700951 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800952 }
Andy Hung293558a2017-03-21 12:19:20 -0700953 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700954 dprintf(fd, " Output devices: %s (%s)\n",
955 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
956 dprintf(fd, " Input device: %#x (%s)\n",
957 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800958 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800959
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700960 // Dump timestamp statistics for the Thread types that support it.
961 if (mType == RECORD
962 || mType == MIXER
963 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700964 || mType == DIRECT
965 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700966 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700967 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700968 }
969
Andy Hung446f4df2019-02-21 12:26:41 -0800970 if (mLastIoBeginNs > 0) { // MMAP may not set this
971 dprintf(fd, " Last %s occurred (msecs): %lld\n",
972 isOutput() ? "write" : "read",
973 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
974 }
975
976 if (mProcessTimeMs.getN() > 0) {
977 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
978 }
979
980 if (mIoJitterMs.getN() > 0) {
981 dprintf(fd, " Hal %s jitter ms stats: %s\n",
982 isOutput() ? "write" : "read",
983 mIoJitterMs.toString().c_str());
984 }
985
Andy Hunge6c37112019-02-26 17:38:10 -0800986 if (mLatencyMs.getN() > 0) {
987 dprintf(fd, " Threadloop %s latency stats: %s\n",
988 isOutput() ? "write" : "read",
989 mLatencyMs.toString().c_str());
990 }
Eric Laurent81784c32012-11-19 14:55:58 -0800991}
992
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700993void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800994{
995 const size_t SIZE = 256;
996 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800997
Marco Nelissenb2208842014-02-07 14:00:50 -0800998 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000999 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001000 write(fd, buffer, strlen(buffer));
1001
Marco Nelissenb2208842014-02-07 14:00:50 -08001002 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001003 sp<EffectChain> chain = mEffectChains[i];
1004 if (chain != 0) {
1005 chain->dump(fd, args);
1006 }
1007 }
1008}
1009
Andy Hungdae27702016-10-31 14:01:16 -07001010void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001011{
1012 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001013 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001014}
1015
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001016String16 AudioFlinger::ThreadBase::getWakeLockTag()
1017{
1018 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001019 case MIXER:
1020 return String16("AudioMix");
1021 case DIRECT:
1022 return String16("AudioDirectOut");
1023 case DUPLICATING:
1024 return String16("AudioDup");
1025 case RECORD:
1026 return String16("AudioIn");
1027 case OFFLOAD:
1028 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001029 case MMAP_PLAYBACK:
1030 return String16("MmapPlayback");
1031 case MMAP_CAPTURE:
1032 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001033 case SPATIALIZER:
1034 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001035 default:
1036 ALOG_ASSERT(false);
1037 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001038 }
1039}
1040
Andy Hungdae27702016-10-31 14:01:16 -07001041void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001042{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001043 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001044 if (mPowerManager != 0) {
1045 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001046 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001047 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1048 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001049 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001050 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001051 {} /* workSource */,
1052 {} /* historyTag */);
1053 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001054 mWakeLockToken = binder;
1055 }
Chris Ye6597d732020-02-28 22:38:25 -08001056 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001057 }
Wei Jia3f273d12015-11-24 09:06:49 -08001058
Andy Hung3f0c9022016-01-15 17:49:46 -08001059 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001060 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1061 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001062}
1063
1064void AudioFlinger::ThreadBase::releaseWakeLock()
1065{
1066 Mutex::Autolock _l(mLock);
1067 releaseWakeLock_l();
1068}
1069
1070void AudioFlinger::ThreadBase::releaseWakeLock_l()
1071{
Andy Hung3f0c9022016-01-15 17:49:46 -08001072 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001073 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001074 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001075 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001076 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001077 }
1078 mWakeLockToken.clear();
1079 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001080}
1081
1082void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001083 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001084 // use checkService() to avoid blocking if power service is not up yet
1085 sp<IBinder> binder =
1086 defaultServiceManager()->checkService(String16("power"));
1087 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001088 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001089 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001090 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001091 binder->linkToDeath(mDeathRecipient);
1092 }
1093 }
1094}
1095
Andy Hungd01b0f12016-11-07 16:10:30 -08001096void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001097 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001098
1099#if !LOG_NDEBUG
1100 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001101 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001102 s << uid << " ";
1103 }
1104 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1105#endif
1106
Andy Hung438e7572015-12-14 15:51:17 -08001107 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1108 if (mSystemReady) {
1109 ALOGE("no wake lock to update, but system ready!");
1110 } else {
1111 ALOGW("no wake lock to update, system not ready yet");
1112 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001113 return;
1114 }
1115 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001116 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001117 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1118 mWakeLockToken, uidsAsInt);
1119 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001120 }
1121}
1122
Eric Laurent81784c32012-11-19 14:55:58 -08001123void AudioFlinger::ThreadBase::clearPowerManager()
1124{
1125 Mutex::Autolock _l(mLock);
1126 releaseWakeLock_l();
1127 mPowerManager.clear();
1128}
1129
jiabinc52b1ff2019-10-31 17:20:42 -07001130void AudioFlinger::ThreadBase::updateOutDevices(
1131 const DeviceDescriptorBaseVector& outDevices __unused)
1132{
1133 ALOGE("%s should only be called in RecordThread", __func__);
1134}
1135
Eric Laurentec376dc2021-04-08 20:41:22 +02001136void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1137{
1138 ALOGE("%s should only be called in RecordThread", __func__);
1139}
1140
Glenn Kasten0f11b512014-01-31 16:18:54 -08001141void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001142{
1143 sp<ThreadBase> thread = mThread.promote();
1144 if (thread != 0) {
1145 thread->clearPowerManager();
1146 }
1147 ALOGW("power manager service died !!!");
1148}
1149
Eric Laurent81784c32012-11-19 14:55:58 -08001150void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001151 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001152{
1153 sp<EffectChain> chain = getEffectChain_l(sessionId);
1154 if (chain != 0) {
1155 if (type != NULL) {
1156 chain->setEffectSuspended_l(type, suspend);
1157 } else {
1158 chain->setEffectSuspendedAll_l(suspend);
1159 }
1160 }
1161
1162 updateSuspendedSessions_l(type, suspend, sessionId);
1163}
1164
1165void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1166{
1167 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1168 if (index < 0) {
1169 return;
1170 }
1171
1172 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1173 mSuspendedSessions.valueAt(index);
1174
1175 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001176 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001177 for (int j = 0; j < desc->mRefCount; j++) {
1178 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1179 chain->setEffectSuspendedAll_l(true);
1180 } else {
1181 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1182 desc->mType.timeLow);
1183 chain->setEffectSuspended_l(&desc->mType, true);
1184 }
1185 }
1186 }
1187}
1188
1189void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1190 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001191 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001192{
1193 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1194
1195 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1196
1197 if (suspend) {
1198 if (index >= 0) {
1199 sessionEffects = mSuspendedSessions.valueAt(index);
1200 } else {
1201 mSuspendedSessions.add(sessionId, sessionEffects);
1202 }
1203 } else {
1204 if (index < 0) {
1205 return;
1206 }
1207 sessionEffects = mSuspendedSessions.valueAt(index);
1208 }
1209
1210
1211 int key = EffectChain::kKeyForSuspendAll;
1212 if (type != NULL) {
1213 key = type->timeLow;
1214 }
1215 index = sessionEffects.indexOfKey(key);
1216
1217 sp<SuspendedSessionDesc> desc;
1218 if (suspend) {
1219 if (index >= 0) {
1220 desc = sessionEffects.valueAt(index);
1221 } else {
1222 desc = new SuspendedSessionDesc();
1223 if (type != NULL) {
1224 desc->mType = *type;
1225 }
1226 sessionEffects.add(key, desc);
1227 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1228 }
1229 desc->mRefCount++;
1230 } else {
1231 if (index < 0) {
1232 return;
1233 }
1234 desc = sessionEffects.valueAt(index);
1235 if (--desc->mRefCount == 0) {
1236 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1237 sessionEffects.removeItemsAt(index);
1238 if (sessionEffects.isEmpty()) {
1239 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1240 sessionId);
1241 mSuspendedSessions.removeItem(sessionId);
1242 }
1243 }
1244 }
1245 if (!sessionEffects.isEmpty()) {
1246 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1247 }
1248}
1249
Eric Laurent6b446ce2019-12-13 10:56:31 -08001250void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1251 audio_session_t sessionId,
1252 bool threadLocked) {
1253 if (!threadLocked) {
1254 mLock.lock();
1255 }
Eric Laurent81784c32012-11-19 14:55:58 -08001256
Eric Laurent81784c32012-11-19 14:55:58 -08001257 if (mType != RECORD) {
1258 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1259 // another session. This gives the priority to well behaved effect control panels
1260 // and applications not using global effects.
1261 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1262 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001263 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001264 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1265 }
1266 }
1267
Eric Laurent6b446ce2019-12-13 10:56:31 -08001268 if (!threadLocked) {
1269 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001270 }
1271}
1272
Eric Laurent4c415062016-06-17 16:14:16 -07001273// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1274status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1275 const effect_descriptor_t *desc, audio_session_t sessionId)
1276{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001277 // No global output effect sessions on record threads
1278 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1279 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001280 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1281 desc->name, mThreadName);
1282 return BAD_VALUE;
1283 }
1284 // only pre processing effects on record thread
1285 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1286 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1287 desc->name, mThreadName);
1288 return BAD_VALUE;
1289 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001290
1291 // always allow effects without processing load or latency
1292 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1293 return NO_ERROR;
1294 }
1295
Eric Laurent4c415062016-06-17 16:14:16 -07001296 audio_input_flags_t flags = mInput->flags;
1297 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1298 if (flags & AUDIO_INPUT_FLAG_RAW) {
1299 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1300 desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1304 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1305 desc->name, mThreadName);
1306 return BAD_VALUE;
1307 }
1308 }
jiabineb3bda02020-06-30 14:07:03 -07001309
1310 if (EffectModule::isHapticGenerator(&desc->type)) {
1311 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1312 return BAD_VALUE;
1313 }
Eric Laurent4c415062016-06-17 16:14:16 -07001314 return NO_ERROR;
1315}
1316
1317// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1318status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1319 const effect_descriptor_t *desc, audio_session_t sessionId)
1320{
1321 // no preprocessing on playback threads
1322 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1323 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1324 " thread %s", desc->name, mThreadName);
1325 return BAD_VALUE;
1326 }
1327
Eric Laurent3e4de772017-07-16 16:55:08 -07001328 // always allow effects without processing load or latency
1329 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1330 return NO_ERROR;
1331 }
1332
jiabineb3bda02020-06-30 14:07:03 -07001333 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1334 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1335 __func__);
1336 return BAD_VALUE;
1337 }
1338
Eric Laurentf690c462021-09-17 14:47:03 +02001339 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1340 && mType != SPATIALIZER) {
1341 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1342 __func__, mType);
1343 return BAD_VALUE;
1344 }
1345
Eric Laurent4c415062016-06-17 16:14:16 -07001346 switch (mType) {
1347 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001348#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001349 // Reject any effect on mixer multichannel sinks.
1350 // TODO: fix both format and multichannel issues with effects.
1351 if (mChannelCount != FCC_2) {
1352 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1353 " thread %s", desc->name, mChannelCount, mThreadName);
1354 return BAD_VALUE;
1355 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001356#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001357 audio_output_flags_t flags = mOutput->flags;
1358 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1359 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1360 // global effects are applied only to non fast tracks if they are SW
1361 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1362 break;
1363 }
1364 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1365 // only post processing on output stage session
1366 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1367 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1368 " on output stage session", desc->name);
1369 return BAD_VALUE;
1370 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001371 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1372 // only post processing on output stage session
1373 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1374 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1375 " on device session", desc->name);
1376 return BAD_VALUE;
1377 }
Eric Laurent4c415062016-06-17 16:14:16 -07001378 } else {
1379 // no restriction on effects applied on non fast tracks
1380 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1381 break;
1382 }
1383 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001384
Eric Laurent4c415062016-06-17 16:14:16 -07001385 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1386 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1387 desc->name);
1388 return BAD_VALUE;
1389 }
1390 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1391 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1392 " in fast mode", desc->name);
1393 return BAD_VALUE;
1394 }
1395 }
1396 } break;
1397 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001398 // nothing actionable on offload threads, if the effect:
1399 // - is offloadable: the effect can be created
1400 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1401 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001402 break;
1403 case DIRECT:
1404 // Reject any effect on Direct output threads for now, since the format of
1405 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1406 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1407 desc->name, mThreadName);
1408 return BAD_VALUE;
1409 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001410#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001411 // Reject any effect on mixer multichannel sinks.
1412 // TODO: fix both format and multichannel issues with effects.
1413 if (mChannelCount != FCC_2) {
1414 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1415 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1416 return BAD_VALUE;
1417 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001418#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001419 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001420 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1421 " thread %s", desc->name, mThreadName);
1422 return BAD_VALUE;
1423 }
1424 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1425 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1426 " DUPLICATING thread %s", desc->name, mThreadName);
1427 return BAD_VALUE;
1428 }
1429 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1430 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1431 " DUPLICATING thread %s", desc->name, mThreadName);
1432 return BAD_VALUE;
1433 }
1434 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001435 case SPATIALIZER:
Eric Laurentb3f315a2021-07-13 15:09:05 +02001436 if (!audio_is_global_session(sessionId)) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001437 ALOGW("checkEffectCompatibility_l(): non global effect %s on SPATIALIZER"
Eric Laurentb3f315a2021-07-13 15:09:05 +02001438 " thread %s", desc->name, mThreadName);
1439 return BAD_VALUE;
1440 }
1441 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001442 default:
1443 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1444 }
1445
1446 return NO_ERROR;
1447}
1448
Eric Laurent81784c32012-11-19 14:55:58 -08001449// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1450sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1451 const sp<AudioFlinger::Client>& client,
1452 const sp<IEffectClient>& effectClient,
1453 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001454 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001455 effect_descriptor_t *desc,
1456 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001457 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001458 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001459 bool probe,
1460 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001461{
1462 sp<EffectModule> effect;
1463 sp<EffectHandle> handle;
1464 status_t lStatus;
1465 sp<EffectChain> chain;
1466 bool chainCreated = false;
1467 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001468 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001469
1470 lStatus = initCheck();
1471 if (lStatus != NO_ERROR) {
1472 ALOGW("createEffect_l() Audio driver not initialized.");
1473 goto Exit;
1474 }
1475
Eric Laurent81784c32012-11-19 14:55:58 -08001476 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1477
1478 { // scope for mLock
1479 Mutex::Autolock _l(mLock);
1480
Eric Laurent4c415062016-06-17 16:14:16 -07001481 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001482 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001483 goto Exit;
1484 }
1485
Eric Laurent81784c32012-11-19 14:55:58 -08001486 // check for existing effect chain with the requested audio session
1487 chain = getEffectChain_l(sessionId);
1488 if (chain == 0) {
1489 // create a new chain for this session
1490 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1491 chain = new EffectChain(this, sessionId);
1492 addEffectChain_l(chain);
1493 chain->setStrategy(getStrategyForSession_l(sessionId));
1494 chainCreated = true;
1495 } else {
1496 effect = chain->getEffectFromDesc_l(desc);
1497 }
1498
1499 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1500
1501 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001502 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001503 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001504 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001505 if (lStatus != NO_ERROR) {
1506 goto Exit;
1507 }
1508 effectCreated = true;
1509
jiabinc52b1ff2019-10-31 17:20:42 -07001510 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001511 effect->setDevices(outDeviceTypeAddrs());
1512 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001513 effect->setMode(mAudioFlinger->getMode());
1514 effect->setAudioSource(mAudioSource);
1515 }
jiabin1319f5a2021-03-30 22:21:24 +00001516 if (effect->isHapticGenerator()) {
1517 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1518 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001519 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1520 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1521 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001522 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001523 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001524 }
1525 }
Eric Laurent81784c32012-11-19 14:55:58 -08001526 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001527 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001528 lStatus = handle->initCheck();
1529 if (lStatus == OK) {
1530 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001531 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001532 }
Eric Laurent81784c32012-11-19 14:55:58 -08001533 if (enabled != NULL) {
1534 *enabled = (int)effect->isEnabled();
1535 }
1536 }
1537
1538Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001539 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001540 Mutex::Autolock _l(mLock);
1541 if (effectCreated) {
1542 chain->removeEffect_l(effect);
1543 }
Eric Laurent81784c32012-11-19 14:55:58 -08001544 if (chainCreated) {
1545 removeEffectChain_l(chain);
1546 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001547 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001548 }
1549
Glenn Kasten9156ef32013-08-06 15:39:08 -07001550 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001551 return handle;
1552}
1553
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001554void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1555 bool unpinIfLast)
1556{
1557 bool remove = false;
1558 sp<EffectModule> effect;
1559 {
1560 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001561 sp<EffectBase> effectBase = handle->effect().promote();
1562 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001563 return;
1564 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001565 effect = effectBase->asEffectModule();
1566 if (effect == nullptr) {
1567 return;
1568 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001569 // restore suspended effects if the disconnected handle was enabled and the last one.
1570 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1571 if (remove) {
1572 removeEffect_l(effect, true);
1573 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001574 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001575 }
1576 if (remove) {
1577 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001578 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001579 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001580 }
1581 }
1582}
1583
Eric Laurent6b446ce2019-12-13 10:56:31 -08001584void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001585 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001586 Mutex::Autolock _l(mLock);
1587 broadcast_l();
1588 }
1589 if (!effect->isOffloadable()) {
1590 if (mType == ThreadBase::OFFLOAD) {
1591 PlaybackThread *t = (PlaybackThread *)this;
1592 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1593 }
1594 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1595 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1596 }
1597 }
1598}
1599
1600void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001601 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001602 Mutex::Autolock _l(mLock);
1603 broadcast_l();
1604 }
1605}
1606
Glenn Kastend848eb42016-03-08 13:42:11 -08001607sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1608 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001609{
1610 Mutex::Autolock _l(mLock);
1611 return getEffect_l(sessionId, effectId);
1612}
1613
Glenn Kastend848eb42016-03-08 13:42:11 -08001614sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1615 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001616{
1617 sp<EffectChain> chain = getEffectChain_l(sessionId);
1618 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1619}
1620
Eric Laurent6c796322019-04-09 14:13:17 -07001621std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1622{
1623 sp<EffectChain> chain = getEffectChain_l(sessionId);
1624 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1625}
1626
Eric Laurent81784c32012-11-19 14:55:58 -08001627// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1628// PlaybackThread::mLock held
1629status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1630{
1631 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001632 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001633 sp<EffectChain> chain = getEffectChain_l(sessionId);
1634 bool chainCreated = false;
1635
Eric Laurent5baf2af2013-09-12 17:37:00 -07001636 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001637 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001638 this, effect->desc().name, effect->desc().flags);
1639
Eric Laurent81784c32012-11-19 14:55:58 -08001640 if (chain == 0) {
1641 // create a new chain for this session
1642 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1643 chain = new EffectChain(this, sessionId);
1644 addEffectChain_l(chain);
1645 chain->setStrategy(getStrategyForSession_l(sessionId));
1646 chainCreated = true;
1647 }
1648 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1649
1650 if (chain->getEffectFromId_l(effect->id()) != 0) {
1651 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1652 this, effect->desc().name, chain.get());
1653 return BAD_VALUE;
1654 }
1655
Eric Laurent5baf2af2013-09-12 17:37:00 -07001656 effect->setOffloaded(mType == OFFLOAD, mId);
1657
Eric Laurent81784c32012-11-19 14:55:58 -08001658 status_t status = chain->addEffect_l(effect);
1659 if (status != NO_ERROR) {
1660 if (chainCreated) {
1661 removeEffectChain_l(chain);
1662 }
1663 return status;
1664 }
1665
jiabin8f278ee2019-11-11 12:16:27 -08001666 effect->setDevices(outDeviceTypeAddrs());
1667 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001668 effect->setMode(mAudioFlinger->getMode());
1669 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001670
Eric Laurent81784c32012-11-19 14:55:58 -08001671 return NO_ERROR;
1672}
1673
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001674void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001675
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001676 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001677 effect_descriptor_t desc = effect->desc();
1678 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1679 detachAuxEffect_l(effect->id());
1680 }
1681
Andy Hungfda44002021-06-03 17:23:16 -07001682 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001683 if (chain != 0) {
1684 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001685 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001686 removeEffectChain_l(chain);
1687 }
1688 } else {
1689 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1690 }
1691}
1692
1693void AudioFlinger::ThreadBase::lockEffectChains_l(
1694 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1695{
1696 effectChains = mEffectChains;
1697 for (size_t i = 0; i < mEffectChains.size(); i++) {
1698 mEffectChains[i]->lock();
1699 }
1700}
1701
1702void AudioFlinger::ThreadBase::unlockEffectChains(
1703 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1704{
1705 for (size_t i = 0; i < effectChains.size(); i++) {
1706 effectChains[i]->unlock();
1707 }
1708}
1709
Glenn Kastend848eb42016-03-08 13:42:11 -08001710sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001711{
1712 Mutex::Autolock _l(mLock);
1713 return getEffectChain_l(sessionId);
1714}
1715
Glenn Kastend848eb42016-03-08 13:42:11 -08001716sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1717 const
Eric Laurent81784c32012-11-19 14:55:58 -08001718{
1719 size_t size = mEffectChains.size();
1720 for (size_t i = 0; i < size; i++) {
1721 if (mEffectChains[i]->sessionId() == sessionId) {
1722 return mEffectChains[i];
1723 }
1724 }
1725 return 0;
1726}
1727
1728void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1729{
1730 Mutex::Autolock _l(mLock);
1731 size_t size = mEffectChains.size();
1732 for (size_t i = 0; i < size; i++) {
1733 mEffectChains[i]->setMode_l(mode);
1734 }
1735}
1736
Mikhail Naganovdc769682018-05-04 15:34:08 -07001737void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001738{
1739 config->type = AUDIO_PORT_TYPE_MIX;
1740 config->ext.mix.handle = mId;
1741 config->sample_rate = mSampleRate;
1742 config->format = mFormat;
1743 config->channel_mask = mChannelMask;
1744 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1745 AUDIO_PORT_CONFIG_FORMAT;
1746}
1747
Eric Laurent72e3f392015-05-20 14:43:50 -07001748void AudioFlinger::ThreadBase::systemReady()
1749{
1750 Mutex::Autolock _l(mLock);
1751 if (mSystemReady) {
1752 return;
1753 }
1754 mSystemReady = true;
1755
1756 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1757 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1758 }
1759 mPendingConfigEvents.clear();
1760}
1761
Andy Hungdae27702016-10-31 14:01:16 -07001762template <typename T>
1763ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1764 ssize_t index = mActiveTracks.indexOf(track);
1765 if (index >= 0) {
1766 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1767 return index;
1768 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001769 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001770 mActiveTracksGeneration++;
1771 mLatestActiveTrack = track;
1772 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001773 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001774 return mActiveTracks.add(track);
1775}
1776
1777template <typename T>
1778ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1779 ssize_t index = mActiveTracks.remove(track);
1780 if (index < 0) {
1781 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1782 return index;
1783 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001784 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001785 mActiveTracksGeneration++;
1786 --mBatteryCounter[track->uid()].second;
1787 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001788 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001789#ifdef TEE_SINK
1790 track->dumpTee(-1 /* fd */, "_REMOVE");
1791#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001792 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001793 return index;
1794}
1795
1796template <typename T>
1797void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1798 for (const sp<T> &track : mActiveTracks) {
1799 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001800 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001801 }
1802 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001803 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001804 mActiveTracks.clear();
1805 mLatestActiveTrack.clear();
1806 mBatteryCounter.clear();
1807}
1808
1809template <typename T>
1810void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1811 sp<ThreadBase> thread, bool force) {
1812 // Updates ActiveTracks client uids to the thread wakelock.
1813 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1814 thread->updateWakeLockUids_l(getWakeLockUids());
1815 mLastActiveTracksGeneration = mActiveTracksGeneration;
1816 }
1817
1818 // Updates BatteryNotifier uids
1819 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1820 const uid_t uid = it->first;
1821 ssize_t &previous = it->second.first;
1822 ssize_t &current = it->second.second;
1823 if (current > 0) {
1824 if (previous == 0) {
1825 BatteryNotifier::getInstance().noteStartAudio(uid);
1826 }
1827 previous = current;
1828 ++it;
1829 } else if (current == 0) {
1830 if (previous > 0) {
1831 BatteryNotifier::getInstance().noteStopAudio(uid);
1832 }
1833 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1834 } else /* (current < 0) */ {
1835 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1836 }
1837 }
1838}
Eric Laurent83b88082014-06-20 18:31:16 -07001839
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001840template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001841bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001842 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001843 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001844
1845 for (const sp<T> &track : mActiveTracks) {
1846 // Do not short-circuit as all hasChanged states must be reset
1847 // as all the metadata are going to be sent
1848 hasChanged |= track->readAndClearHasChanged();
1849 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001850 return hasChanged;
1851}
1852
1853template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001854void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1855 const char *funcName, const sp<T> &track) const {
1856 if (mLocalLog != nullptr) {
1857 String8 result;
1858 track->appendDump(result, false /* active */);
1859 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1860 }
1861}
1862
Eric Laurent6acd1d42017-01-04 14:23:29 -08001863void AudioFlinger::ThreadBase::broadcast_l()
1864{
1865 // Thread could be blocked waiting for async
1866 // so signal it to handle state changes immediately
1867 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1868 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1869 mSignalPending = true;
1870 mWaitWorkCV.broadcast();
1871}
1872
Andy Hungd0979812019-02-21 15:51:44 -08001873// Call only from threadLoop() or when it is idle.
1874// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1875void AudioFlinger::ThreadBase::sendStatistics(bool force)
1876{
1877 // Do not log if we have no stats.
1878 // We choose the timestamp verifier because it is the most likely item to be present.
1879 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1880 if (nstats == 0) {
1881 return;
1882 }
1883
1884 // Don't log more frequently than once per 12 hours.
1885 // We use BOOTTIME to include suspend time.
1886 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1887 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1888 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1889 return;
1890 }
1891
1892 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1893 mLastRecordedTimeNs = timeNs;
1894
Ray Essickf27e9872019-12-07 06:28:46 -08001895 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001896
1897#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1898
1899 // thread configuration
1900 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1901 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1902 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1903 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1904 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1905 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1906 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001907 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1908 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001909
1910 // thread statistics
1911 if (mIoJitterMs.getN() > 0) {
1912 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1913 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1914 }
1915 if (mProcessTimeMs.getN() > 0) {
1916 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1917 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1918 }
1919 const auto tsjitter = mTimestampVerifier.getJitterMs();
1920 if (tsjitter.getN() > 0) {
1921 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1922 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1923 }
1924 if (mLatencyMs.getN() > 0) {
1925 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1926 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1927 }
1928
1929 item->selfrecord();
1930}
1931
Eric Laurentd66d7a12021-07-13 13:35:32 +02001932product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1933{
1934 if (!mAudioFlinger->isAudioPolicyReady()) {
1935 return PRODUCT_STRATEGY_NONE;
1936 }
1937 return AudioSystem::getStrategyForStream(stream);
1938}
1939
Eric Laurent81784c32012-11-19 14:55:58 -08001940// ----------------------------------------------------------------------------
1941// Playback
1942// ----------------------------------------------------------------------------
1943
1944AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1945 AudioStreamOut* output,
1946 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001947 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001948 bool systemReady,
1949 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07001950 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001951 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001952 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08001953 mMixerBuffer(NULL),
1954 mMixerBufferSize(0),
1955 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1956 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001957 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08001958 mEffectBuffer(NULL),
1959 mEffectBufferSize(0),
1960 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1961 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001962 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001963 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001964 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001965 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001966 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001967 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001968 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001969 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001970 mMixerStatus(MIXER_IDLE),
1971 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001972 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001973 mBytesRemaining(0),
1974 mCurrentWriteLength(0),
1975 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001976 mWriteAckSequence(0),
1977 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001978 mScreenState(AudioFlinger::mScreenState),
1979 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001980 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001981 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001982 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1983 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001984{
Glenn Kastend7dca052015-03-05 16:05:54 -08001985 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1986 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001987
1988 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1989 // it would be safer to explicitly pass initial masterVolume/masterMute as
1990 // parameter.
1991 //
1992 // If the HAL we are using has support for master volume or master mute,
1993 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1994 // and the mute set to false).
1995 mMasterVolume = audioFlinger->masterVolume_l();
1996 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08001997 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08001998 if (mOutput->audioHwDev->canSetMasterVolume()) {
1999 mMasterVolume = 1.0;
2000 }
2001
2002 if (mOutput->audioHwDev->canSetMasterMute()) {
2003 mMasterMute = false;
2004 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002005 mIsMsdDevice = strcmp(
2006 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002007 }
2008
Eric Laurentf1f22e72021-07-13 14:04:14 +02002009 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2010 mMixerChannelMask = mixerConfig->channel_mask;
2011 }
2012
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002013 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002014
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002015 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002016 && mMixerChannelMask != mChannelMask) {
2017 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2018 mChannelMask, mMixerChannelMask);
2019 }
2020
Andy Hungc8fddf32018-08-08 18:32:37 -07002021 // TODO: We may also match on address as well as device type for
2022 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002023 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002024 // TODO: This property should be ensure that only contains one single device type.
2025 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2026 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002027 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2028 : AUDIO_DEVICE_NONE));
2029 }
2030
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002031 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2032 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002033 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002034 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2035 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002036 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002037 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2038 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002039 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2040 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002041}
2042
2043AudioFlinger::PlaybackThread::~PlaybackThread()
2044{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002045 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002046 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002047 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002048 free(mEffectBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02002049 free(mEffectToSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002050}
2051
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002052// Thread virtuals
2053
2054void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002055{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002056 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002057 ALOGE("The stream is not open yet"); // This should not happen.
2058 } else {
2059 // setEventCallback will need a strong pointer as a parameter. Calling it
2060 // here instead of constructor of PlaybackThread so that the onFirstRef
2061 // callback would not be made on an incompletely constructed object.
2062 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002063 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002064 }
2065 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002066 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002067}
2068
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002069// ThreadBase virtuals
2070void AudioFlinger::PlaybackThread::preExit()
2071{
2072 ALOGV(" preExit()");
2073 // FIXME this is using hard-coded strings but in the future, this functionality will be
2074 // converted to use audio HAL extensions required to support tunneling
2075 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2076 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2077}
2078
2079void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002080{
Eric Laurent81784c32012-11-19 14:55:58 -08002081 String8 result;
2082
Marco Nelissenb2208842014-02-07 14:00:50 -08002083 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002084 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2085 const stream_type_t *st = &mStreamTypes[i];
2086 if (i > 0) {
2087 result.appendFormat(", ");
2088 }
2089 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2090 if (st->mute) {
2091 result.append("M");
2092 }
2093 }
2094 result.append("\n");
2095 write(fd, result.string(), result.length());
2096 result.clear();
2097
Eric Laurent81784c32012-11-19 14:55:58 -08002098 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2099 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002100 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002101 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002102
2103 size_t numtracks = mTracks.size();
2104 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002105 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002106 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002107 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002108 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002109 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002110 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002111 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002112 for (size_t i = 0; i < numtracks; ++i) {
2113 sp<Track> track = mTracks[i];
2114 if (track != 0) {
2115 bool active = mActiveTracks.indexOf(track) >= 0;
2116 if (active) {
2117 numactiveseen++;
2118 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002119 result.append(prefix);
2120 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002121 }
2122 }
2123 } else {
2124 result.append("\n");
2125 }
2126 if (numactiveseen != numactive) {
2127 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002128 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002129 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002130 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002131 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002132 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002133 sp<Track> track = mActiveTracks[i];
2134 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002135 result.append(prefix);
2136 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002137 }
2138 }
2139 }
2140
2141 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002142}
2143
Andy Hung61589a42021-06-16 09:37:53 -07002144void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002145{
Andy Hung04cb8f72020-03-20 13:44:33 -07002146 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002147 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002148 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2149 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002150 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2151 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2152 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2153 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002154 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002155 dprintf(fd, " Total writes: %d\n", mNumWrites);
2156 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2157 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2158 dprintf(fd, " Suspend count: %d\n", mSuspended);
2159 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2160 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2161 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2162 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002163 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002164 AudioStreamOut *output = mOutput;
2165 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002166 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002167 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002168 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2169 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2170 if (mPipeSink.get() != nullptr) {
2171 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2172 }
2173 if (output != nullptr) {
2174 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002175 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002176 }
Eric Laurent81784c32012-11-19 14:55:58 -08002177}
2178
Eric Laurent81784c32012-11-19 14:55:58 -08002179// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2180sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2181 const sp<AudioFlinger::Client>& client,
2182 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002183 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002184 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002185 audio_format_t format,
2186 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002187 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002188 size_t *pNotificationFrameCount,
2189 uint32_t notificationsPerBuffer,
2190 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002191 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002192 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002193 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002194 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002195 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002196 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002197 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002198 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002199 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002200{
Glenn Kasten74935e42013-12-19 08:56:45 -08002201 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002202 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002203 sp<Track> track;
2204 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002205 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002206 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002207 uint32_t sampleRate;
2208
2209 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2210 lStatus = BAD_VALUE;
2211 goto Exit;
2212 }
Eric Laurent21da6472017-11-09 16:29:26 -08002213
2214 if (*pSampleRate == 0) {
2215 *pSampleRate = mSampleRate;
2216 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002217 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002218
2219 // special case for FAST flag considered OK if fast mixer is present
2220 if (hasFastMixer()) {
2221 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2222 }
2223
2224 // Check if requested flags are compatible with output stream flags
2225 if ((*flags & outputFlags) != *flags) {
2226 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2227 *flags, outputFlags);
2228 *flags = (audio_output_flags_t)(*flags & outputFlags);
2229 }
Eric Laurent81784c32012-11-19 14:55:58 -08002230
Eric Laurent81784c32012-11-19 14:55:58 -08002231 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002232 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002233 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002234 // PCM data
2235 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002236 // TODO: extract as a data library function that checks that a computationally
2237 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002238 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002239 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2240 (channelMask == AUDIO_CHANNEL_OUT_MONO
2241 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002242 // hardware sample rate
2243 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002244 // normal mixer has an associated fast mixer
2245 hasFastMixer() &&
2246 // there are sufficient fast track slots available
2247 (mFastTrackAvailMask != 0)
2248 // FIXME test that MixerThread for this fast track has a capable output HAL
2249 // FIXME add a permission test also?
2250 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002251 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2252 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002253 // read the fast track multiplier property the first time it is needed
2254 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2255 if (ok != 0) {
2256 ALOGE("%s pthread_once failed: %d", __func__, ok);
2257 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002258 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002259 }
Eric Laurent4c415062016-06-17 16:14:16 -07002260
2261 // check compatibility with audio effects.
2262 { // scope for mLock
2263 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002264 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002265 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002266 AUDIO_SESSION_OUTPUT_STAGE,
2267 AUDIO_SESSION_OUTPUT_MIX,
2268 sessionId,
2269 }) {
2270 sp<EffectChain> chain = getEffectChain_l(session);
2271 if (chain.get() != nullptr) {
2272 audio_output_flags_t old = *flags;
2273 chain->checkOutputFlagCompatibility(flags);
2274 if (old != *flags) {
2275 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2276 (int)session, (int)old, (int)*flags);
2277 }
Eric Laurent4c415062016-06-17 16:14:16 -07002278 }
2279 }
2280 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002281 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002282 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2283 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002284 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002285 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2286 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002287 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002288 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002289 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002290 audio_is_linear_pcm(format), channelMask, sampleRate,
2291 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002292 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002293 }
2294 }
Eric Laurent21da6472017-11-09 16:29:26 -08002295
2296 if (!audio_has_proportional_frames(format)) {
2297 if (sharedBuffer != 0) {
2298 // Same comment as below about ignoring frameCount parameter for set()
2299 frameCount = sharedBuffer->size();
2300 } else if (frameCount == 0) {
2301 frameCount = mNormalFrameCount;
2302 }
2303 if (notificationFrameCount != frameCount) {
2304 notificationFrameCount = frameCount;
2305 }
2306 } else if (sharedBuffer != 0) {
2307 // FIXME: Ensure client side memory buffers need
2308 // not have additional alignment beyond sample
2309 // (e.g. 16 bit stereo accessed as 32 bit frame).
2310 size_t alignment = audio_bytes_per_sample(format);
2311 if (alignment & 1) {
2312 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2313 alignment = 1;
2314 }
2315 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2316 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2317 if (channelCount > 1) {
2318 // More than 2 channels does not require stronger alignment than stereo
2319 alignment <<= 1;
2320 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002321 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002322 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002323 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002324 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002325 goto Exit;
2326 }
Eric Laurent21da6472017-11-09 16:29:26 -08002327
2328 // When initializing a shared buffer AudioTrack via constructors,
2329 // there's no frameCount parameter.
2330 // But when initializing a shared buffer AudioTrack via set(),
2331 // there _is_ a frameCount parameter. We silently ignore it.
2332 frameCount = sharedBuffer->size() / frameSize;
2333 } else {
2334 size_t minFrameCount = 0;
2335 // For fast tracks we try to respect the application's request for notifications per buffer.
2336 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2337 if (notificationsPerBuffer > 0) {
2338 // Avoid possible arithmetic overflow during multiplication.
2339 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2340 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2341 notificationsPerBuffer, mFrameCount);
2342 } else {
2343 minFrameCount = mFrameCount * notificationsPerBuffer;
2344 }
2345 }
2346 } else {
2347 // For normal PCM streaming tracks, update minimum frame count.
2348 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2349 // cover audio hardware latency.
2350 // This is probably too conservative, but legacy application code may depend on it.
2351 // If you change this calculation, also review the start threshold which is related.
2352 uint32_t latencyMs = latency_l();
2353 if (latencyMs == 0) {
2354 ALOGE("Error when retrieving output stream latency");
2355 lStatus = UNKNOWN_ERROR;
2356 goto Exit;
2357 }
2358
2359 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2360 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2361
Eric Laurent81784c32012-11-19 14:55:58 -08002362 }
Eric Laurent21da6472017-11-09 16:29:26 -08002363 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002364 frameCount = minFrameCount;
2365 }
Eric Laurent81784c32012-11-19 14:55:58 -08002366 }
Eric Laurent21da6472017-11-09 16:29:26 -08002367
2368 // Make sure that application is notified with sufficient margin before underrun.
2369 // The client can divide the AudioTrack buffer into sub-buffers,
2370 // and expresses its desire to server as the notification frame count.
2371 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2372 size_t maxNotificationFrames;
2373 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2374 // notify every HAL buffer, regardless of the size of the track buffer
2375 maxNotificationFrames = mFrameCount;
2376 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002377 // Triple buffer the notification period for a triple buffered mixer period;
2378 // otherwise, double buffering for the notification period is fine.
2379 //
2380 // TODO: This should be moved to AudioTrack to modify the notification period
2381 // on AudioTrack::setBufferSizeInFrames() changes.
2382 const int nBuffering =
2383 (uint64_t{frameCount} * mSampleRate)
2384 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2385
Eric Laurent21da6472017-11-09 16:29:26 -08002386 maxNotificationFrames = frameCount / nBuffering;
2387 // If client requested a fast track but this was denied, then use the smaller maximum.
2388 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2389 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2390 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2391 maxNotificationFrames = maxNotificationFramesFastDenied;
2392 }
2393 }
2394 }
2395 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2396 if (notificationFrameCount == 0) {
2397 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2398 maxNotificationFrames, frameCount);
2399 } else {
2400 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2401 notificationFrameCount, maxNotificationFrames, frameCount);
2402 }
2403 notificationFrameCount = maxNotificationFrames;
2404 }
2405 }
2406
Glenn Kasten74935e42013-12-19 08:56:45 -08002407 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002408 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002409
Glenn Kastenc3df8382014-03-13 15:05:25 -07002410 switch (mType) {
2411
2412 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002413 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002414 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002415 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2416 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002417 sampleRate, format, channelMask, mOutput, mFormat);
2418 lStatus = BAD_VALUE;
2419 goto Exit;
2420 }
2421 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002422 break;
2423
2424 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002426 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2427 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002428 sampleRate, format, channelMask, mOutput, mFormat);
2429 lStatus = BAD_VALUE;
2430 goto Exit;
2431 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002432 break;
2433
2434 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002435 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002436 ALOGE("createTrack_l() Bad parameter: format %#x \""
2437 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002438 format, mOutput, mFormat);
2439 lStatus = BAD_VALUE;
2440 goto Exit;
2441 }
Andy Hungcd044842014-08-07 11:04:34 -07002442 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002443 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2444 lStatus = BAD_VALUE;
2445 goto Exit;
2446 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002447 break;
2448
Eric Laurent81784c32012-11-19 14:55:58 -08002449 }
2450
2451 lStatus = initCheck();
2452 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002453 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002454 goto Exit;
2455 }
2456
2457 { // scope for mLock
2458 Mutex::Autolock _l(mLock);
2459
2460 // all tracks in same audio session must share the same routing strategy otherwise
2461 // conflicts will happen when tracks are moved from one output to another by audio policy
2462 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002463 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002464 for (size_t i = 0; i < mTracks.size(); ++i) {
2465 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002466 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002467 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002468 if (sessionId == t->sessionId() && strategy != actual) {
2469 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2470 strategy, actual);
2471 lStatus = BAD_VALUE;
2472 goto Exit;
2473 }
2474 }
2475 }
2476
yucliuc9c49cd2020-07-13 16:25:21 -07002477 // Set DIRECT flag if current thread is DirectOutputThread. This can
2478 // happen when the playback is rerouted to direct output thread by
2479 // dynamic audio policy.
2480 // Do NOT report the flag changes back to client, since the client
2481 // doesn't explicitly request a direct flag.
2482 audio_output_flags_t trackFlags = *flags;
2483 if (mType == DIRECT) {
2484 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2485 }
2486
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002487 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002488 channelMask, frameCount,
2489 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002490 sessionId, creatorPid, attributionSource, trackFlags,
2491 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002492
Glenn Kasten03003332013-08-06 15:40:54 -07002493 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2494 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002495 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002496 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002497 goto Exit;
2498 }
2499 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002500 {
2501 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2502 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002503 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002504 }
2505 }
Eric Laurent81784c32012-11-19 14:55:58 -08002506
2507 sp<EffectChain> chain = getEffectChain_l(sessionId);
2508 if (chain != 0) {
2509 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2510 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002511 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002512 chain->incTrackCnt();
2513 }
2514
Eric Laurent05067782016-06-01 18:27:28 -07002515 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002516 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2517 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2518 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002519 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002520 }
2521 }
2522
2523 lStatus = NO_ERROR;
2524
2525Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002526 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002527 return track;
2528}
2529
Andy Hung1bc088a2018-02-09 15:57:31 -08002530template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002531ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2532{
Andy Hungc0691382018-09-12 18:01:57 -07002533 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002534 const ssize_t index = mTracks.remove(track);
2535 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002536 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002537 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002538 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002539 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002540 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002541 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002542 }
2543 return index;
2544}
2545
Eric Laurent81784c32012-11-19 14:55:58 -08002546uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2547{
2548 return latency;
2549}
2550
2551uint32_t AudioFlinger::PlaybackThread::latency() const
2552{
2553 Mutex::Autolock _l(mLock);
2554 return latency_l();
2555}
2556uint32_t AudioFlinger::PlaybackThread::latency_l() const
2557{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002558 uint32_t latency;
2559 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2560 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002561 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002562 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002563}
2564
2565void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2566{
2567 Mutex::Autolock _l(mLock);
2568 // Don't apply master volume in SW if our HAL can do it for us.
2569 if (mOutput && mOutput->audioHwDev &&
2570 mOutput->audioHwDev->canSetMasterVolume()) {
2571 mMasterVolume = 1.0;
2572 } else {
2573 mMasterVolume = value;
2574 }
2575}
2576
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002577void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2578{
2579 mMasterBalance.store(balance);
2580}
2581
Eric Laurent81784c32012-11-19 14:55:58 -08002582void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2583{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002584 if (isDuplicating()) {
2585 return;
2586 }
Eric Laurent81784c32012-11-19 14:55:58 -08002587 Mutex::Autolock _l(mLock);
2588 // Don't apply master mute in SW if our HAL can do it for us.
2589 if (mOutput && mOutput->audioHwDev &&
2590 mOutput->audioHwDev->canSetMasterMute()) {
2591 mMasterMute = false;
2592 } else {
2593 mMasterMute = muted;
2594 }
2595}
2596
2597void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2598{
2599 Mutex::Autolock _l(mLock);
2600 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002601 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002602}
2603
2604void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2605{
2606 Mutex::Autolock _l(mLock);
2607 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002608 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002609}
2610
2611float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2612{
2613 Mutex::Autolock _l(mLock);
2614 return mStreamTypes[stream].volume;
2615}
2616
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002617void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2618{
2619 mOutput->stream->setVolume(left, right);
2620}
2621
Eric Laurent81784c32012-11-19 14:55:58 -08002622// addTrack_l() must be called with ThreadBase::mLock held
2623status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2624{
2625 status_t status = ALREADY_EXISTS;
2626
Eric Laurent81784c32012-11-19 14:55:58 -08002627 if (mActiveTracks.indexOf(track) < 0) {
2628 // the track is newly added, make sure it fills up all its
2629 // buffers before playing. This is to ensure the client will
2630 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002631 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002632 TrackBase::track_state state = track->mState;
2633 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002634 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002635 mLock.lock();
2636 // abort track was stopped/paused while we released the lock
2637 if (state != track->mState) {
2638 if (status == NO_ERROR) {
2639 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002640 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 mLock.lock();
2642 }
2643 return INVALID_OPERATION;
2644 }
2645 // abort if start is rejected by audio policy manager
2646 if (status != NO_ERROR) {
2647 return PERMISSION_DENIED;
2648 }
2649#ifdef ADD_BATTERY_DATA
2650 // to track the speaker usage
2651 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2652#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002653 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 }
2655
Eric Laurent51716182016-02-29 18:00:56 -08002656 // set retry count for buffer fill
2657 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002658 if (track->isStopping_1()) {
2659 track->mRetryCount = kMaxTrackStopRetriesOffload;
2660 } else {
2661 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2662 }
2663 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002664 } else {
2665 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002666 track->mFillingUpStatus =
2667 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002668 }
2669
jiabineb3bda02020-06-30 14:07:03 -07002670 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2671 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2672 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2673 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002674 // Unlock due to VibratorService will lock for this call and will
2675 // call Tracks.mute/unmute which also require thread's lock.
2676 mLock.unlock();
2677 const int intensity = AudioFlinger::onExternalVibrationStart(
2678 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002679 std::optional<media::AudioVibratorInfo> vibratorInfo;
2680 {
2681 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2682 // used to play this track.
2683 Mutex::Autolock _l(mAudioFlinger->mLock);
2684 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2685 }
jiabin57303cc2018-12-18 15:45:57 -08002686 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002687 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002688 if (vibratorInfo) {
2689 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2690 }
2691
jiabin57303cc2018-12-18 15:45:57 -08002692 // Haptic playback should be enabled by vibrator service.
2693 if (track->getHapticPlaybackEnabled()) {
2694 // Disable haptic playback of all active track to ensure only
2695 // one track playing haptic if current track should play haptic.
2696 for (const auto &t : mActiveTracks) {
2697 t->setHapticPlaybackEnabled(false);
2698 }
jiabin245cdd92018-12-07 17:55:15 -08002699 }
jiabine70bc7f2020-06-30 22:07:55 -07002700
2701 // Set haptic intensity for effect
2702 if (chain != nullptr) {
2703 chain->setHapticIntensity_l(track->id(), intensity);
2704 }
jiabin245cdd92018-12-07 17:55:15 -08002705 }
2706
Eric Laurent81784c32012-11-19 14:55:58 -08002707 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002708 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002709 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002710 if (chain != 0) {
2711 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2712 track->sessionId());
2713 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002714 }
2715
Andy Hungc2b11cb2020-04-22 09:04:01 -07002716 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002717 status = NO_ERROR;
2718 }
2719
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002720 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002721 return status;
2722}
2723
Eric Laurentbfb1b832013-01-07 09:53:42 -08002724bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002725{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002726 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002727 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002728 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2729 track->mState = TrackBase::STOPPED;
2730 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002731 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002732 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002733 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002735
2736 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002737}
2738
2739void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2740{
2741 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002742
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002743 String8 result;
2744 track->appendDump(result, false /* active */);
2745 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002746
Eric Laurent81784c32012-11-19 14:55:58 -08002747 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002748 {
2749 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2750 mAudioTrackCallbacks.erase(track);
2751 }
Eric Laurent81784c32012-11-19 14:55:58 -08002752 if (track->isFastTrack()) {
2753 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002754 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002755 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2756 mFastTrackAvailMask |= 1 << index;
2757 // redundant as track is about to be destroyed, for dumpsys only
2758 track->mFastIndex = -1;
2759 }
2760 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2761 if (chain != 0) {
2762 chain->decTrackCnt();
2763 }
2764}
2765
2766String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2767{
Eric Laurent81784c32012-11-19 14:55:58 -08002768 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002769 String8 out_s8;
2770 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2771 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002772 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002773 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002774}
2775
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002776status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2777 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002778 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002779 return NO_INIT;
2780 }
2781 return mOutput->stream->selectPresentation(presentationId, programId);
2782}
2783
Eric Laurent09f1ed22019-04-24 17:45:17 -07002784void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2785 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002786 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2787 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002788
Eric Laurent73e26b62015-04-27 16:55:58 -07002789 desc->mIoHandle = mId;
Eric Laurent74c38dc2020-12-23 18:19:44 +01002790 struct audio_patch patch = mPatch;
2791 if (isMsdDevice()) {
2792 patch = mDownStreamPatch;
2793 }
Eric Laurent81784c32012-11-19 14:55:58 -08002794
2795 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002796 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002797 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002798 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002799 desc->mPatch = patch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002800 desc->mChannelMask = mChannelMask;
2801 desc->mSamplingRate = mSampleRate;
2802 desc->mFormat = mFormat;
2803 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002804 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002805 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002806 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002807 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002808 case AUDIO_CLIENT_STARTED:
Eric Laurent74c38dc2020-12-23 18:19:44 +01002809 desc->mPatch = patch;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002810 desc->mPortId = portId;
2811 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002812 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002813 default:
2814 break;
2815 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002816 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002817}
2818
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002819void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002821 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002822}
2823
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002824void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002825{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002826 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002827}
2828
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002829void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002830{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002831 mCallbackThread->setAsyncError();
2832}
2833
jiabinf6eb4c32020-02-25 14:06:25 -08002834void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2835 const std::basic_string<uint8_t>& metadataBs)
2836{
2837 std::thread([this, metadataBs]() {
2838 audio_utils::metadata::Data metadata =
2839 audio_utils::metadata::dataFromByteString(metadataBs);
2840 if (metadata.empty()) {
2841 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2842 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2843 (int)metadataBs.size());
2844 return;
2845 }
2846
2847 audio_utils::metadata::ByteString metaDataStr =
2848 audio_utils::metadata::byteStringFromData(metadata);
2849 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2850 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002851 for (const auto& callbackPair : mAudioTrackCallbacks) {
2852 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002853 }
2854 }).detach();
2855}
2856
Eric Laurent3b4529e2013-09-05 18:09:19 -07002857void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858{
2859 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002860 // reject out of sequence requests
2861 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2862 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 mWaitWorkCV.signal();
2864 }
2865}
2866
Eric Laurent3b4529e2013-09-05 18:09:19 -07002867void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868{
2869 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002870 // reject out of sequence requests
2871 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002872 // Register discontinuity when HW drain is completed because that can cause
2873 // the timestamp frame position to reset to 0 for direct and offload threads.
2874 // (Out of sequence requests are ignored, since the discontinuity would be handled
2875 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002876 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002877 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 mWaitWorkCV.signal();
2879 }
2880}
2881
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002882void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002883{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002884 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002885 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2886 mSampleRate = audioConfig.sample_rate;
2887 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002888 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002889 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002890 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002891 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002892 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2893 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002894 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002895
2896 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2897 mMixerChannelMask = mChannelMask;
2898 }
2899
Andy Hunge5412692014-05-16 11:25:07 -07002900 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002901 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002902
Eric Laurentf1f22e72021-07-13 14:04:14 +02002903 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2904
Phil Burkca5e6142015-07-14 09:42:29 -07002905 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002906 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002907 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002908 // Get format from the shim, which will be different than the HAL format
2909 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002910 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002911 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002912 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002913 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002914 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002915 LOG_FATAL("HAL format %#x not supported for mixed output",
2916 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002917 }
Phil Burk062e67a2015-02-11 13:40:50 -08002918 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002919 result = mOutput->stream->getBufferSize(&mBufferSize);
2920 LOG_ALWAYS_FATAL_IF(result != OK,
2921 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002922 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002923 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002924 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002925 mFrameCount);
2926 }
2927
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002928 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2929 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002930 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002931 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002932 }
2933 }
2934
Eric Laurentd1f69b02014-12-15 14:33:13 -08002935 mHwSupportsPause = false;
2936 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002937 bool supportsPause = false, supportsResume = false;
2938 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2939 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002940 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002941 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002942 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002943 } else if (supportsResume) {
2944 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002945 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002946 }
2947 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002948 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2949 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2950 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002951
Andy Hungfbfc3952015-01-15 13:33:51 -08002952 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2953 // For best precision, we use float instead of the associated output
2954 // device format (typically PCM 16 bit).
2955
2956 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2957 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2958 mBufferSize = mFrameSize * mFrameCount;
2959
2960 // TODO: We currently use the associated output device channel mask and sample rate.
2961 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2962 // (if a valid mask) to avoid premature downmix.
2963 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2964 // instead of the output device sample rate to avoid loss of high frequency information.
2965 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2966 }
2967
Andy Hung09a50072014-02-27 14:30:47 -08002968 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002969 double multiplier = 1.0;
2970 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2971 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002972 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2973 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002974
Eric Laurent81784c32012-11-19 14:55:58 -08002975 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2976 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2977 maxNormalFrameCount = maxNormalFrameCount & ~15;
2978 if (maxNormalFrameCount < minNormalFrameCount) {
2979 maxNormalFrameCount = minNormalFrameCount;
2980 }
2981 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2982 if (multiplier <= 1.0) {
2983 multiplier = 1.0;
2984 } else if (multiplier <= 2.0) {
2985 if (2 * mFrameCount <= maxNormalFrameCount) {
2986 multiplier = 2.0;
2987 } else {
2988 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2989 }
2990 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002991 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002992 }
2993 }
2994 mNormalFrameCount = multiplier * mFrameCount;
2995 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02002996 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07002997 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2998 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002999 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003000 mNormalFrameCount);
3001
Andy Hung08fb1742015-05-31 23:22:10 -07003002 // Check if we want to throttle the processing to no more than 2x normal rate
3003 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003004 mThreadThrottleTimeMs = 0;
3005 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003006 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3007
Andy Hung010a1a12014-03-13 13:57:33 -07003008 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3009 // Originally this was int16_t[] array, need to remove legacy implications.
3010 free(mSinkBuffer);
3011 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003012 free(mEffectToSinkBuffer);
3013 mEffectToSinkBuffer = nullptr;
3014
Andy Hung5b10a202014-03-13 13:59:29 -07003015 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3016 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3017 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003018 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003019
Eric Laurent39095982021-08-24 18:29:27 +02003020 if (mType == SPATIALIZER) {
3021 (void)posix_memalign(&mEffectToSinkBuffer, 32, sinkBufferSize);
3022 }
3023
Andy Hung69aed5f2014-02-25 17:24:40 -08003024 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3025 // drives the output.
3026 free(mMixerBuffer);
3027 mMixerBuffer = NULL;
3028 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003029 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003030 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003031 * audio_bytes_per_sample(mMixerBufferFormat);
3032 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3033 }
Andy Hung98ef9782014-03-04 14:46:50 -08003034 free(mEffectBuffer);
3035 mEffectBuffer = NULL;
3036 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003037 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003038 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003039 * audio_bytes_per_sample(mEffectBufferFormat);
3040 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3041 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003042
Mikhail Naganov55773032020-10-01 15:08:13 -07003043 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3044 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003045 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3046 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003047 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003048
Eric Laurent81784c32012-11-19 14:55:58 -08003049 // force reconfiguration of effect chains and engines to take new buffer size and audio
3050 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003051 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003052 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3053 // matter.
3054 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3055 Vector< sp<EffectChain> > effectChains = mEffectChains;
3056 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003057 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3058 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003059 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003060
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003061 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003062 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003063 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3064 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3065 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3066 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3067 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3068 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3069 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3070 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3071 (int32_t)mHapticChannelMask)
3072 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3073 (int32_t)mHapticChannelCount)
3074 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3075 formatToString(mHALFormat).c_str())
3076 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3077 (int32_t)mFrameCount) // sic - added HAL
3078 ;
3079 uint32_t latencyMs;
3080 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3081 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3082 }
3083 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003084}
3085
Kevin Rocard069c2712018-03-29 19:09:14 -07003086void AudioFlinger::PlaybackThread::updateMetadata_l()
3087{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003088 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003089 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003090 }
3091 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003092 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003093 for (const sp<Track> &track : mActiveTracks) {
3094 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003095 // Do not forward metadata for PatchTrack with unspecified stream type
3096 if (track->streamType() != AUDIO_STREAM_PATCH) {
3097 track->copyMetadataTo(backInserter);
3098 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003099 }
Kevin Rocard12381092018-04-11 09:19:59 -07003100 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003101}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003102
Kevin Rocard12381092018-04-11 09:19:59 -07003103void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3104 const StreamOutHalInterface::SourceMetadata& metadata)
3105{
3106 mOutput->stream->updateSourceMetadata(metadata);
3107};
3108
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003109status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003110{
3111 if (halFrames == NULL || dspFrames == NULL) {
3112 return BAD_VALUE;
3113 }
3114 Mutex::Autolock _l(mLock);
3115 if (initCheck() != NO_ERROR) {
3116 return INVALID_OPERATION;
3117 }
Andy Hung818e7a32016-02-16 18:08:07 -08003118 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003119 *halFrames = framesWritten;
3120
3121 if (isSuspended()) {
3122 // return an estimation of rendered frames when the output is suspended
3123 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003124 *dspFrames = (uint32_t)
3125 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003126 return NO_ERROR;
3127 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003128 status_t status;
3129 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003130 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003131 *dspFrames = (size_t)frames;
3132 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003133 }
3134}
3135
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003136product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003137{
3138 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3139 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3140 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003141 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003142 }
3143 for (size_t i = 0; i < mTracks.size(); i++) {
3144 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003145 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003146 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003147 }
3148 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003149 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003150}
3151
3152
Phil Burk062e67a2015-02-11 13:40:50 -08003153AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003154{
3155 Mutex::Autolock _l(mLock);
3156 return mOutput;
3157}
3158
Phil Burk062e67a2015-02-11 13:40:50 -08003159AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003160{
3161 Mutex::Autolock _l(mLock);
3162 AudioStreamOut *output = mOutput;
3163 mOutput = NULL;
3164 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3165 // must push a NULL and wait for ack
3166 mOutputSink.clear();
3167 mPipeSink.clear();
3168 mNormalSink.clear();
3169 return output;
3170}
3171
3172// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003173sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003174{
3175 if (mOutput == NULL) {
3176 return NULL;
3177 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003178 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003179}
3180
3181uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3182{
3183 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3184}
3185
3186status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3187{
3188 if (!isValidSyncEvent(event)) {
3189 return BAD_VALUE;
3190 }
3191
3192 Mutex::Autolock _l(mLock);
3193
3194 for (size_t i = 0; i < mTracks.size(); ++i) {
3195 sp<Track> track = mTracks[i];
3196 if (event->triggerSession() == track->sessionId()) {
3197 (void) track->setSyncEvent(event);
3198 return NO_ERROR;
3199 }
3200 }
3201
3202 return NAME_NOT_FOUND;
3203}
3204
3205bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3206{
3207 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3208}
3209
3210void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3211 const Vector< sp<Track> >& tracksToRemove)
3212{
Andy Hungfe726a62018-09-27 15:17:25 -07003213 // Miscellaneous track cleanup when removed from the active list,
3214 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003215#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003216 for (const auto& track : tracksToRemove) {
3217 if (track->isExternalTrack()) {
3218 // to track the speaker usage
3219 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003220 }
3221 }
Andy Hungfe726a62018-09-27 15:17:25 -07003222#else
3223 (void)tracksToRemove; // suppress unused warning
3224#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003225}
3226
3227void AudioFlinger::PlaybackThread::checkSilentMode_l()
3228{
3229 if (!mMasterMute) {
3230 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003231 if (mOutDeviceTypeAddrs.empty()) {
3232 ALOGD("ro.audio.silent is ignored since no output device is set");
3233 return;
3234 }
jiabinc52b1ff2019-10-31 17:20:42 -07003235 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003236 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3237 return;
3238 }
Eric Laurent81784c32012-11-19 14:55:58 -08003239 if (property_get("ro.audio.silent", value, "0") > 0) {
3240 char *endptr;
3241 unsigned long ul = strtoul(value, &endptr, 0);
3242 if (*endptr == '\0' && ul != 0) {
3243 ALOGD("Silence is golden");
3244 // The setprop command will not allow a property to be changed after
3245 // the first time it is set, so we don't have to worry about un-muting.
3246 setMasterMute_l(true);
3247 }
3248 }
3249 }
3250}
3251
3252// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003253ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003254{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003255 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003256 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003257 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003258 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003259
3260 // If an NBAIO sink is present, use it to write the normal mixer's submix
3261 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003262
Andy Hung010a1a12014-03-13 13:57:33 -07003263 const size_t count = mBytesRemaining / mFrameSize;
3264
Simon Wilson2d590962012-11-29 15:18:50 -08003265 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003266 // update the setpoint when AudioFlinger::mScreenState changes
3267 uint32_t screenState = AudioFlinger::mScreenState;
3268 if (screenState != mScreenState) {
3269 mScreenState = screenState;
3270 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3271 if (pipe != NULL) {
3272 pipe->setAvgFrames((mScreenState & 1) ?
3273 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3274 }
3275 }
Andy Hung010a1a12014-03-13 13:57:33 -07003276 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003277 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003278 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003279 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003280#ifdef TEE_SINK
3281 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3282#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003283 } else {
3284 bytesWritten = framesWritten;
3285 }
3286 // otherwise use the HAL / AudioStreamOut directly
3287 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003288 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003289
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003291 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3292 mWriteAckSequence += 2;
3293 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003294 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003295 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003296 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003297 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003298 // FIXME We should have an implementation of timestamps for direct output threads.
3299 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003300 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003301 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003302
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303 if (mUseAsyncWrite &&
3304 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3305 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003306 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003307 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003308 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003309 }
Eric Laurent81784c32012-11-19 14:55:58 -08003310 }
3311
Eric Laurent81784c32012-11-19 14:55:58 -08003312 mNumWrites++;
3313 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003314 if (mStandby) {
3315 mThreadMetrics.logBeginInterval();
3316 mStandby = false;
3317 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003318 return bytesWritten;
3319}
3320
3321void AudioFlinger::PlaybackThread::threadLoop_drain()
3322{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003323 bool supportsDrain = false;
3324 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003325 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3326 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003327 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3328 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003329 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003330 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003331 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003332 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003333 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003334 }
3335}
3336
3337void AudioFlinger::PlaybackThread::threadLoop_exit()
3338{
Eric Laurent275e8e92014-11-30 15:14:47 -08003339 {
3340 Mutex::Autolock _l(mLock);
3341 for (size_t i = 0; i < mTracks.size(); i++) {
3342 sp<Track> track = mTracks[i];
3343 track->invalidate();
3344 }
Andy Hungdae27702016-10-31 14:01:16 -07003345 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3346 // After we exit there are no more track changes sent to BatteryNotifier
3347 // because that requires an active threadLoop.
3348 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3349 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003350 }
Eric Laurent81784c32012-11-19 14:55:58 -08003351}
3352
3353/*
3354The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003355 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003356 - mActiveSleepTimeUs from activeSleepTimeUs()
3357 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003358 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3359 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003360 - maxPeriod from frame count and sample rate (MIXER only)
3361
3362The parameters that affect these derived values are:
3363 - frame count
3364 - frame size
3365 - sample rate
3366 - device type: A2DP or not
3367 - device latency
3368 - format: PCM or not
3369 - active sleep time
3370 - idle sleep time
3371*/
3372
3373void AudioFlinger::PlaybackThread::cacheParameters_l()
3374{
Andy Hung25c2dac2014-02-27 14:56:00 -08003375 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003376 mActiveSleepTimeUs = activeSleepTimeUs();
3377 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003378
3379 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3380 // truncating audio when going to standby.
3381 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003382 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003383 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3384 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3385 }
3386 }
Eric Laurent81784c32012-11-19 14:55:58 -08003387}
3388
Eric Laurent13084622016-05-17 10:51:49 -07003389bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003390{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003391 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003392 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003393 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003394 size_t size = mTracks.size();
3395 for (size_t i = 0; i < size; i++) {
3396 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003397 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003398 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003399 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003400 }
3401 }
Eric Laurent13084622016-05-17 10:51:49 -07003402 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003403}
3404
Haynes Mathew George05317d22016-05-03 16:34:26 -07003405void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3406{
3407 Mutex::Autolock _l(mLock);
3408 invalidateTracks_l(streamType);
3409}
3410
jiabinf042b9b2021-05-07 23:46:28 +00003411// getTrackById_l must be called with holding thread lock
3412AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3413 audio_port_handle_t trackPortId) {
3414 for (size_t i = 0; i < mTracks.size(); i++) {
3415 if (mTracks[i]->portId() == trackPortId) {
3416 return mTracks[i].get();
3417 }
3418 }
3419 return nullptr;
3420}
3421
Eric Laurent81784c32012-11-19 14:55:58 -08003422status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3423{
Glenn Kastend848eb42016-03-08 13:42:11 -08003424 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003425 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003426 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003427 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3428 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3429 &halInBuffer);
3430 if (result != OK) return result;
3431 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003432 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003433 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003434 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003435 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003436 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003437 if (mType != DIRECT) {
Eric Laurentf1f22e72021-07-13 14:04:14 +02003438 size_t numSamples = mNormalFrameCount
3439 * (audio_channel_count_from_out_mask(mMixerChannelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003440 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003441 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003442 &halInBuffer);
3443 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003444#ifdef FLOAT_EFFECT_CHAIN
3445 buffer = halInBuffer->audioBuffer()->f32;
3446#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003447 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003448#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003449 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3450 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003451 }
3452
3453 // Attach all tracks with same session ID to this chain.
3454 for (size_t i = 0; i < mTracks.size(); ++i) {
3455 sp<Track> track = mTracks[i];
3456 if (session == track->sessionId()) {
3457 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3458 buffer);
3459 track->setMainBuffer(buffer);
3460 chain->incTrackCnt();
3461 }
3462 }
3463
3464 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003465 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003466 if (session == track->sessionId()) {
3467 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3468 chain->incActiveTrackCnt();
3469 }
3470 }
3471 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003472 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003473 chain->setInBuffer(halInBuffer);
3474 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003475 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3476 // chains list in order to be processed last as it contains output device effects.
3477 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3478 // processing effects specific to an output stream before effects applied to all streams
3479 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003480 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3481 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003482 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003483 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003484 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003485 // Effect chain for other sessions are inserted at beginning of effect
3486 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003487 // sessions is not important.
3488 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003489 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3490 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003491 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003492 size_t size = mEffectChains.size();
3493 size_t i = 0;
3494 for (i = 0; i < size; i++) {
3495 if (mEffectChains[i]->sessionId() < session) {
3496 break;
3497 }
3498 }
3499 mEffectChains.insertAt(chain, i);
3500 checkSuspendOnAddEffectChain_l(chain);
3501
3502 return NO_ERROR;
3503}
3504
3505size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3506{
Glenn Kastend848eb42016-03-08 13:42:11 -08003507 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003508
3509 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3510
3511 for (size_t i = 0; i < mEffectChains.size(); i++) {
3512 if (chain == mEffectChains[i]) {
3513 mEffectChains.removeAt(i);
3514 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003515 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003516 if (session == track->sessionId()) {
3517 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3518 chain.get(), session);
3519 chain->decActiveTrackCnt();
3520 }
3521 }
3522
3523 // detach all tracks with same session ID from this chain
3524 for (size_t i = 0; i < mTracks.size(); ++i) {
3525 sp<Track> track = mTracks[i];
3526 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003527 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003528 chain->decTrackCnt();
3529 }
3530 }
3531 break;
3532 }
3533 }
3534 return mEffectChains.size();
3535}
3536
3537status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003538 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003539{
3540 Mutex::Autolock _l(mLock);
3541 return attachAuxEffect_l(track, EffectId);
3542}
3543
3544status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003545 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003546{
3547 status_t status = NO_ERROR;
3548
3549 if (EffectId == 0) {
3550 track->setAuxBuffer(0, NULL);
3551 } else {
3552 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3553 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3554 if (effect != 0) {
3555 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3556 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3557 } else {
3558 status = INVALID_OPERATION;
3559 }
3560 } else {
3561 status = BAD_VALUE;
3562 }
3563 }
3564 return status;
3565}
3566
3567void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3568{
3569 for (size_t i = 0; i < mTracks.size(); ++i) {
3570 sp<Track> track = mTracks[i];
3571 if (track->auxEffectId() == effectId) {
3572 attachAuxEffect_l(track, 0);
3573 }
3574 }
3575}
3576
3577bool AudioFlinger::PlaybackThread::threadLoop()
3578{
Glenn Kasten388d5712017-04-07 14:38:41 -07003579 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003580
Eric Laurent81784c32012-11-19 14:55:58 -08003581 Vector< sp<Track> > tracksToRemove;
3582
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003583 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003584 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003585
3586 // MIXER
3587 nsecs_t lastWarning = 0;
3588
3589 // DUPLICATING
3590 // FIXME could this be made local to while loop?
3591 writeFrames = 0;
3592
3593 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003594 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003595
3596 if (mType == MIXER) {
3597 sleepTimeShift = 0;
3598 }
3599
3600 CpuStats cpuStats;
3601 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3602
3603 acquireWakeLock();
3604
Glenn Kasteneef598c2017-04-03 14:41:13 -07003605 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3606 // thread associated with this PlaybackThread.
3607 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3608 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003609 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3610 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003611 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003612 const char *logString = NULL;
3613
rago1bb90822017-05-02 18:31:48 -07003614 // Estimated time for next buffer to be written to hal. This is used only on
3615 // suspended mode (for now) to help schedule the wait time until next iteration.
3616 nsecs_t timeLoopNextNs = 0;
3617
Eric Laurent664539d2013-09-23 18:24:31 -07003618 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003619
Andy Hung2dbffc22018-08-08 18:50:41 -07003620 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003621
Eric Laurentb3f315a2021-07-13 15:09:05 +02003622 sendCheckOutputStageEffectsEvent();
3623
Andy Hung446f4df2019-02-21 12:26:41 -08003624 // loopCount is used for statistics and diagnostics.
3625 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003626 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003627 // Log merge requests are performed during AudioFlinger binder transactions, but
3628 // that does not cover audio playback. It's requested here for that reason.
3629 mAudioFlinger->requestLogMerge();
3630
Eric Laurent81784c32012-11-19 14:55:58 -08003631 cpuStats.sample(myName);
3632
3633 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003634 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003635 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003636
Andy Hung2dbffc22018-08-08 18:50:41 -07003637 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3638 //
jiabinc52b1ff2019-10-31 17:20:42 -07003639 // Note: we access outDeviceTypes() outside of mLock.
3640 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003641 // Here, we try for the AF lock, but do not block on it as the latency
3642 // is more informational.
3643 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3644 std::vector<PatchPanel::SoftwarePatch> swPatches;
3645 double latencyMs;
3646 status_t status = INVALID_OPERATION;
3647 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3648 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3649 && swPatches.size() > 0) {
3650 status = swPatches[0].getLatencyMs_l(&latencyMs);
3651 downstreamPatchHandle = swPatches[0].getPatchHandle();
3652 }
3653 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003654 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003655 lastDownstreamPatchHandle = downstreamPatchHandle;
3656 }
3657 if (status == OK) {
3658 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003659 // latency of 5 seconds).
3660 const double minLatency = 0., maxLatency = 5000.;
3661 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003662 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003663 } else {
3664 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003665 if (latencyMs < minLatency) latencyMs = minLatency;
3666 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003667 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003668 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003669 }
3670 mAudioFlinger->mLock.unlock();
3671 }
3672 } else {
3673 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3674 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003675 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003676 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3677 }
3678 }
3679
Eric Laurentb3f315a2021-07-13 15:09:05 +02003680 if (mCheckOutputStageEffects.exchange(false)) {
3681 checkOutputStageEffects();
3682 }
3683
Eric Laurent81784c32012-11-19 14:55:58 -08003684 { // scope for mLock
3685
3686 Mutex::Autolock _l(mLock);
3687
Eric Laurent021cf962014-05-13 10:18:14 -07003688 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003689 if (mCheckOutputStageEffects.load()) {
3690 continue;
3691 }
Eric Laurent10351942014-05-08 18:49:52 -07003692
Glenn Kasteneef598c2017-04-03 14:41:13 -07003693 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003694 if (logString != NULL) {
3695 mNBLogWriter->logTimestamp();
3696 mNBLogWriter->log(logString);
3697 logString = NULL;
3698 }
3699
Dean Wheatley12473e92021-03-18 23:00:55 +11003700 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003701
Eric Laurent81784c32012-11-19 14:55:58 -08003702 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003703 if (mSignalPending) {
3704 // A signal was raised while we were unlocked
3705 mSignalPending = false;
3706 } else if (waitingAsyncCallback_l()) {
3707 if (exitPending()) {
3708 break;
3709 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003710 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003711 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003712 releaseWakeLock_l();
3713 released = true;
3714 }
Andy Hung10cbff12017-02-21 17:30:14 -08003715
3716 const int64_t waitNs = computeWaitTimeNs_l();
3717 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3718 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3719 if (status == TIMED_OUT) {
3720 mSignalPending = true; // if timeout recheck everything
3721 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003722 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003723 if (released) {
3724 acquireWakeLock_l();
3725 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003726 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3727 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003728
3729 continue;
3730 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003731 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003732 isSuspended()) {
3733 // put audio hardware into standby after short delay
3734 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003735
3736 threadLoop_standby();
3737
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003738 // This is where we go into standby
3739 if (!mStandby) {
3740 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003741 mThreadMetrics.logEndInterval();
3742 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003743 }
Andy Hungd0979812019-02-21 15:51:44 -08003744 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003745 }
3746
Eric Tan39ec8d62018-07-24 09:49:29 -07003747 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003748 // we're about to wait, flush the binder command buffer
3749 IPCThreadState::self()->flushCommands();
3750
3751 clearOutputTracks();
3752
3753 if (exitPending()) {
3754 break;
3755 }
3756
3757 releaseWakeLock_l();
3758 // wait until we have something to do...
3759 ALOGV("%s going to sleep", myName.string());
3760 mWaitWorkCV.wait(mLock);
3761 ALOGV("%s waking up", myName.string());
3762 acquireWakeLock_l();
3763
3764 mMixerStatus = MIXER_IDLE;
3765 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3766 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003767 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003768 checkSilentMode_l();
3769
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003770 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3771 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003772 if (mType == MIXER) {
3773 sleepTimeShift = 0;
3774 }
3775
3776 continue;
3777 }
3778 }
Eric Laurent81784c32012-11-19 14:55:58 -08003779 // mMixerStatusIgnoringFastTracks is also updated internally
3780 mMixerStatus = prepareTracks_l(&tracksToRemove);
3781
Andy Hungdae27702016-10-31 14:01:16 -07003782 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003783
Kevin Rocard069c2712018-03-29 19:09:14 -07003784 updateMetadata_l();
3785
Eric Laurent81784c32012-11-19 14:55:58 -08003786 // prevent any changes in effect chain list and in each effect chain
3787 // during mixing and effect process as the audio buffers could be deleted
3788 // or modified if an effect is created or deleted
3789 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003790
3791 // Determine which session to pick up haptic data.
3792 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003793 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003794 // TODO: Write haptic data directly to sink buffer when mixing.
3795 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3796 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003797 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3798 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3799 activeHapticSessionId = track->sessionId();
3800 break;
3801 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003802 if (track->getHapticPlaybackEnabled()) {
3803 activeHapticSessionId = track->sessionId();
3804 break;
3805 }
3806 }
3807 }
3808
Andy Hungc1646382019-04-30 16:12:10 -07003809 // Acquire a local copy of active tracks with lock (release w/o lock).
3810 //
3811 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3812 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3813 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3814 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003815 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003816
Eric Laurentbfb1b832013-01-07 09:53:42 -08003817 if (mBytesRemaining == 0) {
3818 mCurrentWriteLength = 0;
3819 if (mMixerStatus == MIXER_TRACKS_READY) {
3820 // threadLoop_mix() sets mCurrentWriteLength
3821 threadLoop_mix();
3822 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3823 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003824 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003825 // must be written to HAL
3826 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003827 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003828 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003829
3830 // Tally underrun frames as we are inserting 0s here.
3831 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003832 if (track->mFillingUpStatus == Track::FS_ACTIVE
3833 && !track->isStopped()
3834 && !track->isPaused()
3835 && !track->isTerminated()) {
3836 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3837 __func__, track->id(), track->getTrackStateAsString(),
3838 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003839 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3840 }
3841 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003842 }
3843 }
Andy Hung98ef9782014-03-04 14:46:50 -08003844 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003845 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003846 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3847 // or mSinkBuffer (if there are no effects).
3848 //
3849 // This is done pre-effects computation; if effects change to
3850 // support higher precision, this needs to move.
3851 //
3852 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003853 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003854 uint32_t mixerChannelCount = mEffectBufferValid ?
3855 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003856 if (mMixerBufferValid) {
3857 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3858 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3859
Andy Hung2ddee192015-12-18 17:34:44 -08003860 // mono blend occurs for mixer threads only (not direct or offloaded)
3861 // and is handled here if we're going directly to the sink.
3862 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003863 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3864 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003865 }
3866
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003867 if (!hasFastMixer()) {
3868 // Balance must take effect after mono conversion.
3869 // We do it here if there is no FastMixer.
3870 // mBalance detects zero balance within the class for speed (not needed here).
3871 mBalance.setBalance(mMasterBalance.load());
3872 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3873 }
3874
Andy Hung98ef9782014-03-04 14:46:50 -08003875 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02003876 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08003877
3878 // If we're going directly to the sink and there are haptic channels,
3879 // we should adjust channels as the sample data is partially interleaved
3880 // in this case.
3881 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3882 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3883 mChannelCount + mHapticChannelCount,
3884 audio_bytes_per_sample(format),
3885 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3886 }
Andy Hung98ef9782014-03-04 14:46:50 -08003887 }
3888
Eric Laurentbfb1b832013-01-07 09:53:42 -08003889 mBytesRemaining = mCurrentWriteLength;
3890 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003891 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3892 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3893 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3894 mBytesWritten += mBytesRemaining;
3895 mFramesWritten += framesRemaining;
3896 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 mBytesRemaining = 0;
3898 }
Eric Laurent81784c32012-11-19 14:55:58 -08003899
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003901 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003902 for (size_t i = 0; i < effectChains.size(); i ++) {
3903 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003904 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003905 if (activeHapticSessionId != AUDIO_SESSION_NONE
3906 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003907 // Haptic data is active in this case, copy it directly from
3908 // in buffer to out buffer.
Eric Laurent39095982021-08-24 18:29:27 +02003909 uint32_t channelCount =
3910 effectChains[i]->sessionId() == AUDIO_SESSION_OUTPUT_STAGE ?
3911 mixerChannelCount : mChannelCount;
jiabin47affe52019-04-04 18:02:07 -07003912 const size_t audioBufferSize = mNormalFrameCount
Eric Laurent39095982021-08-24 18:29:27 +02003913 * audio_bytes_per_frame(channelCount, EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07003914 memcpy_by_audio_format(
3915 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3916 EFFECT_BUFFER_FORMAT,
3917 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3918 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3919 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003920 }
Eric Laurent81784c32012-11-19 14:55:58 -08003921 }
3922 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003923 // Process effect chains for offloaded thread even if no audio
3924 // was read from audio track: process only updates effect state
3925 // and thus does have to be synchronized with audio writes but may have
3926 // to be called while waiting for async write callback
3927 if (mType == OFFLOAD) {
3928 for (size_t i = 0; i < effectChains.size(); i ++) {
3929 effectChains[i]->process_l();
3930 }
3931 }
Eric Laurent81784c32012-11-19 14:55:58 -08003932
Andy Hung98ef9782014-03-04 14:46:50 -08003933 // Only if the Effects buffer is enabled and there is data in the
3934 // Effects buffer (buffer valid), we need to
3935 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003936 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003937 if (mEffectBufferValid) {
3938 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003939
3940 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003941 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3942 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003943 }
3944
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003945 if (!hasFastMixer()) {
3946 // Balance must take effect after mono conversion.
3947 // We do it here if there is no FastMixer.
3948 // mBalance detects zero balance within the class for speed (not needed here).
3949 mBalance.setBalance(mMasterBalance.load());
3950 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3951 }
3952
Eric Laurent39095982021-08-24 18:29:27 +02003953 if (mType == SPATIALIZER) {
3954 memcpy_by_audio_format(mEffectToSinkBuffer, mFormat, mEffectBuffer,
3955 mEffectBufferFormat,
3956 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3957 accumulate_by_audio_format(mSinkBuffer, mEffectToSinkBuffer, mFormat,
3958 mNormalFrameCount * mChannelCount);
3959 const size_t audioBufferSize = mNormalFrameCount
3960 * audio_bytes_per_frame(mChannelCount, mFormat);
3961 memcpy_by_audio_format(
3962 (uint8_t*)mSinkBuffer + audioBufferSize,
3963 mFormat,
3964 (uint8_t*)mEffectToSinkBuffer + audioBufferSize,
3965 mFormat, mNormalFrameCount * mHapticChannelCount);
3966 } else {
3967 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3968 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3969 }
jiabin245cdd92018-12-07 17:55:15 -08003970 // The sample data is partially interleaved when haptic channels exist,
3971 // we need to adjust channels here.
3972 if (mHapticChannelCount > 0) {
3973 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3974 mChannelCount + mHapticChannelCount,
3975 audio_bytes_per_sample(mFormat),
3976 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3977 }
Andy Hung98ef9782014-03-04 14:46:50 -08003978 }
3979
Eric Laurent81784c32012-11-19 14:55:58 -08003980 // enable changes in effect chain
3981 unlockEffectChains(effectChains);
3982
Eric Laurentbfb1b832013-01-07 09:53:42 -08003983 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003984 // mSleepTimeUs == 0 means we must write to audio hardware
3985 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003986 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003987 // writePeriodNs is updated >= 0 when ret > 0.
3988 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003989 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003990 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003991 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003992 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003993 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003994 if (ret < 0) {
3995 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003996 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003997 mBytesWritten += ret;
3998 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003999 const int64_t frames = ret / mFrameSize;
4000 mFramesWritten += frames;
4001
4002 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4003 // process information relating to write time.
4004 if (audio_has_proportional_frames(mFormat)) {
4005 // we are in a continuous mixing cycle
4006 if (mMixerStatus == MIXER_TRACKS_READY &&
4007 loopCount == lastLoopCountWritten + 1) {
4008
4009 const double jitterMs =
4010 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4011 {frames, writePeriodNs},
4012 {0, 0} /* lastTimestamp */, mSampleRate);
4013 const double processMs =
4014 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4015
4016 Mutex::Autolock _l(mLock);
4017 mIoJitterMs.add(jitterMs);
4018 mProcessTimeMs.add(processMs);
4019 }
4020
4021 // write blocked detection
4022 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
4023 if (mType == MIXER && deltaWriteNs > maxPeriod) {
4024 mNumDelayedWrites++;
4025 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4026 ATRACE_NAME("underrun");
4027 ALOGW("write blocked for %lld msecs, "
4028 "%d delayed writes, thread %d",
4029 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4030 mNumDelayedWrites, mId);
4031 lastWarning = lastIoEndNs;
4032 }
4033 }
4034 }
4035 // update timing info.
4036 mLastIoBeginNs = lastIoBeginNs;
4037 mLastIoEndNs = lastIoEndNs;
4038 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004039 }
4040 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4041 (mMixerStatus == MIXER_DRAIN_ALL)) {
4042 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004043 }
Andy Hung08fb1742015-05-31 23:22:10 -07004044 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004045
4046 if (mThreadThrottle
4047 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004048 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004049 // Limit MixerThread data processing to no more than twice the
4050 // expected processing rate.
4051 //
4052 // This helps prevent underruns with NuPlayer and other applications
4053 // which may set up buffers that are close to the minimum size, or use
4054 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4055 //
4056 // The throttle smooths out sudden large data drains from the device,
4057 // e.g. when it comes out of standby, which often causes problems with
4058 // (1) mixer threads without a fast mixer (which has its own warm-up)
4059 // (2) minimum buffer sized tracks (even if the track is full,
4060 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004061 //
4062 // Total time spent in last processing cycle equals time spent in
4063 // 1. threadLoop_write, as well as time spent in
4064 // 2. threadLoop_mix (significant for heavy mixing, especially
4065 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004066
Andy Hung446f4df2019-02-21 12:26:41 -08004067 // it's OK if deltaMs is an overestimate.
4068
4069 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004070
Ivan Lozanoea04d392017-11-07 14:37:07 -08004071 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004072 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004073 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004074
Andy Hung08fb1742015-05-31 23:22:10 -07004075 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004076 // notify of throttle start on verbose log
4077 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4078 "mixer(%p) throttle begin:"
4079 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004080 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004081 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004082 // Throttle must be attributed to the previous mixer loop's write time
4083 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004084 // This also ensures proper timing statistics.
4085 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004086 } else {
4087 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4088 if (diff > 0) {
4089 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004090 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004091 ALOGD_IF(!isSingleDeviceType(
4092 outDeviceTypes(), audio_is_a2dp_out_device) &&
4093 !isSingleDeviceType(
4094 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004095 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004096 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4097 }
Andy Hung08fb1742015-05-31 23:22:10 -07004098 }
4099 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100 }
Eric Laurent81784c32012-11-19 14:55:58 -08004101
Eric Laurentbfb1b832013-01-07 09:53:42 -08004102 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004103 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004104 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004105 // suspended requires accurate metering of sleep time.
4106 if (isSuspended()) {
4107 // advance by expected sleepTime
4108 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4109 const nsecs_t nowNs = systemTime();
4110
4111 // compute expected next time vs current time.
4112 // (negative deltas are treated as delays).
4113 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4114 if (deltaNs < -kMaxNextBufferDelayNs) {
4115 // Delays longer than the max allowed trigger a reset.
4116 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4117 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4118 timeLoopNextNs = nowNs + deltaNs;
4119 } else if (deltaNs < 0) {
4120 // Delays within the max delay allowed: zero the delta/sleepTime
4121 // to help the system catch up in the next iteration(s)
4122 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4123 deltaNs = 0;
4124 }
4125 // update sleep time (which is >= 0)
4126 mSleepTimeUs = deltaNs / 1000;
4127 }
Eric Laurente93cc032016-05-05 10:15:10 -07004128 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4129 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004130 }
Glenn Kastene7754022014-10-31 12:11:26 -07004131 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132 }
Eric Laurent81784c32012-11-19 14:55:58 -08004133 }
4134
4135 // Finally let go of removed track(s), without the lock held
4136 // since we can't guarantee the destructors won't acquire that
4137 // same lock. This will also mutate and push a new fast mixer state.
4138 threadLoop_removeTracks(tracksToRemove);
4139 tracksToRemove.clear();
4140
4141 // FIXME I don't understand the need for this here;
4142 // it was in the original code but maybe the
4143 // assignment in saveOutputTracks() makes this unnecessary?
4144 clearOutputTracks();
4145
4146 // Effect chains will be actually deleted here if they were removed from
4147 // mEffectChains list during mixing or effects processing
4148 effectChains.clear();
4149
4150 // FIXME Note that the above .clear() is no longer necessary since effectChains
4151 // is now local to this block, but will keep it for now (at least until merge done).
4152 }
4153
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 threadLoop_exit();
4155
Eric Laurentcf817a22014-08-04 20:36:31 -07004156 if (!mStandby) {
4157 threadLoop_standby();
4158 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004159 }
4160
4161 releaseWakeLock();
4162
4163 ALOGV("Thread %p type %d exiting", this, mType);
4164 return false;
4165}
4166
Dean Wheatley12473e92021-03-18 23:00:55 +11004167void AudioFlinger::PlaybackThread::collectTimestamps_l()
4168{
4169 // Collect timestamp statistics for the Playback Thread types that support it.
4170 if (mType != MIXER
4171 && mType != DUPLICATING
4172 && mType != DIRECT
4173 && mType != OFFLOAD) {
4174 return;
4175 }
4176 if (mStandby) {
4177 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4178 return;
4179 } else if (mHwPaused) {
4180 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4181 return;
4182 }
4183
4184 // Gather the framesReleased counters for all active tracks,
4185 // and associate with the sink frames written out. We need
4186 // this to convert the sink timestamp to the track timestamp.
4187 bool kernelLocationUpdate = false;
4188 ExtendedTimestamp timestamp; // use private copy to fetch
4189
4190 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4191 // HAL may be draining some small duration buffered data for fade out.
4192 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4193 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4194 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4195 mSampleRate);
4196
4197 if (isTimestampCorrectionEnabled()) {
4198 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4199 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4200 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4201 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4202 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4203 = correctedTimestamp.mFrames;
4204 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4205 = correctedTimestamp.mTimeNs;
4206 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4207 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4208 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4209
4210 // Note: Downstream latency only added if timestamp correction enabled.
4211 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4212 const int64_t newPosition =
4213 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4214 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4215 // prevent retrograde
4216 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4217 newPosition,
4218 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4219 - mSuspendedFrames));
4220 }
4221 }
4222
4223 // We always fetch the timestamp here because often the downstream
4224 // sink will block while writing.
4225
4226 // We keep track of the last valid kernel position in case we are in underrun
4227 // and the normal mixer period is the same as the fast mixer period, or there
4228 // is some error from the HAL.
4229 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4230 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4231 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4232 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4233 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4234
4235 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4236 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4237 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4238 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4239 }
4240
4241 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4242 kernelLocationUpdate = true;
4243 } else {
4244 ALOGVV("getTimestamp error - no valid kernel position");
4245 }
4246
4247 // copy over kernel info
4248 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4249 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4250 + mSuspendedFrames; // add frames discarded when suspended
4251 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4252 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4253 } else {
4254 mTimestampVerifier.error();
4255 }
4256
4257 // mFramesWritten for non-offloaded tracks are contiguous
4258 // even after standby() is called. This is useful for the track frame
4259 // to sink frame mapping.
4260 bool serverLocationUpdate = false;
4261 if (mFramesWritten != mLastFramesWritten) {
4262 serverLocationUpdate = true;
4263 mLastFramesWritten = mFramesWritten;
4264 }
4265 // Only update timestamps if there is a meaningful change.
4266 // Either the kernel timestamp must be valid or we have written something.
4267 if (kernelLocationUpdate || serverLocationUpdate) {
4268 if (serverLocationUpdate) {
4269 // use the time before we called the HAL write - it is a bit more accurate
4270 // to when the server last read data than the current time here.
4271 //
4272 // If we haven't written anything, mLastIoBeginNs will be -1
4273 // and we use systemTime().
4274 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4275 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4276 ? systemTime() : mLastIoBeginNs;
4277 }
4278
4279 for (const sp<Track> &t : mActiveTracks) {
4280 if (!t->isFastTrack()) {
4281 t->updateTrackFrameInfo(
4282 t->mAudioTrackServerProxy->framesReleased(),
4283 mFramesWritten,
4284 mSampleRate,
4285 mTimestamp);
4286 }
4287 }
4288 }
4289
4290 if (audio_has_proportional_frames(mFormat)) {
4291 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4292 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4293 mLatencyMs.add(latencyMs);
4294 }
4295 }
4296#if 0
4297 // logFormat example
4298 if (z % 100 == 0) {
4299 timespec ts;
4300 clock_gettime(CLOCK_MONOTONIC, &ts);
4301 LOGT("This is an integer %d, this is a float %f, this is my "
4302 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4303 LOGT("A deceptive null-terminated string %\0");
4304 }
4305 ++z;
4306#endif
4307}
4308
Eric Laurentbfb1b832013-01-07 09:53:42 -08004309// removeTracks_l() must be called with ThreadBase::mLock held
4310void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4311{
Andy Hungfe726a62018-09-27 15:17:25 -07004312 for (const auto& track : tracksToRemove) {
4313 mActiveTracks.remove(track);
4314 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4315 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4316 if (chain != 0) {
4317 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4318 __func__, track->id(), chain.get(), track->sessionId());
4319 chain->decActiveTrackCnt();
4320 }
4321 // If an external client track, inform APM we're no longer active, and remove if needed.
4322 // We do this under lock so that the state is consistent if the Track is destroyed.
4323 if (track->isExternalTrack()) {
4324 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004325 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004326 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327 }
4328 }
Andy Hungfe726a62018-09-27 15:17:25 -07004329 if (track->isTerminated()) {
4330 // remove from our tracks vector
4331 removeTrack_l(track);
4332 }
jiabineb3bda02020-06-30 14:07:03 -07004333 if (mHapticChannelCount > 0 &&
4334 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4335 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004336 mLock.unlock();
4337 // Unlock due to VibratorService will lock for this call and will
4338 // call Tracks.mute/unmute which also require thread's lock.
4339 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4340 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004341
4342 // When the track is stop, set the haptic intensity as MUTE
4343 // for the HapticGenerator effect.
4344 if (chain != nullptr) {
4345 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4346 }
jiabin245cdd92018-12-07 17:55:15 -08004347 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004348 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004349}
Eric Laurent81784c32012-11-19 14:55:58 -08004350
Eric Laurentaccc1472013-09-20 09:36:34 -07004351status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4352{
4353 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004354 ExtendedTimestamp ets;
4355 status_t status = mNormalSink->getTimestamp(ets);
4356 if (status == NO_ERROR) {
4357 status = ets.getBestTimestamp(&timestamp);
4358 }
4359 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004360 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004361 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004362 collectTimestamps_l();
4363 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4364 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004365 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004366 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4367 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4368 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4369 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4370 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004371 }
4372 return INVALID_OPERATION;
4373}
Eric Laurent1c333e22014-05-20 10:48:17 -07004374
Eric Laurenteab90452019-06-24 15:17:46 -07004375// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4376// still applied by the mixer.
4377// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4378// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4379// if more than one track are active
4380status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4381{
4382 status_t result = NO_ERROR;
4383 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4384 if (*volume != mLeftVolFloat) {
4385 result = mOutput->stream->setVolume(*volume, *volume);
4386 ALOGE_IF(result != OK,
4387 "Error when setting output stream volume: %d", result);
4388 if (result == NO_ERROR) {
4389 mLeftVolFloat = *volume;
4390 }
4391 }
4392 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4393 // remove stream volume contribution from software volume.
4394 if (mLeftVolFloat == *volume) {
4395 *volume = 1.0f;
4396 }
4397 }
4398 return result;
4399}
4400
Eric Laurent054d9d32015-04-24 08:48:48 -07004401status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4402 audio_patch_handle_t *handle)
4403{
Andy Hungf60abce2016-08-26 11:37:54 -07004404 status_t status;
4405 if (property_get_bool("af.patch_park", false /* default_value */)) {
4406 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4407 // or if HAL does not properly lock against access.
4408 AutoPark<FastMixer> park(mFastMixer);
4409 status = PlaybackThread::createAudioPatch_l(patch, handle);
4410 } else {
4411 status = PlaybackThread::createAudioPatch_l(patch, handle);
4412 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004413 return status;
4414}
4415
Eric Laurent1c333e22014-05-20 10:48:17 -07004416status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4417 audio_patch_handle_t *handle)
4418{
4419 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004420
4421 // store new device and send to effects
4422 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004423 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004424 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004425 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4426 && !mOutput->audioHwDev->supportsAudioPatches(),
4427 "Enumerated device type(%#x) must not be used "
4428 "as it does not support audio patches",
4429 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004430 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004431 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4432 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004433 }
4434
François Gaffie0c280aa2018-07-25 10:02:15 +02004435 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004436#ifdef ADD_BATTERY_DATA
4437 // when changing the audio output device, call addBatteryData to notify
4438 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004439 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004440 uint32_t params = 0;
4441 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004442 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004443 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004444 }
4445
Eric Laurent054d9d32015-04-24 08:48:48 -07004446 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004447 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004448 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4449 }
4450
4451 if (params != 0) {
4452 addBatteryData(params);
4453 }
4454 }
4455#endif
4456
4457 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004458 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004459 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004460
jiabinc52b1ff2019-10-31 17:20:42 -07004461 // mPatch.num_sinks is not set when the thread is created so that
4462 // the first patch creation triggers an ioConfigChanged callback
4463 bool configChanged = (mPatch.num_sinks == 0) ||
4464 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004465 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004466 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004467 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004468
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004469 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004470 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4471 status = hwDevice->createAudioPatch(patch->num_sources,
4472 patch->sources,
4473 patch->num_sinks,
4474 patch->sinks,
4475 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004476 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004477 char *address;
4478 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4479 //FIXME: we only support address on first sink with HAL version < 3.0
4480 address = audio_device_address_to_parameter(
4481 patch->sinks[0].ext.device.type,
4482 patch->sinks[0].ext.device.address);
4483 } else {
4484 address = (char *)calloc(1, 1);
4485 }
4486 AudioParameter param = AudioParameter(String8(address));
4487 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004488 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004489 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004490 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004491 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004492 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004493
4494 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004495 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004496 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004497 // also dispatch to active AudioTracks for MediaMetrics
4498 for (const auto &track : mActiveTracks) {
4499 track->logEndInterval();
4500 track->logBeginInterval(patchSinksAsString);
4501 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004502
Eric Laurente8726fe2015-06-26 09:39:24 -07004503 if (configChanged) {
4504 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4505 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004506 return status;
4507}
4508
Eric Laurent054d9d32015-04-24 08:48:48 -07004509status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4510{
Andy Hungf60abce2016-08-26 11:37:54 -07004511 status_t status;
4512 if (property_get_bool("af.patch_park", false /* default_value */)) {
4513 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4514 // or if HAL does not properly lock against access.
4515 AutoPark<FastMixer> park(mFastMixer);
4516 status = PlaybackThread::releaseAudioPatch_l(handle);
4517 } else {
4518 status = PlaybackThread::releaseAudioPatch_l(handle);
4519 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004520 return status;
4521}
4522
Eric Laurent1c333e22014-05-20 10:48:17 -07004523status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4524{
4525 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004526
jiabinc52b1ff2019-10-31 17:20:42 -07004527 mPatch = audio_patch{};
4528 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004529
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004530 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004531 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4532 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004533 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004534 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004535 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004536 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004537 }
4538 return status;
4539}
4540
Eric Laurent83b88082014-06-20 18:31:16 -07004541void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4542{
4543 Mutex::Autolock _l(mLock);
4544 mTracks.add(track);
4545}
4546
4547void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4548{
4549 Mutex::Autolock _l(mLock);
4550 destroyTrack_l(track);
4551}
4552
Mikhail Naganovdc769682018-05-04 15:34:08 -07004553void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004554{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004555 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004556 config->role = AUDIO_PORT_ROLE_SOURCE;
4557 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4558 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004559 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4560 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4561 config->flags.output = mOutput->flags;
4562 }
Eric Laurent83b88082014-06-20 18:31:16 -07004563}
4564
Eric Laurent81784c32012-11-19 14:55:58 -08004565// ----------------------------------------------------------------------------
4566
4567AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004568 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4569 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004570 // mAudioMixer below
4571 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004572 mFastMixerFutex(0),
4573 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004574 // mOutputSink below
4575 // mPipeSink below
4576 // mNormalSink below
4577{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004578 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004579 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004580 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004581 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004582 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4583 mNormalFrameCount);
4584 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4585
Andy Hungfbfc3952015-01-15 13:33:51 -08004586 if (type == DUPLICATING) {
4587 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4588 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4589 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4590 return;
4591 }
Eric Laurent81784c32012-11-19 14:55:58 -08004592 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004593 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004594 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004595 const NBAIO_Format offers[1] = {Format_from_SR_C(
4596 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004597#if !LOG_NDEBUG
4598 ssize_t index =
4599#else
4600 (void)
4601#endif
4602 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004603 ALOG_ASSERT(index == 0);
4604
4605 // initialize fast mixer depending on configuration
4606 bool initFastMixer;
4607 switch (kUseFastMixer) {
4608 case FastMixer_Never:
4609 initFastMixer = false;
4610 break;
4611 case FastMixer_Always:
4612 initFastMixer = true;
4613 break;
4614 case FastMixer_Static:
4615 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004616 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4617 // where the period is less than an experimentally determined threshold that can be
4618 // scheduled reliably with CFS. However, the BT A2DP HAL is
4619 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4620 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004621 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004622 break;
4623 }
Eric Laurent39095982021-08-24 18:29:27 +02004624 ALOG_ASSERT(initFastMixer && mType == SPATIALIZER);
Andy Hungfda69402017-02-15 14:33:12 -08004625 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4626 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4627 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004628 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004629 audio_format_t fastMixerFormat;
4630 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4631 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4632 } else {
4633 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4634 }
4635 if (mFormat != fastMixerFormat) {
4636 // change our Sink format to accept our intermediate precision
4637 mFormat = fastMixerFormat;
4638 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004639 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004640 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4641 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4642 }
Eric Laurent81784c32012-11-19 14:55:58 -08004643
4644 // create a MonoPipe to connect our submix to FastMixer
4645 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004646
Andy Hung1258c1a2014-05-23 21:22:17 -07004647 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004648 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004649 format.mFormat = fastMixerFormat;
4650 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4651
Eric Laurent81784c32012-11-19 14:55:58 -08004652 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4653 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4654 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4655 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4656 const NBAIO_Format offers[1] = {format};
4657 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004658#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004659 ssize_t index =
4660#else
4661 (void)
4662#endif
4663 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004664 ALOG_ASSERT(index == 0);
4665 monoPipe->setAvgFrames((mScreenState & 1) ?
4666 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4667 mPipeSink = monoPipe;
4668
Eric Laurent81784c32012-11-19 14:55:58 -08004669 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004670 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004671 FastMixerStateQueue *sq = mFastMixer->sq();
4672#ifdef STATE_QUEUE_DUMP
4673 sq->setObserverDump(&mStateQueueObserverDump);
4674 sq->setMutatorDump(&mStateQueueMutatorDump);
4675#endif
4676 FastMixerState *state = sq->begin();
4677 FastTrack *fastTrack = &state->mFastTracks[0];
4678 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4679 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4680 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004681 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4682 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4683 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004684 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004685 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004686 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004687 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004688 fastTrack->mGeneration++;
4689 state->mFastTracksGen++;
4690 state->mTrackMask = 1;
4691 // fast mixer will use the HAL output sink
4692 state->mOutputSink = mOutputSink.get();
4693 state->mOutputSinkGen++;
4694 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004695 // specify sink channel mask when haptic channel mask present as it can not
4696 // be calculated directly from channel count
4697 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004698 ? AUDIO_CHANNEL_NONE
4699 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004700 state->mCommand = FastMixerState::COLD_IDLE;
4701 // already done in constructor initialization list
4702 //mFastMixerFutex = 0;
4703 state->mColdFutexAddr = &mFastMixerFutex;
4704 state->mColdGen++;
4705 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004706 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4707 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004708 sq->end();
4709 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4710
Eric Tan0513b5d2018-09-17 10:32:48 -07004711 NBLog::thread_info_t info;
4712 info.id = mId;
4713 info.type = NBLog::FASTMIXER;
4714 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4715
Eric Laurent81784c32012-11-19 14:55:58 -08004716 // start the fast mixer
4717 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4718 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004719 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004720 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004721
4722#ifdef AUDIO_WATCHDOG
4723 // create and start the watchdog
4724 mAudioWatchdog = new AudioWatchdog();
4725 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4726 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4727 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004728 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004729#endif
Andy Hung8946a282018-04-19 20:04:56 -07004730 } else {
4731#ifdef TEE_SINK
4732 // Only use the MixerThread tee if there is no FastMixer.
4733 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4734 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4735#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004736 }
4737
4738 switch (kUseFastMixer) {
4739 case FastMixer_Never:
4740 case FastMixer_Dynamic:
4741 mNormalSink = mOutputSink;
4742 break;
4743 case FastMixer_Always:
4744 mNormalSink = mPipeSink;
4745 break;
4746 case FastMixer_Static:
4747 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4748 break;
4749 }
4750}
4751
4752AudioFlinger::MixerThread::~MixerThread()
4753{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004754 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004755 FastMixerStateQueue *sq = mFastMixer->sq();
4756 FastMixerState *state = sq->begin();
4757 if (state->mCommand == FastMixerState::COLD_IDLE) {
4758 int32_t old = android_atomic_inc(&mFastMixerFutex);
4759 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004760 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004761 }
4762 }
4763 state->mCommand = FastMixerState::EXIT;
4764 sq->end();
4765 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4766 mFastMixer->join();
4767 // Though the fast mixer thread has exited, it's state queue is still valid.
4768 // We'll use that extract the final state which contains one remaining fast track
4769 // corresponding to our sub-mix.
4770 state = sq->begin();
4771 ALOG_ASSERT(state->mTrackMask == 1);
4772 FastTrack *fastTrack = &state->mFastTracks[0];
4773 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4774 delete fastTrack->mBufferProvider;
4775 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004776 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004777#ifdef AUDIO_WATCHDOG
4778 if (mAudioWatchdog != 0) {
4779 mAudioWatchdog->requestExit();
4780 mAudioWatchdog->requestExitAndWait();
4781 mAudioWatchdog.clear();
4782 }
4783#endif
4784 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004785 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004786 delete mAudioMixer;
4787}
4788
4789
4790uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4791{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004792 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004793 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4794 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4795 }
4796 return latency;
4797}
4798
Eric Laurentbfb1b832013-01-07 09:53:42 -08004799ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004800{
4801 // FIXME we should only do one push per cycle; confirm this is true
4802 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004803 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004804 FastMixerStateQueue *sq = mFastMixer->sq();
4805 FastMixerState *state = sq->begin();
4806 if (state->mCommand != FastMixerState::MIX_WRITE &&
4807 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4808 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004809
4810 // FIXME workaround for first HAL write being CPU bound on some devices
4811 ATRACE_BEGIN("write");
4812 mOutput->write((char *)mSinkBuffer, 0);
4813 ATRACE_END();
4814
Eric Laurent81784c32012-11-19 14:55:58 -08004815 int32_t old = android_atomic_inc(&mFastMixerFutex);
4816 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004817 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004818 }
4819#ifdef AUDIO_WATCHDOG
4820 if (mAudioWatchdog != 0) {
4821 mAudioWatchdog->resume();
4822 }
4823#endif
4824 }
4825 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004826#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004827 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004828 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004829#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004830 sq->end();
4831 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4832 if (kUseFastMixer == FastMixer_Dynamic) {
4833 mNormalSink = mPipeSink;
4834 }
4835 } else {
4836 sq->end(false /*didModify*/);
4837 }
4838 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004839 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004840}
4841
4842void AudioFlinger::MixerThread::threadLoop_standby()
4843{
4844 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004845 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004846 FastMixerStateQueue *sq = mFastMixer->sq();
4847 FastMixerState *state = sq->begin();
4848 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004849 // Report any frames trapped in the Monopipe
4850 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4851 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4852 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4853 "monoPipeWritten:%lld monoPipeLeft:%lld",
4854 (long long)mFramesWritten, (long long)mSuspendedFrames,
4855 (long long)mPipeSink->framesWritten(), pipeFrames);
4856 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4857
Eric Laurent81784c32012-11-19 14:55:58 -08004858 state->mCommand = FastMixerState::COLD_IDLE;
4859 state->mColdFutexAddr = &mFastMixerFutex;
4860 state->mColdGen++;
4861 mFastMixerFutex = 0;
4862 sq->end();
4863 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4864 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4865 if (kUseFastMixer == FastMixer_Dynamic) {
4866 mNormalSink = mOutputSink;
4867 }
4868#ifdef AUDIO_WATCHDOG
4869 if (mAudioWatchdog != 0) {
4870 mAudioWatchdog->pause();
4871 }
4872#endif
4873 } else {
4874 sq->end(false /*didModify*/);
4875 }
4876 }
4877 PlaybackThread::threadLoop_standby();
4878}
4879
Eric Laurentbfb1b832013-01-07 09:53:42 -08004880bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4881{
4882 return false;
4883}
4884
4885bool AudioFlinger::PlaybackThread::shouldStandby_l()
4886{
4887 return !mStandby;
4888}
4889
4890bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4891{
4892 Mutex::Autolock _l(mLock);
4893 return waitingAsyncCallback_l();
4894}
4895
Eric Laurent81784c32012-11-19 14:55:58 -08004896// shared by MIXER and DIRECT, overridden by DUPLICATING
4897void AudioFlinger::PlaybackThread::threadLoop_standby()
4898{
4899 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004900 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004901 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004902 // discard any pending drain or write ack by incrementing sequence
4903 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4904 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004905 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004906 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4907 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004908 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004909 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004910}
4911
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004912void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4913{
4914 ALOGV("signal playback thread");
4915 broadcast_l();
4916}
4917
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004918void AudioFlinger::PlaybackThread::onAsyncError()
4919{
4920 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4921 invalidateTracks((audio_stream_type_t)i);
4922 }
4923}
4924
Eric Laurent81784c32012-11-19 14:55:58 -08004925void AudioFlinger::MixerThread::threadLoop_mix()
4926{
Eric Laurent81784c32012-11-19 14:55:58 -08004927 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004928 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004929 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004930 // increase sleep time progressively when application underrun condition clears.
4931 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4932 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4933 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004934 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004935 sleepTimeShift--;
4936 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004937 mSleepTimeUs = 0;
4938 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004939 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004940
Eric Laurent81784c32012-11-19 14:55:58 -08004941}
4942
4943void AudioFlinger::MixerThread::threadLoop_sleepTime()
4944{
4945 // If no tracks are ready, sleep once for the duration of an output
4946 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004947 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004948 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004949 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4950 // Using the Monopipe availableToWrite, we estimate the
4951 // sleep time to retry for more data (before we underrun).
4952 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4953 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4954 const size_t pipeFrames = monoPipe->maxFrames();
4955 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4956 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4957 const size_t framesDelay = std::min(
4958 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4959 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4960 pipeFrames, framesLeft, framesDelay);
4961 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4962 } else {
4963 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4964 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4965 mSleepTimeUs = kMinThreadSleepTimeUs;
4966 }
4967 // reduce sleep time in case of consecutive application underruns to avoid
4968 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4969 // duration we would end up writing less data than needed by the audio HAL if
4970 // the condition persists.
4971 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4972 sleepTimeShift++;
4973 }
Eric Laurent81784c32012-11-19 14:55:58 -08004974 }
4975 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004976 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004977 }
4978 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004979 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4980 // before effects processing or output.
4981 if (mMixerBufferValid) {
4982 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02004983 if (mType == SPATIALIZER) {
4984 memset(mSinkBuffer, 0, mSinkBufferSize);
4985 }
Andy Hung98ef9782014-03-04 14:46:50 -08004986 } else {
4987 memset(mSinkBuffer, 0, mSinkBufferSize);
4988 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004989 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004990 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4991 "anticipated start");
4992 }
4993 // TODO add standby time extension fct of effect tail
4994}
4995
4996// prepareTracks_l() must be called with ThreadBase::mLock held
4997AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4998 Vector< sp<Track> > *tracksToRemove)
4999{
Andy Hungc0691382018-09-12 18:01:57 -07005000 // clean up deleted track ids in AudioMixer before allocating new tracks
5001 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5002 // for each trackId, destroy it in the AudioMixer
5003 if (mAudioMixer->exists(trackId)) {
5004 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005005 }
5006 });
Andy Hungc0691382018-09-12 18:01:57 -07005007 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005008
5009 mixer_state mixerStatus = MIXER_IDLE;
5010 // find out which tracks need to be processed
5011 size_t count = mActiveTracks.size();
5012 size_t mixedTracks = 0;
5013 size_t tracksWithEffect = 0;
5014 // counts only _active_ fast tracks
5015 size_t fastTracks = 0;
5016 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5017
5018 float masterVolume = mMasterVolume;
5019 bool masterMute = mMasterMute;
5020
5021 if (masterMute) {
5022 masterVolume = 0;
5023 }
5024 // Delegate master volume control to effect in output mix effect chain if needed
5025 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5026 if (chain != 0) {
5027 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5028 chain->setVolume_l(&v, &v);
5029 masterVolume = (float)((v + (1 << 23)) >> 24);
5030 chain.clear();
5031 }
5032
5033 // prepare a new state to push
5034 FastMixerStateQueue *sq = NULL;
5035 FastMixerState *state = NULL;
5036 bool didModify = false;
5037 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005038 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005039 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005040 sq = mFastMixer->sq();
5041 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005042 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005043 }
5044
Andy Hung69aed5f2014-02-25 17:24:40 -08005045 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005046 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005047
Andy Hungbd3b2b02018-05-21 10:53:11 -07005048 // DeferredOperations handles statistics after setting mixerStatus.
5049 class DeferredOperations {
5050 public:
Andy Hungea840382020-05-05 21:50:17 -07005051 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5052 : mMixerStatus(mixerStatus)
5053 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005054
5055 // when leaving scope, tally frames properly.
5056 ~DeferredOperations() {
5057 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5058 // because that is when the underrun occurs.
5059 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005060 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005061 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005062 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005063 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005064 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005065 }
5066 }
Andy Hungea840382020-05-05 21:50:17 -07005067 // send the max underrun frames for this mixer period
5068 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005069 }
5070
5071 // tallyUnderrunFrames() is called to update the track counters
5072 // with the number of underrun frames for a particular mixer period.
5073 // We defer tallying until we know the final mixer status.
5074 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5075 mUnderrunFrames.emplace_back(track, underrunFrames);
5076 }
5077
5078 private:
5079 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005080 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005081 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005082 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005083 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005084
jiabin245cdd92018-12-07 17:55:15 -08005085 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005086 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005087 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005088
5089 // this const just means the local variable doesn't change
5090 Track* const track = t.get();
5091
5092 // process fast tracks
5093 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005094 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5095 "%s(%d): FastTrack(%d) present without FastMixer",
5096 __func__, id(), track->id());
5097
jiabin245cdd92018-12-07 17:55:15 -08005098 if (track->getHapticPlaybackEnabled()) {
5099 noFastHapticTrack = false;
5100 }
Eric Laurent81784c32012-11-19 14:55:58 -08005101
5102 // It's theoretically possible (though unlikely) for a fast track to be created
5103 // and then removed within the same normal mix cycle. This is not a problem, as
5104 // the track never becomes active so it's fast mixer slot is never touched.
5105 // The converse, of removing an (active) track and then creating a new track
5106 // at the identical fast mixer slot within the same normal mix cycle,
5107 // is impossible because the slot isn't marked available until the end of each cycle.
5108 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005109 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005110 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5111 FastTrack *fastTrack = &state->mFastTracks[j];
5112
5113 // Determine whether the track is currently in underrun condition,
5114 // and whether it had a recent underrun.
5115 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5116 FastTrackUnderruns underruns = ftDump->mUnderruns;
5117 uint32_t recentFull = (underruns.mBitFields.mFull -
5118 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5119 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5120 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5121 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5122 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5123 uint32_t recentUnderruns = recentPartial + recentEmpty;
5124 track->mObservedUnderruns = underruns;
5125 // don't count underruns that occur while stopping or pausing
5126 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005127 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005128 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5129 recentUnderruns > 0) {
5130 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005131 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005132 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005133 // Immediately account for FastTrack underruns.
5134 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005135
5136 // This is similar to the state machine for normal tracks,
5137 // with a few modifications for fast tracks.
5138 bool isActive = true;
5139 switch (track->mState) {
5140 case TrackBase::STOPPING_1:
5141 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005142 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005143 track->mState = TrackBase::STOPPING_2;
5144 }
5145 break;
5146 case TrackBase::PAUSING:
5147 // ramp down is not yet implemented
5148 track->setPaused();
5149 break;
5150 case TrackBase::RESUMING:
5151 // ramp up is not yet implemented
5152 track->mState = TrackBase::ACTIVE;
5153 break;
5154 case TrackBase::ACTIVE:
5155 if (recentFull > 0 || recentPartial > 0) {
5156 // track has provided at least some frames recently: reset retry count
5157 track->mRetryCount = kMaxTrackRetries;
5158 }
5159 if (recentUnderruns == 0) {
5160 // no recent underruns: stay active
5161 break;
5162 }
5163 // there has recently been an underrun of some kind
5164 if (track->sharedBuffer() == 0) {
5165 // were any of the recent underruns "empty" (no frames available)?
5166 if (recentEmpty == 0) {
5167 // no, then ignore the partial underruns as they are allowed indefinitely
5168 break;
5169 }
5170 // there has recently been an "empty" underrun: decrement the retry counter
5171 if (--(track->mRetryCount) > 0) {
5172 break;
5173 }
5174 // indicate to client process that the track was disabled because of underrun;
5175 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005176 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005177 // remove from active list, but state remains ACTIVE [confusing but true]
5178 isActive = false;
5179 break;
5180 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005181 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005182 case TrackBase::STOPPING_2:
5183 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005184 case TrackBase::STOPPED:
5185 case TrackBase::FLUSHED: // flush() while active
5186 // Check for presentation complete if track is inactive
5187 // We have consumed all the buffers of this track.
5188 // This would be incomplete if we auto-paused on underrun
5189 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005190 uint32_t latency = 0;
5191 status_t result = mOutput->stream->getLatency(&latency);
5192 ALOGE_IF(result != OK,
5193 "Error when retrieving output stream latency: %d", result);
5194 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005195 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005196 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5197 // track stays in active list until presentation is complete
5198 break;
5199 }
5200 }
5201 if (track->isStopping_2()) {
5202 track->mState = TrackBase::STOPPED;
5203 }
5204 if (track->isStopped()) {
5205 // Can't reset directly, as fast mixer is still polling this track
5206 // track->reset();
5207 // So instead mark this track as needing to be reset after push with ack
5208 resetMask |= 1 << i;
5209 }
5210 isActive = false;
5211 break;
5212 case TrackBase::IDLE:
5213 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005214 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005215 }
5216
5217 if (isActive) {
5218 // was it previously inactive?
5219 if (!(state->mTrackMask & (1 << j))) {
5220 ExtendedAudioBufferProvider *eabp = track;
5221 VolumeProvider *vp = track;
5222 fastTrack->mBufferProvider = eabp;
5223 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005224 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005225 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005226 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005227 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005228 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005229 fastTrack->mGeneration++;
5230 state->mTrackMask |= 1 << j;
5231 didModify = true;
5232 // no acknowledgement required for newly active tracks
5233 }
Kevin Rocard12381092018-04-11 09:19:59 -07005234 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005235 float volume;
5236 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5237 volume = 0.f;
5238 } else {
5239 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5240 }
5241
5242 handleVoipVolume_l(&volume);
5243
Eric Laurent81784c32012-11-19 14:55:58 -08005244 // cache the combined master volume and stream type volume for fast mixer; this
5245 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005246 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005247 proxy->framesReleased()).first;
5248 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005249 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005250 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5251 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5252 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005253
Kevin Rocard12381092018-04-11 09:19:59 -07005254 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005255 ++fastTracks;
5256 } else {
5257 // was it previously active?
5258 if (state->mTrackMask & (1 << j)) {
5259 fastTrack->mBufferProvider = NULL;
5260 fastTrack->mGeneration++;
5261 state->mTrackMask &= ~(1 << j);
5262 didModify = true;
5263 // If any fast tracks were removed, we must wait for acknowledgement
5264 // because we're about to decrement the last sp<> on those tracks.
5265 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5266 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005267 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5268 // AudioTrack may start (which may not be with a start() but with a write()
5269 // after underrun) and immediately paused or released. In that case the
5270 // FastTrack state hasn't had time to update.
5271 // TODO Remove the ALOGW when this theory is confirmed.
5272 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005273 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5274 j, track->mState, state->mTrackMask, recentUnderruns,
5275 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005276 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005277 }
5278 tracksToRemove->add(track);
5279 // Avoids a misleading display in dumpsys
5280 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5281 }
jiabin245cdd92018-12-07 17:55:15 -08005282 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5283 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5284 didModify = true;
5285 }
Eric Laurent81784c32012-11-19 14:55:58 -08005286 continue;
5287 }
5288
5289 { // local variable scope to avoid goto warning
5290
5291 audio_track_cblk_t* cblk = track->cblk();
5292
5293 // The first time a track is added we wait
5294 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005295 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005296
5297 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005298 // use the trackId as the AudioMixer name.
5299 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005300 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005301 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005302 track->mChannelMask,
5303 track->mFormat,
5304 track->mSessionId);
5305 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005306 ALOGW("%s(): AudioMixer cannot create track(%d)"
5307 " mask %#x, format %#x, sessionId %d",
5308 __func__, trackId,
5309 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005310 tracksToRemove->add(track);
5311 track->invalidate(); // consider it dead.
5312 continue;
5313 }
5314 }
5315
Eric Laurent81784c32012-11-19 14:55:58 -08005316 // make sure that we have enough frames to mix one full buffer.
5317 // enforce this condition only once to enable draining the buffer in case the client
5318 // app does not call stop() and relies on underrun to stop:
5319 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5320 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005321 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005322 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005323 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005324
5325 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005326 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005327 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5328 // add frames already consumed but not yet released by the resampler
5329 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005330 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005331
Eric Laurent81784c32012-11-19 14:55:58 -08005332 uint32_t minFrames = 1;
5333 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5334 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005335 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005336 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005337
5338 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005339 if (ATRACE_ENABLED()) {
5340 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005341 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005342 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005343 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005344 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005345 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005346 !track->isPaused() && !track->isTerminated())
5347 {
Andy Hungc0691382018-09-12 18:01:57 -07005348 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005349
5350 mixedTracks++;
5351
Andy Hung69aed5f2014-02-25 17:24:40 -08005352 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5353 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005354 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005355 if (track->mainBuffer() != mSinkBuffer &&
5356 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005357 if (mEffectBufferEnabled) {
5358 mEffectBufferValid = true; // Later can set directly.
5359 }
Eric Laurent81784c32012-11-19 14:55:58 -08005360 chain = getEffectChain_l(track->sessionId());
5361 // Delegate volume control to effect in track effect chain if needed
5362 if (chain != 0) {
5363 tracksWithEffect++;
5364 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005365 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005366 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005367 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005368 }
5369 }
5370
5371
5372 int param = AudioMixer::VOLUME;
5373 if (track->mFillingUpStatus == Track::FS_FILLED) {
5374 // no ramp for the first volume setting
5375 track->mFillingUpStatus = Track::FS_ACTIVE;
5376 if (track->mState == TrackBase::RESUMING) {
5377 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005378 // If a new track is paused immediately after start, do not ramp on resume.
5379 if (cblk->mServer != 0) {
5380 param = AudioMixer::RAMP_VOLUME;
5381 }
Eric Laurent81784c32012-11-19 14:55:58 -08005382 }
Andy Hungc0691382018-09-12 18:01:57 -07005383 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005384 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005385 // FIXME should not make a decision based on mServer
5386 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005387 // If the track is stopped before the first frame was mixed,
5388 // do not apply ramp
5389 param = AudioMixer::RAMP_VOLUME;
5390 }
5391
5392 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005393 uint32_t vl, vr; // in U8.24 integer format
5394 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005395 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005396 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005397 // Always fetch volumeshaper volume to ensure state is updated.
5398 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5399 const float vh = track->getVolumeHandler()->getVolume(
5400 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005401
Eric Laurenteab90452019-06-24 15:17:46 -07005402 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5403 v = 0;
5404 }
5405
5406 handleVoipVolume_l(&v);
5407
5408 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005409 vl = vr = 0;
5410 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005411 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005412 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005413 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005414 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5415 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005416 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005417 if (vlf > GAIN_FLOAT_UNITY) {
5418 ALOGV("Track left volume out of range: %.3g", vlf);
5419 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005420 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005421 if (vrf > GAIN_FLOAT_UNITY) {
5422 ALOGV("Track right volume out of range: %.3g", vrf);
5423 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005424 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005425 // now apply the master volume and stream type volume and shaper volume
5426 vlf *= v * vh;
5427 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005428 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005429 // then derive vl and vr as U8.24 versions for the effect chain
5430 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5431 vl = (uint32_t) (scaleto8_24 * vlf);
5432 vr = (uint32_t) (scaleto8_24 * vrf);
5433 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005434 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005435 // send level comes from shared memory and so may be corrupt
5436 if (sendLevel > MAX_GAIN_INT) {
5437 ALOGV("Track send level out of range: %04X", sendLevel);
5438 sendLevel = MAX_GAIN_INT;
5439 }
Andy Hung6be49402014-05-30 10:42:03 -07005440 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5441 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005442 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005443
Kevin Rocard12381092018-04-11 09:19:59 -07005444 track->setFinalVolume((vrf + vlf) / 2.f);
5445
Eric Laurent81784c32012-11-19 14:55:58 -08005446 // Delegate volume control to effect in track effect chain if needed
5447 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5448 // Do not ramp volume if volume is controlled by effect
5449 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005450 // Update remaining floating point volume levels
5451 vlf = (float)vl / (1 << 24);
5452 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005453 track->mHasVolumeController = true;
5454 } else {
5455 // force no volume ramp when volume controller was just disabled or removed
5456 // from effect chain to avoid volume spike
5457 if (track->mHasVolumeController) {
5458 param = AudioMixer::VOLUME;
5459 }
5460 track->mHasVolumeController = false;
5461 }
5462
Eric Laurent81784c32012-11-19 14:55:58 -08005463 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005464 mAudioMixer->setBufferProvider(trackId, track);
5465 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005466
Andy Hungc0691382018-09-12 18:01:57 -07005467 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5468 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5469 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005470 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005471 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005472 AudioMixer::TRACK,
5473 AudioMixer::FORMAT, (void *)track->format());
5474 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005475 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005476 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005477 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005478
5479 if (mType == SPATIALIZER && !track->canBeSpatialized()) {
5480 mAudioMixer->setParameter(
5481 trackId,
5482 AudioMixer::TRACK,
5483 AudioMixer::MIXER_CHANNEL_MASK,
5484 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5485 } else {
5486 mAudioMixer->setParameter(
5487 trackId,
5488 AudioMixer::TRACK,
5489 AudioMixer::MIXER_CHANNEL_MASK,
5490 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5491 }
5492
Glenn Kastene3aa6592012-12-04 12:22:46 -08005493 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005494 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005495 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005496 if (reqSampleRate == 0) {
5497 reqSampleRate = mSampleRate;
5498 } else if (reqSampleRate > maxSampleRate) {
5499 reqSampleRate = maxSampleRate;
5500 }
Eric Laurent81784c32012-11-19 14:55:58 -08005501 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005502 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005503 AudioMixer::RESAMPLE,
5504 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005505 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005506
Andy Hung333ab962019-05-28 20:23:35 -07005507 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005508 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005509 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005510 AudioMixer::TIMESTRETCH,
5511 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005512 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005513
Andy Hung69aed5f2014-02-25 17:24:40 -08005514 /*
5515 * Select the appropriate output buffer for the track.
5516 *
Andy Hung98ef9782014-03-04 14:46:50 -08005517 * Tracks with effects go into their own effects chain buffer
5518 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005519 *
5520 * Other tracks can use mMixerBuffer for higher precision
5521 * channel accumulation. If this buffer is enabled
5522 * (mMixerBufferEnabled true), then selected tracks will accumulate
5523 * into it.
5524 *
5525 */
5526 if (mMixerBufferEnabled
5527 && (track->mainBuffer() == mSinkBuffer
5528 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurent39095982021-08-24 18:29:27 +02005529 if (mType == SPATIALIZER && !track->canBeSpatialized()) {
5530 mAudioMixer->setParameter(
5531 trackId,
5532 AudioMixer::TRACK,
5533 AudioMixer::MIXER_FORMAT, (void *)mFormat);
5534 mAudioMixer->setParameter(
5535 trackId,
5536 AudioMixer::TRACK,
5537 AudioMixer::MAIN_BUFFER, (void *)mSinkBuffer);
5538 } else {
5539 mAudioMixer->setParameter(
5540 trackId,
5541 AudioMixer::TRACK,
5542 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5543 mAudioMixer->setParameter(
5544 trackId,
5545 AudioMixer::TRACK,
5546 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5547 // TODO: override track->mainBuffer()?
5548 mMixerBufferValid = true;
5549 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005550 } else {
5551 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005552 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005553 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005554 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005555 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005556 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005557 AudioMixer::TRACK,
5558 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5559 }
Eric Laurent81784c32012-11-19 14:55:58 -08005560 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005561 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005562 AudioMixer::TRACK,
5563 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005564 mAudioMixer->setParameter(
5565 trackId,
5566 AudioMixer::TRACK,
5567 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005568 mAudioMixer->setParameter(
5569 trackId,
5570 AudioMixer::TRACK,
5571 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005572 mAudioMixer->setParameter(
5573 trackId,
5574 AudioMixer::TRACK,
5575 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005576
5577 // reset retry count
5578 track->mRetryCount = kMaxTrackRetries;
5579
5580 // If one track is ready, set the mixer ready if:
5581 // - the mixer was not ready during previous round OR
5582 // - no other track is not ready
5583 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5584 mixerStatus != MIXER_TRACKS_ENABLED) {
5585 mixerStatus = MIXER_TRACKS_READY;
5586 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005587
5588 // Enable the next few lines to instrument a test for underrun log handling.
5589 // TODO: Remove when we have a better way of testing the underrun log.
5590#if 0
5591 static int i;
5592 if ((++i & 0xf) == 0) {
5593 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5594 }
5595#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005596 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005597 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005598 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005599 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5600 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005601 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005602 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005603 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005604
Eric Laurent81784c32012-11-19 14:55:58 -08005605 // clear effect chain input buffer if an active track underruns to avoid sending
5606 // previous audio buffer again to effects
5607 chain = getEffectChain_l(track->sessionId());
5608 if (chain != 0) {
5609 chain->clearInputBuffer();
5610 }
5611
Andy Hungc0691382018-09-12 18:01:57 -07005612 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005613 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5614 track->isStopped() || track->isPaused()) {
5615 // We have consumed all the buffers of this track.
5616 // Remove it from the list of active tracks.
5617 // TODO: use actual buffer filling status instead of latency when available from
5618 // audio HAL
5619 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005620 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005621 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5622 if (track->isStopped()) {
5623 track->reset();
5624 }
5625 tracksToRemove->add(track);
5626 }
5627 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005628 // No buffers for this track. Give it a few chances to
5629 // fill a buffer, then remove it from active list.
5630 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005631 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5632 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005633 tracksToRemove->add(track);
5634 // indicate to client process that the track was disabled because of underrun;
5635 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005636 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005637 // If one track is not ready, mark the mixer also not ready if:
5638 // - the mixer was ready during previous round OR
5639 // - no other track is ready
5640 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5641 mixerStatus != MIXER_TRACKS_READY) {
5642 mixerStatus = MIXER_TRACKS_ENABLED;
5643 }
5644 }
Andy Hungc0691382018-09-12 18:01:57 -07005645 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005646 }
5647
5648 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005649
5650 }
5651
jiabin245cdd92018-12-07 17:55:15 -08005652 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5653 // When there is no fast track playing haptic and FastMixer exists,
5654 // enabling the first FastTrack, which provides mixed data from normal
5655 // tracks, to play haptic data.
5656 FastTrack *fastTrack = &state->mFastTracks[0];
5657 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5658 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5659 didModify = true;
5660 }
5661 }
5662
Eric Laurent81784c32012-11-19 14:55:58 -08005663 // Push the new FastMixer state if necessary
5664 bool pauseAudioWatchdog = false;
5665 if (didModify) {
5666 state->mFastTracksGen++;
5667 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5668 if (kUseFastMixer == FastMixer_Dynamic &&
5669 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5670 state->mCommand = FastMixerState::COLD_IDLE;
5671 state->mColdFutexAddr = &mFastMixerFutex;
5672 state->mColdGen++;
5673 mFastMixerFutex = 0;
5674 if (kUseFastMixer == FastMixer_Dynamic) {
5675 mNormalSink = mOutputSink;
5676 }
5677 // If we go into cold idle, need to wait for acknowledgement
5678 // so that fast mixer stops doing I/O.
5679 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5680 pauseAudioWatchdog = true;
5681 }
Eric Laurent81784c32012-11-19 14:55:58 -08005682 }
5683 if (sq != NULL) {
5684 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005685 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5686 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5687 // when bringing the output sink into standby.)
5688 //
5689 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5690 //
5691 // This occurs with BT suspend when we idle the FastMixer with
5692 // active tracks, which may be added or removed.
5693 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005694 }
5695#ifdef AUDIO_WATCHDOG
5696 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5697 mAudioWatchdog->pause();
5698 }
5699#endif
5700
5701 // Now perform the deferred reset on fast tracks that have stopped
5702 while (resetMask != 0) {
5703 size_t i = __builtin_ctz(resetMask);
5704 ALOG_ASSERT(i < count);
5705 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005706 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005707 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5708 track->reset();
5709 }
5710
Andy Hung80d03d22018-04-10 10:32:11 -07005711 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5712 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5713 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5714 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5715 // See also the implementation of destroyTrack_l().
5716 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005717 const int trackId = track->id();
5718 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5719 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005720 }
5721 }
5722
Eric Laurent81784c32012-11-19 14:55:58 -08005723 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005724 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005725
Eric Laurentb3f315a2021-07-13 15:09:05 +02005726 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5727 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005728 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005729 }
5730
5731 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005732 // as long as there are effects we should clear the effects buffer, to avoid
5733 // passing a non-clean buffer to the effect chain
5734 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005735 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005736 // sink or mix buffer must be cleared if all tracks are connected to an
5737 // effect chain as in this case the mixer will not write to the sink or mix buffer
5738 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005739 // always clear sink buffer for spatializer output as the output of the spatializer
5740 // effect will be accumulated into it
5741 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5742 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005743 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005744 if (mMixerBufferValid) {
5745 memset(mMixerBuffer, 0, mMixerBufferSize);
5746 // TODO: In testing, mSinkBuffer below need not be cleared because
5747 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5748 // after mixing.
5749 //
5750 // To enforce this guarantee:
5751 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5752 // (mixedTracks == 0 && fastTracks > 0))
5753 // must imply MIXER_TRACKS_READY.
5754 // Later, we may clear buffers regardless, and skip much of this logic.
5755 }
Andy Hung98ef9782014-03-04 14:46:50 -08005756 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005757 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005758 }
5759
5760 // if any fast tracks, then status is ready
5761 mMixerStatusIgnoringFastTracks = mixerStatus;
5762 if (fastTracks > 0) {
5763 mixerStatus = MIXER_TRACKS_READY;
5764 }
5765 return mixerStatus;
5766}
5767
Eric Laurentad7dd962016-09-22 12:38:37 -07005768// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005769uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005770{
5771 uint32_t trackCount = 0;
5772 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005773 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005774 trackCount++;
5775 }
5776 }
5777 return trackCount;
5778}
5779
Andy Hung1bc088a2018-02-09 15:57:31 -08005780// isTrackAllowed_l() must be called with ThreadBase::mLock held
5781bool AudioFlinger::MixerThread::isTrackAllowed_l(
5782 audio_channel_mask_t channelMask, audio_format_t format,
5783 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005784{
Andy Hung1bc088a2018-02-09 15:57:31 -08005785 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5786 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005787 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005788 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005789 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005790 ALOGW("%s: invalid format: %#x", __func__, format);
5791 return false;
5792 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005793 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005794 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5795 return false;
5796 }
5797 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005798}
5799
Eric Laurent10351942014-05-08 18:49:52 -07005800// checkForNewParameter_l() must be called with ThreadBase::mLock held
5801bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5802 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005803{
Eric Laurent81784c32012-11-19 14:55:58 -08005804 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005805 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005806
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005807 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005808
Eric Laurent10351942014-05-08 18:49:52 -07005809 AudioParameter param = AudioParameter(keyValuePair);
5810 int value;
5811 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5812 reconfig = true;
5813 }
5814 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005815 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005816 status = BAD_VALUE;
5817 } else {
5818 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005819 reconfig = true;
5820 }
Eric Laurent10351942014-05-08 18:49:52 -07005821 }
5822 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005823 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005824 status = BAD_VALUE;
5825 } else {
5826 // no need to save value, since it's constant
5827 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005828 }
Eric Laurent10351942014-05-08 18:49:52 -07005829 }
5830 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5831 // do not accept frame count changes if tracks are open as the track buffer
5832 // size depends on frame count and correct behavior would not be guaranteed
5833 // if frame count is changed after track creation
5834 if (!mTracks.isEmpty()) {
5835 status = INVALID_OPERATION;
5836 } else {
5837 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005838 }
Eric Laurent10351942014-05-08 18:49:52 -07005839 }
5840 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005841 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005842 }
Eric Laurent81784c32012-11-19 14:55:58 -08005843
Eric Laurent10351942014-05-08 18:49:52 -07005844 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005845 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005846 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005847 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005848 if (!mStandby) {
5849 mThreadMetrics.logEndInterval();
5850 mStandby = true;
5851 }
Eric Laurent10351942014-05-08 18:49:52 -07005852 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005853 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005854 }
Eric Laurent10351942014-05-08 18:49:52 -07005855 if (status == NO_ERROR && reconfig) {
5856 readOutputParameters_l();
5857 delete mAudioMixer;
5858 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005859 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005860 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005861 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005862 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005863 track->mChannelMask,
5864 track->mFormat,
5865 track->mSessionId);
5866 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005867 "%s(): AudioMixer cannot create track(%d)"
5868 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005869 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005870 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005871 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005872 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005873 }
Eric Laurent81784c32012-11-19 14:55:58 -08005874 }
5875
Dean Wheatley68918102021-03-19 22:09:19 +11005876 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005877}
5878
5879
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005880void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005881{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005882 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005883 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005884 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005885 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005886 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5887 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5888 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005889 if (hasFastMixer()) {
5890 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5891
5892 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5893 // while we are dumping it. It may be inconsistent, but it won't mutate!
5894 // This is a large object so we place it on the heap.
5895 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005896 const std::unique_ptr<FastMixerDumpState> copy =
5897 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005898 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005899
5900#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005901 // Similar for state queue
5902 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5903 observerCopy.dump(fd);
5904 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5905 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005906#endif
5907
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005908#ifdef AUDIO_WATCHDOG
5909 if (mAudioWatchdog != 0) {
5910 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5911 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5912 wdCopy.dump(fd);
5913 }
5914#endif
5915
5916 } else {
5917 dprintf(fd, " No FastMixer\n");
5918 }
Eric Laurent81784c32012-11-19 14:55:58 -08005919}
5920
5921uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5922{
5923 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5924}
5925
5926uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5927{
5928 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5929}
5930
5931void AudioFlinger::MixerThread::cacheParameters_l()
5932{
5933 PlaybackThread::cacheParameters_l();
5934
5935 // FIXME: Relaxed timing because of a certain device that can't meet latency
5936 // Should be reduced to 2x after the vendor fixes the driver issue
5937 // increase threshold again due to low power audio mode. The way this warning
5938 // threshold is calculated and its usefulness should be reconsidered anyway.
5939 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5940}
5941
5942// ----------------------------------------------------------------------------
5943
5944AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005945 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5946 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005947{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005948 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005949}
5950
Eric Laurent81784c32012-11-19 14:55:58 -08005951AudioFlinger::DirectOutputThread::~DirectOutputThread()
5952{
5953}
5954
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005955void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005956{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005957 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005958 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5959 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5960}
5961
5962void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5963{
5964 Mutex::Autolock _l(mLock);
5965 if (mMasterBalance != balance) {
5966 mMasterBalance.store(balance);
5967 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5968 broadcast_l();
5969 }
5970}
5971
Eric Laurent5850c4c2016-11-10 13:04:31 -08005972void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005973{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005974 float left, right;
5975
Andy Hung333ab962019-05-28 20:23:35 -07005976 // Ensure volumeshaper state always advances even when muted.
5977 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5978 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5979 proxy->framesReleased());
5980 mVolumeShaperActive = shaperActive;
5981
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005982 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005983 left = right = 0;
5984 } else {
5985 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005986 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005987
Glenn Kastenc56f3422014-03-21 17:53:17 -07005988 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5989 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5990 if (left > GAIN_FLOAT_UNITY) {
5991 left = GAIN_FLOAT_UNITY;
5992 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005993 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005994 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5995 if (right > GAIN_FLOAT_UNITY) {
5996 right = GAIN_FLOAT_UNITY;
5997 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005998 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005999 }
6000
6001 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006002 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006003 if (left != mLeftVolFloat || right != mRightVolFloat) {
6004 mLeftVolFloat = left;
6005 mRightVolFloat = right;
6006
Eric Laurentbfb1b832013-01-07 09:53:42 -08006007 // Delegate volume control to effect in track effect chain if needed
6008 // only one effect chain can be present on DirectOutputThread, so if
6009 // there is one, the track is connected to it
6010 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006011 // if effect chain exists, volume is handled by it.
6012 // Convert volumes from float to 8.24
6013 uint32_t vl = (uint32_t)(left * (1 << 24));
6014 uint32_t vr = (uint32_t)(right * (1 << 24));
6015 // Direct/Offload effect chains set output volume in setVolume_l().
6016 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6017 } else {
6018 // otherwise we directly set the volume.
6019 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006020 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006021 }
6022 }
6023}
6024
Phil Burk43b4dcc2015-06-09 16:53:44 -07006025void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6026{
6027 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006028 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006029
Eric Laurent0f0631e2015-07-06 18:01:25 -07006030 if (previousTrack != 0 && latestTrack != 0) {
6031 if (mType == DIRECT) {
6032 if (previousTrack.get() != latestTrack.get()) {
6033 mFlushPending = true;
6034 }
6035 } else /* mType == OFFLOAD */ {
6036 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6037 mFlushPending = true;
6038 }
6039 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006040 } else if (previousTrack == 0) {
6041 // there could be an old track added back during track transition for direct
6042 // output, so always issues flush to flush data of the previous track if it
6043 // was already destroyed with HAL paused, then flush can resume the playback
6044 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006045 }
6046 PlaybackThread::onAddNewTrack_l();
6047}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006048
Eric Laurent81784c32012-11-19 14:55:58 -08006049AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6050 Vector< sp<Track> > *tracksToRemove
6051)
6052{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006053 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006054 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006055 bool doHwPause = false;
6056 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006057
6058 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006059 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006060 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006061 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006062 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006063 continue;
6064 }
6065
Eric Laurent5850c4c2016-11-10 13:04:31 -08006066 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006067#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006068 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006069#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006070 // Only consider last track started for volume and mixer state control.
6071 // In theory an older track could underrun and restart after the new one starts
6072 // but as we only care about the transition phase between two tracks on a
6073 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006074 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006075 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006076
Kuowei Li23666472021-01-20 10:23:25 +08006077 if (track->isPausePending()) {
6078 track->pauseAck();
6079 // It is possible a track might have been flushed or stopped.
6080 // Other operations such as flush pending might occur on the next prepare.
6081 if (track->isPausing()) {
6082 track->setPaused();
6083 }
6084 // Always perform pause, as an immediate flush will change
6085 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006086 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006087 doHwPause = true;
6088 mHwPaused = true;
6089 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006090 } else if (track->isFlushPending()) {
6091 track->flushAck();
6092 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006093 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006094 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006095 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006096 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006097 if (last) {
6098 mLeftVolFloat = mRightVolFloat = -1.0;
6099 if (mHwPaused) {
6100 doHwResume = true;
6101 mHwPaused = false;
6102 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006103 }
6104 }
6105
Eric Laurent81784c32012-11-19 14:55:58 -08006106 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006107 // for all its buffers to be filled before processing it.
6108 // Allow draining the buffer in case the client
6109 // app does not call stop() and relies on underrun to stop:
6110 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006111 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6112 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6113 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006114 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006115
6116 // target retry count that we will use is based on the time we wait for retries.
6117 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6118 // the retry threshold is when we accept any size for PCM data. This is slightly
6119 // smaller than the retry count so we can push small bits of data without a glitch.
6120 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006121 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006122 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006123 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006124 minFrames = mNormalFrameCount;
6125 } else {
6126 minFrames = 1;
6127 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006128
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006129 const size_t framesReady = track->framesReady();
6130 const int trackId = track->id();
6131 if (ATRACE_ENABLED()) {
6132 std::string traceName("nRdy");
6133 traceName += std::to_string(trackId);
6134 ATRACE_INT(traceName.c_str(), framesReady);
6135 }
6136 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006137 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006138 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006139 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006140
6141 if (track->mFillingUpStatus == Track::FS_FILLED) {
6142 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006143 if (last) {
6144 // make sure processVolume_l() will apply new volume even if 0
6145 mLeftVolFloat = mRightVolFloat = -1.0;
6146 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006147 if (!mHwSupportsPause) {
6148 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006149 }
6150 }
6151
6152 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006153 processVolume_l(track, last);
6154 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006155 sp<Track> previousTrack = mPreviousTrack.promote();
6156 if (previousTrack != 0) {
6157 if (track != previousTrack.get()) {
6158 // Flush any data still being written from last track
6159 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006160 // Invalidate previous track to force a seek when resuming.
6161 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006162 }
6163 }
6164 mPreviousTrack = track;
6165
Eric Laurentd595b7c2013-04-03 17:27:56 -07006166 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006167 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006168 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006169 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006170 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006171 doHwResume = true;
6172 mHwPaused = false;
6173 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006174 }
Eric Laurent81784c32012-11-19 14:55:58 -08006175 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006176 // clear effect chain input buffer if the last active track started underruns
6177 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006178 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006179 mEffectChains[0]->clearInputBuffer();
6180 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006181 if (track->isStopping_1()) {
6182 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006183 if (last && mHwPaused) {
6184 doHwResume = true;
6185 mHwPaused = false;
6186 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006187 }
6188 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6189 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006190 // We have consumed all the buffers of this track.
6191 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006192 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006193 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006194 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006195 if (track->isStopping_2()) {
6196 track->mState = TrackBase::STOPPED;
6197 }
Eric Laurent81784c32012-11-19 14:55:58 -08006198 if (track->isStopped()) {
6199 track->reset();
6200 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006201 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006202 }
6203 } else {
6204 // No buffers for this track. Give it a few chances to
6205 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006206 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006207 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006208 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006209 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006210 // indicate to client process that the track was disabled because of underrun;
6211 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006212 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006213 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6214 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006215 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6216 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006217 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006218 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006219 doHwPause = true;
6220 mHwPaused = true;
6221 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006222 } else if (last) {
6223 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006224 }
6225 }
6226 }
6227 }
6228
Eric Laurentd1f69b02014-12-15 14:33:13 -08006229 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006230 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006231 for (size_t i = 0; i < mTracks.size(); i++) {
6232 if (mTracks[i]->isFlushPending()) {
6233 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006234 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006235 }
6236 }
6237 }
6238
6239 // make sure the pause/flush/resume sequence is executed in the right order.
6240 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6241 // before flush and then resume HW. This can happen in case of pause/flush/resume
6242 // if resume is received before pause is executed.
6243 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006244 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006245 status_t result = mOutput->stream->pause();
6246 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006247 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006248 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006249 flushHw_l();
6250 }
6251 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006252 status_t result = mOutput->stream->resume();
6253 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006254 }
Eric Laurent81784c32012-11-19 14:55:58 -08006255 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006256 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006257
6258 return mixerStatus;
6259}
6260
6261void AudioFlinger::DirectOutputThread::threadLoop_mix()
6262{
Eric Laurent81784c32012-11-19 14:55:58 -08006263 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006264 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006265 // output audio to hardware
6266 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006267 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006268 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006269 status_t status = mActiveTrack->getNextBuffer(&buffer);
6270 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006271 // no need to pad with 0 for compressed audio
6272 if (audio_has_proportional_frames(mFormat)) {
6273 memset(curBuf, 0, frameCount * mFrameSize);
6274 }
Eric Laurent81784c32012-11-19 14:55:58 -08006275 break;
6276 }
6277 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6278 frameCount -= buffer.frameCount;
6279 curBuf += buffer.frameCount * mFrameSize;
6280 mActiveTrack->releaseBuffer(&buffer);
6281 }
Andy Hung2098f272014-02-27 14:00:06 -08006282 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006283 mSleepTimeUs = 0;
6284 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006285 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006286}
6287
6288void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6289{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006290 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006291 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006292 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006293 return;
6294 }
Andy Hung85ba3332021-04-27 17:40:26 -07006295 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6296 mSleepTimeUs = mActiveSleepTimeUs;
6297 } else {
6298 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006299 }
Andy Hung85ba3332021-04-27 17:40:26 -07006300 // Note: In S or later, we do not write zeroes for
6301 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006302}
6303
Eric Laurentd1f69b02014-12-15 14:33:13 -08006304void AudioFlinger::DirectOutputThread::threadLoop_exit()
6305{
6306 {
6307 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006308 for (size_t i = 0; i < mTracks.size(); i++) {
6309 if (mTracks[i]->isFlushPending()) {
6310 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006311 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006312 }
6313 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006314 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006315 flushHw_l();
6316 }
6317 }
6318 PlaybackThread::threadLoop_exit();
6319}
6320
6321// must be called with thread mutex locked
6322bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6323{
6324 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006325 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006326
6327 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6328 // after a timeout and we will enter standby then.
6329 if (mTracks.size() > 0) {
6330 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006331 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6332 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006333 }
6334
Eric Laurent5cff4032015-05-26 13:49:58 -07006335 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006336}
6337
Eric Laurent10351942014-05-08 18:49:52 -07006338// checkForNewParameter_l() must be called with ThreadBase::mLock held
6339bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6340 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006341{
6342 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006343 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006344
Eric Laurent10351942014-05-08 18:49:52 -07006345 AudioParameter param = AudioParameter(keyValuePair);
6346 int value;
6347 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006348 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006349 }
Eric Laurent10351942014-05-08 18:49:52 -07006350 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6351 // do not accept frame count changes if tracks are open as the track buffer
6352 // size depends on frame count and correct behavior would not be garantied
6353 // if frame count is changed after track creation
6354 if (!mTracks.isEmpty()) {
6355 status = INVALID_OPERATION;
6356 } else {
6357 reconfig = true;
6358 }
6359 }
6360 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006361 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006362 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006363 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006364 if (!mStandby) {
6365 mThreadMetrics.logEndInterval();
6366 mStandby = true;
6367 }
Eric Laurent10351942014-05-08 18:49:52 -07006368 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006369 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006370 }
6371 if (status == NO_ERROR && reconfig) {
6372 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006373 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006374 }
6375 }
6376
Dean Wheatley68918102021-03-19 22:09:19 +11006377 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006378}
6379
6380uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6381{
6382 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006383 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006384 time = PlaybackThread::activeSleepTimeUs();
6385 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006386 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006387 }
6388 return time;
6389}
6390
6391uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6392{
6393 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006394 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006395 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6396 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006397 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006398 }
6399 return time;
6400}
6401
6402uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6403{
6404 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006405 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006406 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6407 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006408 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006409 }
6410 return time;
6411}
6412
6413void AudioFlinger::DirectOutputThread::cacheParameters_l()
6414{
6415 PlaybackThread::cacheParameters_l();
6416
6417 // use shorter standby delay as on normal output to release
6418 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006419 // no delay on outputs with HW A/V sync
6420 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006421 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006422 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006423 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006424 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006425 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006426 }
Eric Laurent81784c32012-11-19 14:55:58 -08006427}
6428
Eric Laurente659ef42014-09-29 13:06:46 -07006429void AudioFlinger::DirectOutputThread::flushHw_l()
6430{
Phil Burk062e67a2015-02-11 13:40:50 -08006431 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006432 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006433 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006434 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006435 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006436}
6437
Andy Hung10cbff12017-02-21 17:30:14 -08006438int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6439 // If a VolumeShaper is active, we must wake up periodically to update volume.
6440 const int64_t NS_PER_MS = 1000000;
6441 return mVolumeShaperActive ?
6442 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6443}
6444
Eric Laurent81784c32012-11-19 14:55:58 -08006445// ----------------------------------------------------------------------------
6446
Eric Laurentbfb1b832013-01-07 09:53:42 -08006447AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006448 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006449 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006450 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006451 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006452 mDrainSequence(0),
6453 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006454{
6455}
6456
6457AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6458{
6459}
6460
6461void AudioFlinger::AsyncCallbackThread::onFirstRef()
6462{
6463 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6464}
6465
6466bool AudioFlinger::AsyncCallbackThread::threadLoop()
6467{
6468 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006469 uint32_t writeAckSequence;
6470 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006471 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006472
6473 {
6474 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006475 while (!((mWriteAckSequence & 1) ||
6476 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006477 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006478 exitPending())) {
6479 mWaitWorkCV.wait(mLock);
6480 }
6481
Eric Laurentbfb1b832013-01-07 09:53:42 -08006482 if (exitPending()) {
6483 break;
6484 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006485 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6486 mWriteAckSequence, mDrainSequence);
6487 writeAckSequence = mWriteAckSequence;
6488 mWriteAckSequence &= ~1;
6489 drainSequence = mDrainSequence;
6490 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006491 asyncError = mAsyncError;
6492 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006493 }
6494 {
Eric Laurent4de95592013-09-26 15:28:21 -07006495 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6496 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006497 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006498 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006499 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006500 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006501 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006502 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006503 if (asyncError) {
6504 playbackThread->onAsyncError();
6505 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006506 }
6507 }
6508 }
6509 return false;
6510}
6511
6512void AudioFlinger::AsyncCallbackThread::exit()
6513{
6514 ALOGV("AsyncCallbackThread::exit");
6515 Mutex::Autolock _l(mLock);
6516 requestExit();
6517 mWaitWorkCV.broadcast();
6518}
6519
Eric Laurent3b4529e2013-09-05 18:09:19 -07006520void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006521{
6522 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006523 // bit 0 is cleared
6524 mWriteAckSequence = sequence << 1;
6525}
6526
6527void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6528{
6529 Mutex::Autolock _l(mLock);
6530 // ignore unexpected callbacks
6531 if (mWriteAckSequence & 2) {
6532 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006533 mWaitWorkCV.signal();
6534 }
6535}
6536
Eric Laurent3b4529e2013-09-05 18:09:19 -07006537void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006538{
6539 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006540 // bit 0 is cleared
6541 mDrainSequence = sequence << 1;
6542}
6543
6544void AudioFlinger::AsyncCallbackThread::resetDraining()
6545{
6546 Mutex::Autolock _l(mLock);
6547 // ignore unexpected callbacks
6548 if (mDrainSequence & 2) {
6549 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006550 mWaitWorkCV.signal();
6551 }
6552}
6553
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006554void AudioFlinger::AsyncCallbackThread::setAsyncError()
6555{
6556 Mutex::Autolock _l(mLock);
6557 mAsyncError = true;
6558 mWaitWorkCV.signal();
6559}
6560
Eric Laurentbfb1b832013-01-07 09:53:42 -08006561
6562// ----------------------------------------------------------------------------
6563AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006564 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6565 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006566 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6567 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006568{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006569 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006570 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006571 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006572}
6573
Eric Laurentbfb1b832013-01-07 09:53:42 -08006574void AudioFlinger::OffloadThread::threadLoop_exit()
6575{
6576 if (mFlushPending || mHwPaused) {
6577 // If a flush is pending or track was paused, just discard buffered data
6578 flushHw_l();
6579 } else {
6580 mMixerStatus = MIXER_DRAIN_ALL;
6581 threadLoop_drain();
6582 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006583 if (mUseAsyncWrite) {
6584 ALOG_ASSERT(mCallbackThread != 0);
6585 mCallbackThread->exit();
6586 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006587 PlaybackThread::threadLoop_exit();
6588}
6589
6590AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6591 Vector< sp<Track> > *tracksToRemove
6592)
6593{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006594 size_t count = mActiveTracks.size();
6595
6596 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006597 bool doHwPause = false;
6598 bool doHwResume = false;
6599
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006600 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006601
Eric Laurentbfb1b832013-01-07 09:53:42 -08006602 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006603 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006604 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006605#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006606 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006607#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006608 // Only consider last track started for volume and mixer state control.
6609 // In theory an older track could underrun and restart after the new one starts
6610 // but as we only care about the transition phase between two tracks on a
6611 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006612 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006613 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006614
Haynes Mathew George7844f672014-01-15 12:32:55 -08006615 if (track->isInvalid()) {
6616 ALOGW("An invalidated track shouldn't be in active list");
6617 tracksToRemove->add(track);
6618 continue;
6619 }
6620
6621 if (track->mState == TrackBase::IDLE) {
6622 ALOGW("An idle track shouldn't be in active list");
6623 continue;
6624 }
6625
Kuowei Li23666472021-01-20 10:23:25 +08006626 if (track->isPausePending()) {
6627 track->pauseAck();
6628 // It is possible a track might have been flushed or stopped.
6629 // Other operations such as flush pending might occur on the next prepare.
6630 if (track->isPausing()) {
6631 track->setPaused();
6632 }
6633 // Always perform pause if last, as an immediate flush will change
6634 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006635 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006636 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006637 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006638 mHwPaused = true;
6639 }
6640 // If we were part way through writing the mixbuffer to
6641 // the HAL we must save this until we resume
6642 // BUG - this will be wrong if a different track is made active,
6643 // in that case we want to discard the pending data in the
6644 // mixbuffer and tell the client to present it again when the
6645 // track is resumed
6646 mPausedWriteLength = mCurrentWriteLength;
6647 mPausedBytesRemaining = mBytesRemaining;
6648 mBytesRemaining = 0; // stop writing
6649 }
6650 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006651 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006652 if (track->isStopping_1()) {
6653 track->mRetryCount = kMaxTrackStopRetriesOffload;
6654 } else {
6655 track->mRetryCount = kMaxTrackRetriesOffload;
6656 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006657 track->flushAck();
6658 if (last) {
6659 mFlushPending = true;
6660 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006661 } else if (track->isResumePending()){
6662 track->resumeAck();
6663 if (last) {
6664 if (mPausedBytesRemaining) {
6665 // Need to continue write that was interrupted
6666 mCurrentWriteLength = mPausedWriteLength;
6667 mBytesRemaining = mPausedBytesRemaining;
6668 mPausedBytesRemaining = 0;
6669 }
6670 if (mHwPaused) {
6671 doHwResume = true;
6672 mHwPaused = false;
6673 // threadLoop_mix() will handle the case that we need to
6674 // resume an interrupted write
6675 }
6676 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006677 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006678
Eric Laurent3df841a2016-07-15 15:15:40 -07006679 mLeftVolFloat = mRightVolFloat = -1.0;
6680
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006681 // Do not handle new data in this iteration even if track->framesReady()
6682 mixerStatus = MIXER_TRACKS_ENABLED;
6683 }
6684 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006685 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006686 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006687 if (track->mFillingUpStatus == Track::FS_FILLED) {
6688 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006689 if (last) {
6690 // make sure processVolume_l() will apply new volume even if 0
6691 mLeftVolFloat = mRightVolFloat = -1.0;
6692 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006693 }
6694
6695 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006696 sp<Track> previousTrack = mPreviousTrack.promote();
6697 if (previousTrack != 0) {
6698 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006699 // Flush any data still being written from last track
6700 mBytesRemaining = 0;
6701 if (mPausedBytesRemaining) {
6702 // Last track was paused so we also need to flush saved
6703 // mixbuffer state and invalidate track so that it will
6704 // re-submit that unwritten data when it is next resumed
6705 mPausedBytesRemaining = 0;
6706 // Invalidate is a bit drastic - would be more efficient
6707 // to have a flag to tell client that some of the
6708 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006709 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006710 }
6711 // flush data already sent to the DSP if changing audio session as audio
6712 // comes from a different source. Also invalidate previous track to force a
6713 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006714 if (previousTrack->sessionId() != track->sessionId()) {
6715 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006716 }
6717 }
6718 }
6719 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006720 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006721 if (track->isStopping_1()) {
6722 track->mRetryCount = kMaxTrackStopRetriesOffload;
6723 } else {
6724 track->mRetryCount = kMaxTrackRetriesOffload;
6725 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006726 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006727 mixerStatus = MIXER_TRACKS_READY;
6728 }
6729 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006730 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006731 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006732 if (--(track->mRetryCount) <= 0) {
6733 // Hardware buffer can hold a large amount of audio so we must
6734 // wait for all current track's data to drain before we say
6735 // that the track is stopped.
6736 if (mBytesRemaining == 0) {
6737 // Only start draining when all data in mixbuffer
6738 // has been written
6739 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6740 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6741 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6742 if (last && !mStandby) {
6743 // do not modify drain sequence if we are already draining. This happens
6744 // when resuming from pause after drain.
6745 if ((mDrainSequence & 1) == 0) {
6746 mSleepTimeUs = 0;
6747 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6748 mixerStatus = MIXER_DRAIN_TRACK;
6749 mDrainSequence += 2;
6750 }
6751 if (mHwPaused) {
6752 // It is possible to move from PAUSED to STOPPING_1 without
6753 // a resume so we must ensure hardware is running
6754 doHwResume = true;
6755 mHwPaused = false;
6756 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006757 }
6758 }
Eric Laurente93cc032016-05-05 10:15:10 -07006759 } else if (last) {
6760 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6761 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006762 }
6763 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006764 // Drain has completed or we are in standby, signal presentation complete
6765 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006766 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006767 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006768 track->reset();
6769 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006770 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006771 if (!mUseAsyncWrite) {
6772 // If we don't get explicit drain notification we must
6773 // register discontinuity regardless of whether this is
6774 // the previous (!last) or the upcoming (last) track
6775 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006776 mTimestampVerifier.discontinuity(
6777 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006778 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006779 }
6780 } else {
6781 // No buffers for this track. Give it a few chances to
6782 // fill a buffer, then remove it from active list.
6783 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006784 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006785 uint64_t position = 0;
6786 struct timespec unused;
6787 // The running check restarts the retry counter at least once.
6788 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6789 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6790 running = true;
6791 mOffloadUnderrunPosition = position;
6792 }
6793 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006794 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6795 (long long)position, (long long)mOffloadUnderrunPosition);
6796 }
6797 if (running) { // still running, give us more time.
6798 track->mRetryCount = kMaxTrackRetriesOffload;
6799 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006800 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6801 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006802 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006803 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006804 // it will then automatically call start() when data is available
6805 track->disable();
6806 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006807 } else if (last){
6808 mixerStatus = MIXER_TRACKS_ENABLED;
6809 }
6810 }
6811 }
6812 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006813 if (track->isReady()) { // check ready to prevent premature start.
6814 processVolume_l(track, last);
6815 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006816 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006817
Eric Laurentea0fade2013-10-04 16:23:48 -07006818 // make sure the pause/flush/resume sequence is executed in the right order.
6819 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6820 // before flush and then resume HW. This can happen in case of pause/flush/resume
6821 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006822 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006823 status_t result = mOutput->stream->pause();
6824 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006825 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006826 if (mFlushPending) {
6827 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006828 }
Eric Laurentfd477972013-10-25 18:10:40 -07006829 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006830 status_t result = mOutput->stream->resume();
6831 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006832 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006833
Eric Laurentbfb1b832013-01-07 09:53:42 -08006834 // remove all the tracks that need to be...
6835 removeTracks_l(*tracksToRemove);
6836
6837 return mixerStatus;
6838}
6839
Eric Laurentbfb1b832013-01-07 09:53:42 -08006840// must be called with thread mutex locked
6841bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6842{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006843 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6844 mWriteAckSequence, mDrainSequence);
6845 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006846 return true;
6847 }
6848 return false;
6849}
6850
Eric Laurentbfb1b832013-01-07 09:53:42 -08006851bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6852{
6853 Mutex::Autolock _l(mLock);
6854 return waitingAsyncCallback_l();
6855}
6856
6857void AudioFlinger::OffloadThread::flushHw_l()
6858{
Eric Laurente659ef42014-09-29 13:06:46 -07006859 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006860 // Flush anything still waiting in the mixbuffer
6861 mCurrentWriteLength = 0;
6862 mBytesRemaining = 0;
6863 mPausedWriteLength = 0;
6864 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006865 // reset bytes written count to reflect that DSP buffers are empty after flush.
6866 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006867 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006868
Eric Laurentbfb1b832013-01-07 09:53:42 -08006869 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006870 // discard any pending drain or write ack by incrementing sequence
6871 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6872 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006873 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006874 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6875 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006876 }
6877}
6878
Haynes Mathew George05317d22016-05-03 16:34:26 -07006879void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6880{
6881 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006882 if (PlaybackThread::invalidateTracks_l(streamType)) {
6883 mFlushPending = true;
6884 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006885}
6886
Eric Laurentbfb1b832013-01-07 09:53:42 -08006887// ----------------------------------------------------------------------------
6888
Eric Laurent81784c32012-11-19 14:55:58 -08006889AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006890 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006891 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006892 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006893 mWaitTimeMs(UINT_MAX)
6894{
6895 addOutputTrack(mainThread);
6896}
6897
6898AudioFlinger::DuplicatingThread::~DuplicatingThread()
6899{
6900 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6901 mOutputTracks[i]->destroy();
6902 }
6903}
6904
6905void AudioFlinger::DuplicatingThread::threadLoop_mix()
6906{
6907 // mix buffers...
6908 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006909 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006910 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006911 if (mMixerBufferValid) {
6912 memset(mMixerBuffer, 0, mMixerBufferSize);
6913 } else {
6914 memset(mSinkBuffer, 0, mSinkBufferSize);
6915 }
Eric Laurent81784c32012-11-19 14:55:58 -08006916 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006917 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006918 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006919 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006920 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006921}
6922
6923void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6924{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006925 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006926 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006927 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006928 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006929 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006930 }
6931 } else if (mBytesWritten != 0) {
6932 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6933 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006934 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006935 } else {
6936 // flush remaining overflow buffers in output tracks
6937 writeFrames = 0;
6938 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006939 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006940 }
6941}
6942
Eric Laurentbfb1b832013-01-07 09:53:42 -08006943ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006944{
6945 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006946 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6947
6948 // Consider the first OutputTrack for timestamp and frame counting.
6949
6950 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6951 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6952 // we always claim success.
6953 if (i == 0) {
6954 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6955 ALOGD_IF(correction != 0 && writeFrames != 0,
6956 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6957 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6958 mFramesWritten -= correction;
6959 }
6960
6961 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006962 }
Andy Hungcf10d742020-04-28 15:38:24 -07006963 if (mStandby) {
6964 mThreadMetrics.logBeginInterval();
6965 mStandby = false;
6966 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006967 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006968}
6969
6970void AudioFlinger::DuplicatingThread::threadLoop_standby()
6971{
6972 // DuplicatingThread implements standby by stopping all tracks
6973 for (size_t i = 0; i < outputTracks.size(); i++) {
6974 outputTracks[i]->stop();
6975 }
6976}
6977
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006978void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006979{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006980 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006981
6982 std::stringstream ss;
6983 const size_t numTracks = mOutputTracks.size();
6984 ss << " " << numTracks << " OutputTracks";
6985 if (numTracks > 0) {
6986 ss << ":";
6987 for (const auto &track : mOutputTracks) {
6988 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006989 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006990 if (thread.get() != nullptr) {
6991 ss << thread.get() << ", " << thread->id();
6992 } else {
6993 ss << "null";
6994 }
6995 ss << ")";
6996 }
6997 }
6998 ss << "\n";
6999 std::string result = ss.str();
7000 write(fd, result.c_str(), result.size());
7001}
7002
Eric Laurent81784c32012-11-19 14:55:58 -08007003void AudioFlinger::DuplicatingThread::saveOutputTracks()
7004{
7005 outputTracks = mOutputTracks;
7006}
7007
7008void AudioFlinger::DuplicatingThread::clearOutputTracks()
7009{
7010 outputTracks.clear();
7011}
7012
7013void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7014{
7015 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007016 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7017 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7018 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7019 const size_t frameCount =
7020 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7021 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7022 // from different OutputTracks and their associated MixerThreads (e.g. one may
7023 // nearly empty and the other may be dropping data).
7024
Svet Ganov33761132021-05-13 22:51:08 +00007025 // TODO b/182392769: use attribution source util, move to server edge
7026 AttributionSourceState attributionSource = AttributionSourceState();
7027 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007028 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007029 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007030 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007031 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007032 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007033 this,
7034 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007035 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007036 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007037 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007038 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007039 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7040 if (status != NO_ERROR) {
7041 ALOGE("addOutputTrack() initCheck failed %d", status);
7042 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007043 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007044 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7045 mOutputTracks.add(outputTrack);
7046 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7047 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007048}
7049
7050void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7051{
7052 Mutex::Autolock _l(mLock);
7053 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7054 if (mOutputTracks[i]->thread() == thread) {
7055 mOutputTracks[i]->destroy();
7056 mOutputTracks.removeAt(i);
7057 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007058 if (thread->getOutput() == mOutput) {
7059 mOutput = NULL;
7060 }
Eric Laurent81784c32012-11-19 14:55:58 -08007061 return;
7062 }
7063 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007064 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007065}
7066
7067// caller must hold mLock
7068void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7069{
7070 mWaitTimeMs = UINT_MAX;
7071 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7072 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7073 if (strong != 0) {
7074 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7075 if (waitTimeMs < mWaitTimeMs) {
7076 mWaitTimeMs = waitTimeMs;
7077 }
7078 }
7079 }
7080}
7081
7082
7083bool AudioFlinger::DuplicatingThread::outputsReady(
7084 const SortedVector< sp<OutputTrack> > &outputTracks)
7085{
7086 for (size_t i = 0; i < outputTracks.size(); i++) {
7087 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7088 if (thread == 0) {
7089 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7090 outputTracks[i].get());
7091 return false;
7092 }
7093 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7094 // see note at standby() declaration
7095 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7096 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7097 thread.get());
7098 return false;
7099 }
7100 }
7101 return true;
7102}
7103
Kevin Rocard12381092018-04-11 09:19:59 -07007104void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7105 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007106{
Kevin Rocard12381092018-04-11 09:19:59 -07007107 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7108 outputTrack->setMetadatas(metadata.tracks);
7109 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007110}
7111
Eric Laurent81784c32012-11-19 14:55:58 -08007112uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7113{
7114 return (mWaitTimeMs * 1000) / 2;
7115}
7116
7117void AudioFlinger::DuplicatingThread::cacheParameters_l()
7118{
7119 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7120 updateWaitTime_l();
7121
7122 MixerThread::cacheParameters_l();
7123}
7124
Eric Laurentb3f315a2021-07-13 15:09:05 +02007125// ----------------------------------------------------------------------------
7126
Eric Laurentfa0f6742021-08-17 18:39:44 +02007127AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007128 AudioStreamOut* output,
7129 audio_io_handle_t id,
7130 bool systemReady,
7131 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007132 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007133{
7134}
7135
Eric Laurentfa0f6742021-08-17 18:39:44 +02007136void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007137{
7138 bool hasVirtualizer = false;
7139 bool hasDownMixer = false;
7140 sp<EffectHandle> finalDownMixer;
7141 {
7142 Mutex::Autolock _l(mLock);
7143 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7144 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007145 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007146 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7147 }
7148
7149 finalDownMixer = mFinalDownMixer;
7150 mFinalDownMixer.clear();
7151 }
7152
7153 if (hasVirtualizer) {
7154 if (finalDownMixer != nullptr) {
7155 int32_t ret;
7156 finalDownMixer->disable(&ret);
7157 }
7158 finalDownMixer.clear();
7159 } else if (!hasDownMixer) {
7160 std::vector<effect_descriptor_t> descriptors;
7161 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7162 EFFECT_UIID_DOWNMIX, &descriptors);
7163 if (status != NO_ERROR) {
7164 return;
7165 }
7166 ALOG_ASSERT(!descriptors.empty(),
7167 "%s getDescriptors() returned no error but empty list", __func__);
7168
7169 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7170 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007171 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007172
7173 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7174 ALOGW("%s error creating downmixer %d", __func__, status);
7175 finalDownMixer.clear();
7176 } else {
7177 int32_t ret;
7178 finalDownMixer->enable(&ret);
7179 }
7180 }
7181
7182 {
7183 Mutex::Autolock _l(mLock);
7184 mFinalDownMixer = finalDownMixer;
7185 }
7186}
7187
Eric Laurent6acd1d42017-01-04 14:23:29 -08007188
Eric Laurent81784c32012-11-19 14:55:58 -08007189// ----------------------------------------------------------------------------
7190// Record
7191// ----------------------------------------------------------------------------
7192
7193AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7194 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007195 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007196 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007197 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007198 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007199 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007200 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007201 mActiveTracks(&this->mLocalLog),
7202 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007203 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007204 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007205 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7206 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007207 // mFastCapture below
7208 , mFastCaptureFutex(0)
7209 // mInputSource
7210 // mPipeSink
7211 // mPipeSource
7212 , mPipeFramesP2(0)
7213 // mPipeMemory
7214 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007215 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007216 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007217{
Glenn Kastend7dca052015-03-05 16:05:54 -08007218 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7219 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007220
George Burgess IVa8f90c12020-05-14 11:27:19 -07007221 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007222 mIsMsdDevice = strcmp(
7223 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7224 }
7225
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007226 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007227
Andy Hungc8fddf32018-08-08 18:32:37 -07007228 // TODO: We may also match on address as well as device type for
7229 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007230 // TODO: This property should be ensure that only contains one single device type.
7231 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7232 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007233 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7234 : AUDIO_DEVICE_NONE));
7235
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007236 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007237 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007238 size_t numCounterOffers = 0;
7239 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007240#if !LOG_NDEBUG
7241 ssize_t index =
7242#else
7243 (void)
7244#endif
7245 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007246 ALOG_ASSERT(index == 0);
7247
7248 // initialize fast capture depending on configuration
7249 bool initFastCapture;
7250 switch (kUseFastCapture) {
7251 case FastCapture_Never:
7252 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007253 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007254 break;
7255 case FastCapture_Always:
7256 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007257 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007258 break;
7259 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007260 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007261 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7262 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7263 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007264 break;
7265 // case FastCapture_Dynamic:
7266 }
7267
7268 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007269 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007270 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007271 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7272 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007273 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007274 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007275 const sp<MemoryDealer> roHeap(readOnlyHeap());
7276 sp<IMemory> pipeMemory;
7277 if ((roHeap == 0) ||
7278 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007279 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007280 ALOGE("not enough memory for pipe buffer size=%zu; "
7281 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7282 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7283 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007284 goto failed;
7285 }
7286 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7287 memset(pipeBuffer, 0, pipeSize);
7288 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7289 const NBAIO_Format offers[1] = {format};
7290 size_t numCounterOffers = 0;
7291 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7292 ALOG_ASSERT(index == 0);
7293 mPipeSink = pipe;
7294 PipeReader *pipeReader = new PipeReader(*pipe);
7295 numCounterOffers = 0;
7296 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7297 ALOG_ASSERT(index == 0);
7298 mPipeSource = pipeReader;
7299 mPipeFramesP2 = pipeFramesP2;
7300 mPipeMemory = pipeMemory;
7301
7302 // create fast capture
7303 mFastCapture = new FastCapture();
7304 FastCaptureStateQueue *sq = mFastCapture->sq();
7305#ifdef STATE_QUEUE_DUMP
7306 // FIXME
7307#endif
7308 FastCaptureState *state = sq->begin();
7309 state->mCblk = NULL;
7310 state->mInputSource = mInputSource.get();
7311 state->mInputSourceGen++;
7312 state->mPipeSink = pipe;
7313 state->mPipeSinkGen++;
7314 state->mFrameCount = mFrameCount;
7315 state->mCommand = FastCaptureState::COLD_IDLE;
7316 // already done in constructor initialization list
7317 //mFastCaptureFutex = 0;
7318 state->mColdFutexAddr = &mFastCaptureFutex;
7319 state->mColdGen++;
7320 state->mDumpState = &mFastCaptureDumpState;
7321#ifdef TEE_SINK
7322 // FIXME
7323#endif
7324 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7325 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7326 sq->end();
7327 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7328
7329 // start the fast capture
7330 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7331 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007332 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007333 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007334#ifdef AUDIO_WATCHDOG
7335 // FIXME
7336#endif
7337
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007338 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007339 }
Andy Hung8946a282018-04-19 20:04:56 -07007340#ifdef TEE_SINK
7341 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7342 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7343#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007344failed: ;
7345
7346 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007347}
7348
Eric Laurent81784c32012-11-19 14:55:58 -08007349AudioFlinger::RecordThread::~RecordThread()
7350{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007351 if (mFastCapture != 0) {
7352 FastCaptureStateQueue *sq = mFastCapture->sq();
7353 FastCaptureState *state = sq->begin();
7354 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7355 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7356 if (old == -1) {
7357 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7358 }
7359 }
7360 state->mCommand = FastCaptureState::EXIT;
7361 sq->end();
7362 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7363 mFastCapture->join();
7364 mFastCapture.clear();
7365 }
7366 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007367 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007368 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007369}
7370
7371void AudioFlinger::RecordThread::onFirstRef()
7372{
Glenn Kastend7dca052015-03-05 16:05:54 -08007373 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007374}
7375
Eric Laurent555530a2017-02-07 18:17:24 -08007376void AudioFlinger::RecordThread::preExit()
7377{
7378 ALOGV(" preExit()");
7379 Mutex::Autolock _l(mLock);
7380 for (size_t i = 0; i < mTracks.size(); i++) {
7381 sp<RecordTrack> track = mTracks[i];
7382 track->invalidate();
7383 }
7384 mActiveTracks.clear();
7385 mStartStopCond.broadcast();
7386}
7387
Eric Laurent81784c32012-11-19 14:55:58 -08007388bool AudioFlinger::RecordThread::threadLoop()
7389{
Eric Laurent81784c32012-11-19 14:55:58 -08007390 nsecs_t lastWarning = 0;
7391
7392 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007393
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007394reacquire_wakelock:
7395 sp<RecordTrack> activeTrack;
7396 {
7397 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007398 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007399 }
7400
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007401 // used to request a deferred sleep, to be executed later while mutex is unlocked
7402 uint32_t sleepUs = 0;
7403
Andy Hung446f4df2019-02-21 12:26:41 -08007404 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7405
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007406 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007407 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007408 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007409
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007410 // activeTracks accumulates a copy of a subset of mActiveTracks
7411 Vector< sp<RecordTrack> > activeTracks;
7412
Glenn Kasten735f45f2014-08-18 15:51:59 -07007413 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007414 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007415
Glenn Kasten735f45f2014-08-18 15:51:59 -07007416 // reference to a fast track which is about to be removed
7417 sp<RecordTrack> fastTrackToRemove;
7418
Eric Laurent33403f02020-05-29 18:35:06 -07007419 bool silenceFastCapture = false;
7420
Eric Laurent81784c32012-11-19 14:55:58 -08007421 { // scope for mLock
7422 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007423
Eric Laurent021cf962014-05-13 10:18:14 -07007424 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007425
Eric Laurent000a4192014-01-29 15:17:32 -08007426 // check exitPending here because checkForNewParameters_l() and
7427 // checkForNewParameters_l() can temporarily release mLock
7428 if (exitPending()) {
7429 break;
7430 }
7431
Eric Laurent5c25d562016-07-13 17:17:45 -07007432 // sleep with mutex unlocked
7433 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007434 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007435 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7436 ATRACE_END();
7437 sleepUs = 0;
7438 continue;
7439 }
7440
Glenn Kasten2b806402013-11-20 16:37:38 -08007441 // if no active track(s), then standby and release wakelock
7442 size_t size = mActiveTracks.size();
7443 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007444 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007445 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007446 releaseWakeLock_l();
7447 ALOGV("RecordThread: loop stopping");
7448 // go to sleep
7449 mWaitWorkCV.wait(mLock);
7450 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007451 goto reacquire_wakelock;
7452 }
7453
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007454 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007455 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007456 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007457
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007458 activeTrack = mActiveTracks[i];
7459 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007460 if (activeTrack->isFastTrack()) {
7461 ALOG_ASSERT(fastTrackToRemove == 0);
7462 fastTrackToRemove = activeTrack;
7463 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007464 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007465 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007466 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007467 continue;
7468 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007469
7470 TrackBase::track_state activeTrackState = activeTrack->mState;
7471 switch (activeTrackState) {
7472
7473 case TrackBase::PAUSING:
7474 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007475 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007476 doBroadcast = true;
7477 size--;
7478 continue;
7479
7480 case TrackBase::STARTING_1:
7481 sleepUs = 10000;
7482 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007483 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007484 continue;
7485
7486 case TrackBase::STARTING_2:
7487 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007488 if (mStandby) {
7489 mThreadMetrics.logBeginInterval();
7490 mStandby = false;
7491 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007492 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007493 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007494 break;
7495
7496 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007497 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007498 break;
7499
Andy Hungce685402018-10-05 17:23:27 -07007500 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7501 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7502 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007503 default:
Andy Hungce685402018-10-05 17:23:27 -07007504 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7505 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007506 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007507
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007508 if (activeTrack->isFastTrack()) {
7509 ALOG_ASSERT(!mFastTrackAvail);
7510 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007511 // if the active fast track is silenced either:
7512 // 1) silence the whole capture from fast capture buffer if this is
7513 // the only active track
7514 // 2) invalidate this track: this will cause the client to reconnect and possibly
7515 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007516 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007517 if (activeTrack->isSilenced()) {
7518 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007519 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007520 } else {
7521 silenceFastCapture = true;
7522 }
7523 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007524 // Invalidate fast tracks if access to audio history is required as this is not
7525 // possible with fast tracks. Once the fast track has been invalidated, no new
7526 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7527 if (mMaxSharedAudioHistoryMs != 0) {
7528 invalidate = true;
7529 }
7530 if (invalidate) {
7531 activeTrack->invalidate();
7532 ALOG_ASSERT(fastTrackToRemove == 0);
7533 fastTrackToRemove = activeTrack;
7534 removeTrack_l(activeTrack);
7535 mActiveTracks.remove(activeTrack);
7536 size--;
7537 continue;
7538 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007539 fastTrack = activeTrack;
7540 }
Eric Laurent33403f02020-05-29 18:35:06 -07007541
7542 activeTracks.add(activeTrack);
7543 i++;
7544
Glenn Kasten9e982352013-08-14 14:39:50 -07007545 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007546
Andy Hungdae27702016-10-31 14:01:16 -07007547 mActiveTracks.updatePowerState(this);
7548
Kevin Rocard069c2712018-03-29 19:09:14 -07007549 updateMetadata_l();
7550
Eric Laurent5c25d562016-07-13 17:17:45 -07007551 if (allStopped) {
7552 standbyIfNotAlreadyInStandby();
7553 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007554 if (doBroadcast) {
7555 mStartStopCond.broadcast();
7556 }
7557
7558 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007559 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007560 if (sleepUs == 0) {
7561 sleepUs = kRecordThreadSleepUs;
7562 }
7563 continue;
7564 }
7565 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007566
Eric Laurent81784c32012-11-19 14:55:58 -08007567 lockEffectChains_l(effectChains);
7568 }
7569
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007570 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007571
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007572 size_t size = effectChains.size();
7573 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007574 // thread mutex is not locked, but effect chain is locked
7575 effectChains[i]->process_l();
7576 }
7577
Glenn Kasten735f45f2014-08-18 15:51:59 -07007578 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007579 if (mFastCapture != 0) {
7580 FastCaptureStateQueue *sq = mFastCapture->sq();
7581 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007582 bool didModify = false;
7583 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007584 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7585 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7586 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7587 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7588 if (old == -1) {
7589 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7590 }
7591 }
7592 state->mCommand = FastCaptureState::READ_WRITE;
7593#if 0 // FIXME
7594 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007595 FastThreadDumpState::kSamplingNforLowRamDevice :
7596 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007597#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007598 didModify = true;
7599 }
7600 audio_track_cblk_t *cblkOld = state->mCblk;
7601 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7602 if (cblkNew != cblkOld) {
7603 state->mCblk = cblkNew;
7604 // block until acked if removing a fast track
7605 if (cblkOld != NULL) {
7606 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7607 }
7608 didModify = true;
7609 }
jiabin01c8f562018-07-19 17:47:28 -07007610 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7611 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7612 if (state->mFastPatchRecordBufferProvider != abp) {
7613 state->mFastPatchRecordBufferProvider = abp;
7614 state->mFastPatchRecordFormat = fastTrack == 0 ?
7615 AUDIO_FORMAT_INVALID : fastTrack->format();
7616 didModify = true;
7617 }
Eric Laurent33403f02020-05-29 18:35:06 -07007618 if (state->mSilenceCapture != silenceFastCapture) {
7619 state->mSilenceCapture = silenceFastCapture;
7620 didModify = true;
7621 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007622 sq->end(didModify);
7623 if (didModify) {
7624 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007625#if 0
7626 if (kUseFastCapture == FastCapture_Dynamic) {
7627 mNormalSource = mPipeSource;
7628 }
7629#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007630 }
7631 }
7632
Glenn Kasten735f45f2014-08-18 15:51:59 -07007633 // now run the fast track destructor with thread mutex unlocked
7634 fastTrackToRemove.clear();
7635
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007636 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7637 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7638 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7639 // If destination is non-contiguous, first read past the nominal end of buffer, then
7640 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007641
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007642 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007643 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007644 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007645
7646 // If an NBAIO source is present, use it to read the normal capture's data
7647 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007648 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007649
7650 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7651 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7652 // we immediately retry the read() to get data and prevent another overflow.
7653 for (int retries = 0; retries <= 2; ++retries) {
7654 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7655 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7656 framesToRead);
7657 if (framesRead != OVERRUN) break;
7658 }
7659
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007660 const ssize_t availableToRead = mPipeSource->availableToRead();
7661 if (availableToRead >= 0) {
Glenn Kastena2f59b32020-08-03 16:37:24 -07007662 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007663 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7664 "more frames to read than fifo size, %zd > %zu",
7665 availableToRead, mPipeFramesP2);
7666 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7667 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7668 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7669 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007670 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7671 }
7672 if (framesRead < 0) {
7673 status_t status = (status_t) framesRead;
7674 switch (status) {
7675 case OVERRUN:
7676 ALOGW("overrun on read from pipe");
7677 framesRead = 0;
7678 break;
7679 case NEGOTIATE:
7680 ALOGE("re-negotiation is needed");
7681 framesRead = -1; // Will cause an attempt to recover.
7682 break;
7683 default:
7684 ALOGE("unknown error %d on read from pipe", status);
7685 break;
7686 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007687 }
7688 // otherwise use the HAL / AudioStreamIn directly
7689 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007690 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007691 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007692 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007693 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007694 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007695 if (result < 0) {
7696 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007697 } else {
7698 framesRead = bytesRead / mFrameSize;
7699 }
7700 }
7701
Andy Hung446f4df2019-02-21 12:26:41 -08007702 const int64_t lastIoEndNs = systemTime(); // end IO timing
7703
Andy Hung3f0c9022016-01-15 17:49:46 -08007704 // Update server timestamp with server stats
7705 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007706 if (framesRead >= 0) {
7707 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7708 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7709 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007710
7711 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007712 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007713 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007714 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007715 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7716 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7717 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007718 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007719 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7720
7721 mTimestampVerifier.add(position, time, mSampleRate);
7722
7723 // Correct timestamps
7724 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007725 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007726 id(), (long long)time, (long long)position);
7727 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7728 position = correctedTimestamp.mFrames;
7729 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007730 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007731 id(), (long long)time, (long long)position);
7732 }
7733
Andy Hung3f0c9022016-01-15 17:49:46 -08007734 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7735 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7736 // Note: In general record buffers should tend to be empty in
7737 // a properly running pipeline.
7738 //
7739 // Also, it is not advantageous to call get_presentation_position during the read
7740 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007741 } else {
7742 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007743 }
7744 }
Andy Hunge6c37112019-02-26 17:38:10 -08007745
7746 // From the timestamp, input read latency is negative output write latency.
7747 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7748 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7749 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7750 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7751 mLatencyMs.add(latencyMs);
7752 }
7753
Andy Hung3f0c9022016-01-15 17:49:46 -08007754 // Use this to track timestamp information
7755 // ALOGD("%s", mTimestamp.toString().c_str());
7756
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007757 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007758 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007759 // Force input into standby so that it tries to recover at next read attempt
7760 inputStandBy();
7761 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007762 }
7763 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007764 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007765 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007766 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007767 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007768
Andy Hung8946a282018-04-19 20:04:56 -07007769#ifdef TEE_SINK
7770 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7771#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007772 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007773 {
7774 size_t part1 = mRsmpInFramesP2 - rear;
7775 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007776 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007777 (framesRead - part1) * mFrameSize);
7778 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007779 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007780 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007781
7782 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007783
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007784 // loop over each active track
7785 for (size_t i = 0; i < size; i++) {
7786 activeTrack = activeTracks[i];
7787
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007788 // skip fast tracks, as those are handled directly by FastCapture
7789 if (activeTrack->isFastTrack()) {
7790 continue;
7791 }
7792
Andy Hung73c02e42015-03-29 01:13:58 -07007793 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007794 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7795
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007796 enum {
7797 OVERRUN_UNKNOWN,
7798 OVERRUN_TRUE,
7799 OVERRUN_FALSE
7800 } overrun = OVERRUN_UNKNOWN;
7801
7802 // loop over getNextBuffer to handle circular sink
7803 for (;;) {
7804
7805 activeTrack->mSink.frameCount = ~0;
7806 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7807 size_t framesOut = activeTrack->mSink.frameCount;
7808 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7809
Andy Hung73c02e42015-03-29 01:13:58 -07007810 // check available frames and handle overrun conditions
7811 // if the record track isn't draining fast enough.
7812 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007813 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007814 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7815 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007816 overrun = OVERRUN_TRUE;
7817 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007818 if (framesOut == 0 || framesIn == 0) {
7819 break;
7820 }
7821
Andy Hung6770c6f2015-04-07 13:43:36 -07007822 // Don't allow framesOut to be larger than what is possible with resampling
7823 // from framesIn.
7824 // This isn't strictly necessary but helps limit buffer resizing in
7825 // RecordBufferConverter. TODO: remove when no longer needed.
7826 framesOut = min(framesOut,
7827 destinationFramesPossible(
7828 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007829
7830 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007831 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007832 // straight from RecordThread buffer to RecordTrack buffer.
7833 AudioBufferProvider::Buffer buffer;
7834 buffer.frameCount = framesOut;
7835 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7836 if (status == OK && buffer.frameCount != 0) {
7837 ALOGV_IF(buffer.frameCount != framesOut,
7838 "%s() read less than expected (%zu vs %zu)",
7839 __func__, buffer.frameCount, framesOut);
7840 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007841 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007842 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7843 } else {
7844 framesOut = 0;
7845 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7846 __func__, status, buffer.frameCount);
7847 }
7848 } else {
7849 // process frames from the RecordThread buffer provider to the RecordTrack
7850 // buffer
7851 framesOut = activeTrack->mRecordBufferConverter->convert(
7852 activeTrack->mSink.raw,
7853 activeTrack->mResamplerBufferProvider,
7854 framesOut);
7855 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007856
7857 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7858 overrun = OVERRUN_FALSE;
7859 }
7860
7861 if (activeTrack->mFramesToDrop == 0) {
7862 if (framesOut > 0) {
7863 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007864 // Sanitize before releasing if the track has no access to the source data
7865 // An idle UID receives silence from non virtual devices until active
7866 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007867 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007868 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007869 activeTrack->releaseBuffer(&activeTrack->mSink);
7870 }
7871 } else {
7872 // FIXME could do a partial drop of framesOut
7873 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007874 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007875 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007876 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007877 }
7878 } else {
7879 activeTrack->mFramesToDrop += framesOut;
7880 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7881 activeTrack->mSyncStartEvent->isCancelled()) {
7882 ALOGW("Synced record %s, session %d, trigger session %d",
7883 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7884 activeTrack->sessionId(),
7885 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007886 activeTrack->mSyncStartEvent->triggerSession() :
7887 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007888 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007889 }
7890 }
7891 }
7892
7893 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007894 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007895 }
7896 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007897
7898 switch (overrun) {
7899 case OVERRUN_TRUE:
7900 // client isn't retrieving buffers fast enough
7901 if (!activeTrack->setOverflow()) {
7902 nsecs_t now = systemTime();
7903 // FIXME should lastWarning per track?
7904 if ((now - lastWarning) > kWarningThrottleNs) {
7905 ALOGW("RecordThread: buffer overflow");
7906 lastWarning = now;
7907 }
7908 }
7909 break;
7910 case OVERRUN_FALSE:
7911 activeTrack->clearOverflow();
7912 break;
7913 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007914 break;
7915 }
7916
Andy Hung3f0c9022016-01-15 17:49:46 -08007917 // update frame information and push timestamp out
7918 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007919 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007920 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7921 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007922 }
7923
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007924unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007925 // enable changes in effect chain
7926 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007927 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007928 if (audio_has_proportional_frames(mFormat)
7929 && loopCount == lastLoopCountRead + 1) {
7930 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7931 const double jitterMs =
7932 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7933 {framesRead, readPeriodNs},
7934 {0, 0} /* lastTimestamp */, mSampleRate);
7935 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7936
7937 Mutex::Autolock _l(mLock);
7938 mIoJitterMs.add(jitterMs);
7939 mProcessTimeMs.add(processMs);
7940 }
7941 // update timing info.
7942 mLastIoBeginNs = lastIoBeginNs;
7943 mLastIoEndNs = lastIoEndNs;
7944 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007945 }
7946
Glenn Kasten93e471f2013-08-19 08:40:07 -07007947 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007948
7949 {
7950 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007951 for (size_t i = 0; i < mTracks.size(); i++) {
7952 sp<RecordTrack> track = mTracks[i];
7953 track->invalidate();
7954 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007955 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007956 mStartStopCond.broadcast();
7957 }
7958
7959 releaseWakeLock();
7960
7961 ALOGV("RecordThread %p exiting", this);
7962 return false;
7963}
7964
Glenn Kasten93e471f2013-08-19 08:40:07 -07007965void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007966{
7967 if (!mStandby) {
7968 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007969 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007970 mStandby = true;
7971 }
7972}
7973
7974void AudioFlinger::RecordThread::inputStandBy()
7975{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007976 // Idle the fast capture if it's currently running
7977 if (mFastCapture != 0) {
7978 FastCaptureStateQueue *sq = mFastCapture->sq();
7979 FastCaptureState *state = sq->begin();
7980 if (!(state->mCommand & FastCaptureState::IDLE)) {
7981 state->mCommand = FastCaptureState::COLD_IDLE;
7982 state->mColdFutexAddr = &mFastCaptureFutex;
7983 state->mColdGen++;
7984 mFastCaptureFutex = 0;
7985 sq->end();
7986 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7987 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7988#if 0
7989 if (kUseFastCapture == FastCapture_Dynamic) {
7990 // FIXME
7991 }
7992#endif
7993#ifdef AUDIO_WATCHDOG
7994 // FIXME
7995#endif
7996 } else {
7997 sq->end(false /*didModify*/);
7998 }
7999 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008000 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008001 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008002
8003 // If going into standby, flush the pipe source.
8004 if (mPipeSource.get() != nullptr) {
8005 const ssize_t flushed = mPipeSource->flush();
8006 if (flushed > 0) {
8007 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8008 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8009 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8010 }
8011 }
Eric Laurent81784c32012-11-19 14:55:58 -08008012}
8013
Glenn Kasten05997e22014-03-13 15:08:33 -07008014// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008015sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008016 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008017 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008018 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008019 audio_format_t format,
8020 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008021 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008022 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008023 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008024 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008025 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008026 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008027 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008028 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008029 audio_port_handle_t portId,
8030 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008031{
Glenn Kasten74935e42013-12-19 08:56:45 -08008032 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008033 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008034 sp<RecordTrack> track;
8035 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008036 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008037 audio_input_flags_t requestedFlags = *flags;
8038 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00008039 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8040 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008041
8042 lStatus = initCheck();
8043 if (lStatus != NO_ERROR) {
8044 ALOGE("createRecordTrack_l() audio driver not initialized");
8045 goto Exit;
8046 }
8047
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008048 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8049 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8050 lStatus = BAD_VALUE;
8051 goto Exit;
8052 }
8053
Eric Laurentec376dc2021-04-08 20:41:22 +02008054 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00008055 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008056 lStatus = PERMISSION_DENIED;
8057 goto Exit;
8058 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008059 if (maxSharedAudioHistoryMs < 0
8060 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8061 lStatus = BAD_VALUE;
8062 goto Exit;
8063 }
8064 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008065 if (*pSampleRate == 0) {
8066 *pSampleRate = mSampleRate;
8067 }
8068 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008069
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008070 // special case for FAST flag considered OK if fast capture is present and access to
8071 // audio history is not required
8072 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008073 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8074 }
8075
Eric Laurentf14db3c2017-12-08 14:20:36 -08008076 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008077 if ((*flags & inputFlags) != *flags) {
8078 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8079 " input flags (%08x)",
8080 *flags, inputFlags);
8081 *flags = (audio_input_flags_t)(*flags & inputFlags);
8082 }
Eric Laurent81784c32012-11-19 14:55:58 -08008083
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008084 // client expresses a preference for FAST and no access to audio history,
8085 // but we get the final say
8086 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008087 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008088 // we formerly checked for a callback handler (non-0 tid),
8089 // but that is no longer required for TRANSFER_OBTAIN mode
8090 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008091 // Frame count is not specified (0), or is less than or equal the pipe depth.
8092 // It is OK to provide a higher capacity than requested.
8093 // We will force it to mPipeFramesP2 below.
8094 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008095 // PCM data
8096 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008097 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008098 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008099 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008100 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008101 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008102 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008103 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008104 hasFastCapture() &&
8105 // there are sufficient fast track slots available
8106 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008107 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008108 // check compatibility with audio effects.
8109 Mutex::Autolock _l(mLock);
8110 // Do not accept FAST flag if the session has software effects
8111 sp<EffectChain> chain = getEffectChain_l(sessionId);
8112 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008113 audio_input_flags_t old = *flags;
8114 chain->checkInputFlagCompatibility(flags);
8115 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008116 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8117 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008118 }
8119 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008120 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008121 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8122 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008123 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008124 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8125 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008126 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008127 this, frameCount, mFrameCount, mPipeFramesP2,
8128 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008129 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008130 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008131 }
8132 }
8133
Eric Laurentf14db3c2017-12-08 14:20:36 -08008134 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8135 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8136 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8137 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8138 lStatus = BAD_TYPE;
8139 goto Exit;
8140 }
8141
Glenn Kasten74105912014-07-03 12:28:53 -07008142 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008143 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008144 // fast track: frame count is exactly the pipe depth
8145 frameCount = mPipeFramesP2;
8146 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008147 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008148 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008149 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8150 // or 20 ms if there is a fast capture
8151 // TODO This could be a roundupRatio inline, and const
8152 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8153 * sampleRate + mSampleRate - 1) / mSampleRate;
8154 // minimum number of notification periods is at least kMinNotifications,
8155 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8156 static const size_t kMinNotifications = 3;
8157 static const uint32_t kMinMs = 30;
8158 // TODO This could be a roundupRatio inline
8159 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8160 // TODO This could be a roundupRatio inline
8161 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8162 maxNotificationFrames;
8163 const size_t minFrameCount = maxNotificationFrames *
8164 max(kMinNotifications, minNotificationsByMs);
8165 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008166 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8167 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008168 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008169 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008170 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008171 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008172
8173 { // scope for mLock
8174 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008175 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008176 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008177 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008178 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008179 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008180 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008181 }
Eric Laurent81784c32012-11-19 14:55:58 -08008182
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008183 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008184 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008185 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008186 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8187 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008188
Glenn Kasten03003332013-08-06 15:40:54 -07008189 lStatus = track->initCheck();
8190 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008191 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008192 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008193 goto Exit;
8194 }
8195 mTracks.add(track);
8196
Eric Laurent05067782016-06-01 18:27:28 -07008197 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008198 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8199 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8200 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008201 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008202 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008203
8204 if (maxSharedAudioHistoryMs != 0) {
8205 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8206 }
Eric Laurent81784c32012-11-19 14:55:58 -08008207 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008208
Eric Laurent81784c32012-11-19 14:55:58 -08008209 lStatus = NO_ERROR;
8210
8211Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008212 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008213 return track;
8214}
8215
8216status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8217 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008218 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008219{
8220 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8221 sp<ThreadBase> strongMe = this;
8222 status_t status = NO_ERROR;
8223
8224 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008225 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008226 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008227 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008228 triggerSession,
8229 recordTrack->sessionId(),
8230 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008231 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008232 // Sync event can be cancelled by the trigger session if the track is not in a
8233 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008234 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008235 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008236 } else {
8237 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008238 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008239 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008240 }
8241 }
8242
8243 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008244 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008245 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008246 if (recordTrack->isInvalid()) {
8247 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008248 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8249 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008250 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008251 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8252 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008253 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8254 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008255 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008256 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008257 } else {
8258 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008259 }
8260 return status;
8261 }
8262
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008263 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8264 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8265 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008266 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008267 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008268 status_t status = NO_ERROR;
8269 if (recordTrack->isExternalTrack()) {
8270 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008271 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008272 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008273 if (recordTrack->isInvalid()) {
8274 recordTrack->clearSyncStartEvent();
8275 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8276 recordTrack->mState = TrackBase::STARTING_2;
8277 // STARTING_2 forces destroy to call stopInput.
8278 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008279 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8280 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008281 }
8282 if (recordTrack->mState != TrackBase::STARTING_1) {
8283 ALOGW("%s(%d): unsynchronized mState:%d change",
8284 __func__, recordTrack->id(), recordTrack->mState);
8285 // Someone else has changed state, let them take over,
8286 // leave mState in the new state.
8287 recordTrack->clearSyncStartEvent();
8288 return INVALID_OPERATION;
8289 }
8290 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008291 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008292 ALOGW("%s(%d): startInput failed, status %d",
8293 __func__, recordTrack->id(), status);
8294 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8295 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008296 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008297 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008298 return status;
8299 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008300 sendIoConfigEvent_l(
8301 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008302 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008303
8304 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8305
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008306 // Catch up with current buffer indices if thread is already running.
8307 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8308 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8309 // see previously buffered data before it called start(), but with greater risk of overrun.
8310
Andy Hung73c02e42015-03-29 01:13:58 -07008311 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008312 if (!recordTrack->isDirect()) {
8313 // clear any converter state as new data will be discontinuous
8314 recordTrack->mRecordBufferConverter->reset();
8315 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008316 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008317 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008318 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008319 return status;
8320 }
Eric Laurent81784c32012-11-19 14:55:58 -08008321}
8322
Eric Laurent81784c32012-11-19 14:55:58 -08008323void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8324{
8325 sp<SyncEvent> strongEvent = event.promote();
8326
8327 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008328 sp<RefBase> ptr = strongEvent->cookie().promote();
8329 if (ptr != 0) {
8330 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8331 recordTrack->handleSyncStartEvent(strongEvent);
8332 }
Eric Laurent81784c32012-11-19 14:55:58 -08008333 }
8334}
8335
Glenn Kastena8356f62013-07-25 14:37:52 -07008336bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008337 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008338 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008339 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008340 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008341 return false;
8342 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008343 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008344 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008345
Andy Hungabfab202019-03-07 19:45:54 -08008346 // NOTE: Waiting here is important to keep stop synchronous.
8347 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008348 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8349 mWaitWorkCV.broadcast(); // signal thread to stop
8350 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008351 }
Andy Hungce685402018-10-05 17:23:27 -07008352
8353 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008354 ALOGV("Record stopped OK");
8355 return true;
8356 }
Andy Hungce685402018-10-05 17:23:27 -07008357
8358 // don't handle anything - we've been invalidated or restarted and in a different state
8359 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8360 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008361 return false;
8362}
8363
Glenn Kasten0f11b512014-01-31 16:18:54 -08008364bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008365{
8366 return false;
8367}
8368
Glenn Kasten0f11b512014-01-31 16:18:54 -08008369status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008370{
8371#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8372 if (!isValidSyncEvent(event)) {
8373 return BAD_VALUE;
8374 }
8375
Glenn Kastend848eb42016-03-08 13:42:11 -08008376 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008377 status_t ret = NAME_NOT_FOUND;
8378
8379 Mutex::Autolock _l(mLock);
8380
8381 for (size_t i = 0; i < mTracks.size(); i++) {
8382 sp<RecordTrack> track = mTracks[i];
8383 if (eventSession == track->sessionId()) {
8384 (void) track->setSyncEvent(event);
8385 ret = NO_ERROR;
8386 }
8387 }
8388 return ret;
8389#else
8390 return BAD_VALUE;
8391#endif
8392}
8393
jiabin653cc0a2018-01-17 17:54:10 -08008394status_t AudioFlinger::RecordThread::getActiveMicrophones(
8395 std::vector<media::MicrophoneInfo>* activeMicrophones)
8396{
8397 ALOGV("RecordThread::getActiveMicrophones");
8398 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008399 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008400 return NO_INIT;
8401 }
jiabin9ff780e2018-03-19 18:19:52 -07008402 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8403 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008404}
8405
Paul McLean12340082019-03-19 09:35:05 -06008406status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8407 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008408{
Paul McLean12340082019-03-19 09:35:05 -06008409 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008410 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008411 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008412 return NO_INIT;
8413 }
Paul McLean12340082019-03-19 09:35:05 -06008414 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008415}
8416
Paul McLean12340082019-03-19 09:35:05 -06008417status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008418{
Paul McLean12340082019-03-19 09:35:05 -06008419 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008420 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008421 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008422 return NO_INIT;
8423 }
Paul McLean12340082019-03-19 09:35:05 -06008424 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008425}
8426
Eric Laurentec376dc2021-04-08 20:41:22 +02008427status_t AudioFlinger::RecordThread::shareAudioHistory(
8428 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8429 int64_t sharedAudioStartMs) {
8430 AutoMutex _l(mLock);
8431 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8432}
8433
8434status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8435 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8436 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008437
Eric Laurentec376dc2021-04-08 20:41:22 +02008438 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8439 return BAD_VALUE;
8440 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008441
8442 if (sharedAudioStartMs < 0
8443 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008444 return BAD_VALUE;
8445 }
8446
Eric Laurent2407ce32021-04-26 14:56:03 +02008447 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8448 // As we cannot detect more than one wraparound, only accept values up current write position
8449 // after one wraparound
8450 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8451 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008452 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008453 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8454 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008455 // Bring the start frame position within the input buffer to match the documented
8456 // "best effort" behavior of the API.
8457 if (sharedOffset < 0) {
8458 sharedAudioStartFrames = mRsmpInRear;
8459 } else if (sharedOffset > mRsmpInFrames) {
8460 sharedAudioStartFrames =
8461 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008462 }
8463
Eric Laurentec376dc2021-04-08 20:41:22 +02008464 mSharedAudioPackageName = sharedAudioPackageName;
8465 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008466 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008467 } else {
8468 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008469 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008470 }
8471 return NO_ERROR;
8472}
8473
Eric Laurent92d0a322021-07-16 15:32:33 +02008474void AudioFlinger::RecordThread::resetAudioHistory_l() {
8475 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8476 mSharedAudioStartFrames = -1;
8477 mSharedAudioPackageName = "";
8478}
8479
Kevin Rocard069c2712018-03-29 19:09:14 -07008480void AudioFlinger::RecordThread::updateMetadata_l()
8481{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008482 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8483 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008484 }
8485 StreamInHalInterface::SinkMetadata metadata;
8486 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008487 // Do not forward PatchRecord metadata to audio HAL
8488 if (track->isPatchTrack()) {
8489 continue;
8490 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008491 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008492 record_track_metadata_v7_t trackMetadata;
8493 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008494 .source = track->attributes().source,
8495 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008496 };
8497 trackMetadata.channel_mask = track->channelMask(),
8498 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8499
8500 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008501 }
8502 mInput->stream->updateSinkMetadata(metadata);
8503}
8504
Eric Laurent81784c32012-11-19 14:55:58 -08008505// destroyTrack_l() must be called with ThreadBase::mLock held
8506void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8507{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008508 track->terminate();
8509 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008510
Eric Laurent81784c32012-11-19 14:55:58 -08008511 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008512 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008513 removeTrack_l(track);
8514 }
8515}
8516
8517void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8518{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008519 String8 result;
8520 track->appendDump(result, false /* active */);
8521 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8522
Eric Laurent81784c32012-11-19 14:55:58 -08008523 mTracks.remove(track);
8524 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008525 if (track->isFastTrack()) {
8526 ALOG_ASSERT(!mFastTrackAvail);
8527 mFastTrackAvail = true;
8528 }
Eric Laurent81784c32012-11-19 14:55:58 -08008529}
8530
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008531void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008532{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008533 AudioStreamIn *input = mInput;
8534 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8535 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008536 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008537 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008538 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008539 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008540 }
Andy Hungbfa64962017-06-12 14:43:19 -07008541
8542 if (input != nullptr) {
8543 dprintf(fd, " Hal stream dump:\n");
8544 (void)input->stream->dump(fd);
8545 }
8546
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008547 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008548 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008549
Glenn Kasten2f90c512015-12-02 11:40:09 -08008550 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8551 // while we are dumping it. It may be inconsistent, but it won't mutate!
8552 // This is a large object so we place it on the heap.
8553 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008554 const std::unique_ptr<FastCaptureDumpState> copy =
8555 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008556 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008557}
8558
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008559void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008560{
Eric Laurent81784c32012-11-19 14:55:58 -08008561 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008562 size_t numtracks = mTracks.size();
8563 size_t numactive = mActiveTracks.size();
8564 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008565 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008566 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008567 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008568 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008569 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008570 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008571 for (size_t i = 0; i < numtracks ; ++i) {
8572 sp<RecordTrack> track = mTracks[i];
8573 if (track != 0) {
8574 bool active = mActiveTracks.indexOf(track) >= 0;
8575 if (active) {
8576 numactiveseen++;
8577 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008578 result.append(prefix);
8579 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008580 }
Eric Laurent81784c32012-11-19 14:55:58 -08008581 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008582 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008583 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008584 }
8585
Marco Nelissenb2208842014-02-07 14:00:50 -08008586 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008587 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008588 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008589 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008590 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008591 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008592 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008593 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008594 result.append(prefix);
8595 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008596 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008597 }
Eric Laurent81784c32012-11-19 14:55:58 -08008598
8599 }
8600 write(fd, result.string(), result.size());
8601}
8602
Eric Laurent5ada82e2019-08-29 17:53:54 -07008603void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008604{
8605 Mutex::Autolock _l(mLock);
8606 for (size_t i = 0; i < mTracks.size() ; i++) {
8607 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008608 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008609 track->setSilenced(silenced);
8610 }
8611 }
8612}
Andy Hung73c02e42015-03-29 01:13:58 -07008613
8614void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8615{
8616 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8617 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008618 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008619 const int32_t rear = recordThread->mRsmpInRear;
8620 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008621 if (mRecordTrack->startFrames() >= 0) {
8622 int32_t startFrames = mRecordTrack->startFrames();
8623 // Accept a recent wraparound of mRsmpInRear
8624 if (startFrames <= rear) {
8625 deltaFrames = rear - startFrames;
8626 } else {
8627 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008628 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008629 // start frame cannot be further in the past than start of resampling buffer
8630 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8631 deltaFrames = recordThread->mRsmpInFrames;
8632 }
8633 }
8634 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008635}
8636
8637void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8638 size_t *framesAvailable, bool *hasOverrun)
8639{
8640 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8641 RecordThread *recordThread = (RecordThread *) threadBase.get();
8642 const int32_t rear = recordThread->mRsmpInRear;
8643 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008644 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008645
8646 size_t framesIn;
8647 bool overrun = false;
8648 if (filled < 0) {
8649 // should not happen, but treat like a massive overrun and re-sync
8650 framesIn = 0;
8651 mRsmpInFront = rear;
8652 overrun = true;
8653 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8654 framesIn = (size_t) filled;
8655 } else {
8656 // client is not keeping up with server, but give it latest data
8657 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008658 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8659 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008660 overrun = true;
8661 }
8662 if (framesAvailable != NULL) {
8663 *framesAvailable = framesIn;
8664 }
8665 if (hasOverrun != NULL) {
8666 *hasOverrun = overrun;
8667 }
8668}
8669
Eric Laurent81784c32012-11-19 14:55:58 -08008670// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008671status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008672 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008673{
Andy Hung73c02e42015-03-29 01:13:58 -07008674 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008675 if (threadBase == 0) {
8676 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008677 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008678 return NOT_ENOUGH_DATA;
8679 }
8680 RecordThread *recordThread = (RecordThread *) threadBase.get();
8681 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008682 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008683 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008684 // FIXME should not be P2 (don't want to increase latency)
8685 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008686 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008687 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008688
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008689 front &= recordThread->mRsmpInFramesP2 - 1;
8690 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008691 if (part1 > (size_t) filled) {
8692 part1 = filled;
8693 }
8694 size_t ask = buffer->frameCount;
8695 ALOG_ASSERT(ask > 0);
8696 if (part1 > ask) {
8697 part1 = ask;
8698 }
8699 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008700 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008701 buffer->raw = NULL;
8702 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008703 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008704 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008705 }
8706
Andy Hung57446612015-04-19 23:56:46 -07008707 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008708 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008709 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008710 return NO_ERROR;
8711}
8712
8713// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008714void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8715 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008716{
Hongwei Wang95e37682019-04-12 11:13:36 -07008717 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008718 if (stepCount == 0) {
8719 return;
8720 }
Andy Hung73c02e42015-03-29 01:13:58 -07008721 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8722 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008723 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008724 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008725 buffer->frameCount = 0;
8726}
8727
Eric Laurentd8365c52017-07-16 15:27:05 -07008728void AudioFlinger::RecordThread::checkBtNrec()
8729{
8730 Mutex::Autolock _l(mLock);
8731 checkBtNrec_l();
8732}
8733
8734void AudioFlinger::RecordThread::checkBtNrec_l()
8735{
8736 // disable AEC and NS if the device is a BT SCO headset supporting those
8737 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008738 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008739 mAudioFlinger->btNrecIsOff();
8740 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8741 for (size_t i = 0; i < mEffectChains.size(); i++) {
8742 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8743 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8744 }
8745 }
8746}
8747
Andy Hung97a893e2015-03-29 01:03:07 -07008748
Eric Laurent10351942014-05-08 18:49:52 -07008749bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8750 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008751{
8752 bool reconfig = false;
8753
Eric Laurent10351942014-05-08 18:49:52 -07008754 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008755
Eric Laurent10351942014-05-08 18:49:52 -07008756 audio_format_t reqFormat = mFormat;
8757 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008758 // 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 -07008759 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8760
8761 AudioParameter param = AudioParameter(keyValuePair);
8762 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008763
8764 // scope for AutoPark extends to end of method
8765 AutoPark<FastCapture> park(mFastCapture);
8766
Eric Laurent10351942014-05-08 18:49:52 -07008767 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8768 // channel count change can be requested. Do we mandate the first client defines the
8769 // HAL sampling rate and channel count or do we allow changes on the fly?
8770 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8771 samplingRate = value;
8772 reconfig = true;
8773 }
8774 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008775 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008776 status = BAD_VALUE;
8777 } else {
8778 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008779 reconfig = true;
8780 }
Eric Laurent10351942014-05-08 18:49:52 -07008781 }
8782 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8783 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008784 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008785 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008786 status = BAD_VALUE;
8787 } else {
8788 channelMask = mask;
8789 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008790 }
Eric Laurent10351942014-05-08 18:49:52 -07008791 }
8792 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8793 // do not accept frame count changes if tracks are open as the track buffer
8794 // size depends on frame count and correct behavior would not be guaranteed
8795 // if frame count is changed after track creation
8796 if (mActiveTracks.size() > 0) {
8797 status = INVALID_OPERATION;
8798 } else {
8799 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008800 }
Eric Laurent10351942014-05-08 18:49:52 -07008801 }
8802 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008803 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008804 }
8805 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8806 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008807 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008808 }
Glenn Kastene198c362013-08-13 09:13:36 -07008809
Eric Laurent10351942014-05-08 18:49:52 -07008810 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008811 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008812 if (status == INVALID_OPERATION) {
8813 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008814 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008815 }
8816 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008817 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008818 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8819 if (mInput->stream->getAudioProperties(&config) == OK &&
8820 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8821 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008822 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008823 status = NO_ERROR;
8824 }
Eric Laurent81784c32012-11-19 14:55:58 -08008825 }
Eric Laurent10351942014-05-08 18:49:52 -07008826 if (status == NO_ERROR) {
8827 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008828 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008829 }
8830 }
Eric Laurent81784c32012-11-19 14:55:58 -08008831 }
Eric Laurent10351942014-05-08 18:49:52 -07008832
Eric Laurent81784c32012-11-19 14:55:58 -08008833 return reconfig;
8834}
8835
8836String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8837{
Eric Laurent81784c32012-11-19 14:55:58 -08008838 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008839 if (initCheck() == NO_ERROR) {
8840 String8 out_s8;
8841 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8842 return out_s8;
8843 }
Eric Laurent81784c32012-11-19 14:55:58 -08008844 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008845 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008846}
8847
Eric Laurent09f1ed22019-04-24 17:45:17 -07008848void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8849 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008850 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8851
8852 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008853
8854 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008855 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008856 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008857 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008858 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008859 desc->mChannelMask = mChannelMask;
8860 desc->mSamplingRate = mSampleRate;
8861 desc->mFormat = mFormat;
8862 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008863 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008864 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008865 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008866 case AUDIO_CLIENT_STARTED:
8867 desc->mPatch = mPatch;
8868 desc->mPortId = portId;
8869 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008870 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008871 default:
8872 break;
8873 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008874 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008875}
8876
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008877void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008878{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008879 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8880 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008881 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008882 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8883 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008884 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8885 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008886 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008887 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008888 ALOGI("HAL format %#x is not linear pcm", mFormat);
8889 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008890 result = mInput->stream->getFrameSize(&mFrameSize);
8891 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008892 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8893 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008894 result = mInput->stream->getBufferSize(&mBufferSize);
8895 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008896 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008897 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8898 "mBufferSize=%zu, mFrameCount=%zu",
8899 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008900
Eric Laurentec376dc2021-04-08 20:41:22 +02008901 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8902 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008903 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008904
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008905 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8906 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008907
8908 audio_input_flags_t flags = mInput->flags;
8909 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8910 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8911 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8912 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8913 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8914 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8915 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8916 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8917 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008918}
8919
Glenn Kasten5f972c02014-01-13 09:59:31 -08008920uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008921{
8922 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008923 uint32_t result;
8924 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8925 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008926 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008927 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008928}
8929
Glenn Kastend848eb42016-03-08 13:42:11 -08008930KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008931{
Glenn Kastend848eb42016-03-08 13:42:11 -08008932 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008933 Mutex::Autolock _l(mLock);
8934 for (size_t j = 0; j < mTracks.size(); ++j) {
8935 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008936 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008937 if (ids.indexOfKey(sessionId) < 0) {
8938 ids.add(sessionId, true);
8939 }
8940 }
8941 return ids;
8942}
8943
8944AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8945{
8946 Mutex::Autolock _l(mLock);
8947 AudioStreamIn *input = mInput;
8948 mInput = NULL;
8949 return input;
8950}
8951
8952// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008953sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008954{
8955 if (mInput == NULL) {
8956 return NULL;
8957 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008958 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008959}
8960
8961status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8962{
Eric Laurent81784c32012-11-19 14:55:58 -08008963 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008964 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008965 chain->setInBuffer(NULL);
8966 chain->setOutBuffer(NULL);
8967
8968 checkSuspendOnAddEffectChain_l(chain);
8969
Eric Laurent1b928682014-10-02 19:41:47 -07008970 // make sure enabled pre processing effects state is communicated to the HAL as we
8971 // just moved them to a new input stream.
8972 chain->syncHalEffectsState();
8973
Eric Laurent81784c32012-11-19 14:55:58 -08008974 mEffectChains.add(chain);
8975
8976 return NO_ERROR;
8977}
8978
8979size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8980{
8981 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008982
8983 for (size_t i = 0; i < mEffectChains.size(); i++) {
8984 if (chain == mEffectChains[i]) {
8985 mEffectChains.removeAt(i);
8986 break;
8987 }
Eric Laurent81784c32012-11-19 14:55:58 -08008988 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008989 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008990}
8991
Eric Laurent1c333e22014-05-20 10:48:17 -07008992status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8993 audio_patch_handle_t *handle)
8994{
8995 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008996
8997 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008998 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008999 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009000 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009001 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009002 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009003 }
9004
Eric Laurentd8365c52017-07-16 15:27:05 -07009005 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009006
9007 // store new source and send to effects
9008 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9009 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009010 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009011 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009012 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009013 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009014
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009015 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009016 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9017 status = hwDevice->createAudioPatch(patch->num_sources,
9018 patch->sources,
9019 patch->num_sinks,
9020 patch->sinks,
9021 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009022 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009023 char *address;
9024 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
9025 address = audio_device_address_to_parameter(
9026 patch->sources[0].ext.device.type,
9027 patch->sources[0].ext.device.address);
9028 } else {
9029 address = (char *)calloc(1, 1);
9030 }
9031 AudioParameter param = AudioParameter(String8(address));
9032 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07009033 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07009034 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07009035 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07009036 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009037 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07009038 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009039 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009040
jiabinc52b1ff2019-10-31 17:20:42 -07009041 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009042 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009043 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009044 }
Eric Laurent296fb132015-05-01 11:38:42 -07009045
Andy Hungc2b11cb2020-04-22 09:04:01 -07009046 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009047 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009048 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009049 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009050 // also dispatch to active AudioRecords
9051 for (const auto &track : mActiveTracks) {
9052 track->logEndInterval();
9053 track->logBeginInterval(pathSourcesAsString);
9054 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009055 return status;
9056}
9057
9058status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9059{
9060 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009061
jiabinc52b1ff2019-10-31 17:20:42 -07009062 mPatch = audio_patch{};
9063 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009064
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009065 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009066 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9067 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009068 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009069 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07009070 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009071 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07009072 }
9073 return status;
9074}
9075
jiabinc52b1ff2019-10-31 17:20:42 -07009076void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9077{
wendy lin56aa82b2020-12-02 15:19:55 +08009078 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009079 mOutDevices = outDevices;
9080 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9081 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009082 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009083 }
9084}
9085
Eric Laurentec376dc2021-04-08 20:41:22 +02009086int32_t AudioFlinger::RecordThread::getOldestFront_l()
9087{
9088 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009089 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009090 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009091 int32_t oldestFront = mRsmpInRear;
9092 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009093 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009094 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9095 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009096 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009097 if (filled > maxFilled) {
9098 oldestFront = front;
9099 maxFilled = filled;
9100 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009101 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009102 if (maxFilled > mRsmpInFrames) {
9103 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9104 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009105 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009106}
9107
9108void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9109{
9110 if (offset == 0) {
9111 return;
9112 }
9113 for (size_t i = 0; i < mTracks.size(); i++) {
9114 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9115 front = audio_utils::safe_sub_overflow(front, offset);
9116 mTracks[i]->mResamplerBufferProvider->setFront(front);
9117 }
9118}
9119
9120void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9121{
9122 // This is the formula for calculating the temporary buffer size.
9123 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9124 // 1 full output buffer, regardless of the alignment of the available input.
9125 // The value is somewhat arbitrary, and could probably be even larger.
9126 // A larger value should allow more old data to be read after a track calls start(),
9127 // without increasing latency.
9128 //
9129 // Note this is independent of the maximum downsampling ratio permitted for capture.
9130 size_t minRsmpInFrames = mFrameCount * 7;
9131
9132 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9133 // capture history available to another client using the same session ID:
9134 // dimension the resampler input buffer accordingly.
9135
9136 // Get oldest client read position: getOldestFront_l() must be called before altering
9137 // mRsmpInRear, or mRsmpInFrames
9138 int32_t previousFront = getOldestFront_l();
9139 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9140 int32_t previousRear = mRsmpInRear;
9141 mRsmpInRear = 0;
9142
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009143 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9144 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9145 "resizeInputBuffer_l() called with invalid max shared history %d",
9146 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009147 if (maxSharedAudioHistoryMs != 0) {
9148 // resizeInputBuffer_l should never be called with a non zero shared history if the
9149 // buffer was not already allocated
9150 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9151 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9152 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9153 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009154 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009155 return;
9156 }
9157 mRsmpInFrames = rsmpInFrames;
9158 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009159 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009160 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9161 // initialized
9162 if (mRsmpInFrames < minRsmpInFrames) {
9163 mRsmpInFrames = minRsmpInFrames;
9164 }
9165 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9166
9167 // TODO optimize audio capture buffer sizes ...
9168 // Here we calculate the size of the sliding buffer used as a source
9169 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9170 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9171 // be better to have it derived from the pipe depth in the long term.
9172 // The current value is higher than necessary. However it should not add to latency.
9173
9174 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9175 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9176
9177 void *rsmpInBuffer;
9178 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9179 // if posix_memalign fails, will segv here.
9180 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9181
9182 // Copy audio history if any from old buffer before freeing it
9183 if (previousRear != 0) {
9184 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9185 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9186
9187 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9188 previousFront &= previousRsmpInFramesP2 - 1;
9189 size_t part1 = previousRsmpInFramesP2 - previousFront;
9190 if (part1 > (size_t) unread) {
9191 part1 = unread;
9192 }
9193 if (part1 != 0) {
9194 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9195 part1 * mFrameSize);
9196 mRsmpInRear = part1;
9197 part1 = unread - part1;
9198 if (part1 != 0) {
9199 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9200 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9201 mRsmpInRear += part1;
9202 }
9203 }
9204 // Update front for all clients according to new rear
9205 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9206 } else {
9207 mRsmpInRear = 0;
9208 }
9209 free(mRsmpInBuffer);
9210 mRsmpInBuffer = rsmpInBuffer;
9211}
9212
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009213void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009214{
9215 Mutex::Autolock _l(mLock);
9216 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009217 if (record->getSource()) {
9218 mSource = record->getSource();
9219 }
Eric Laurent83b88082014-06-20 18:31:16 -07009220}
9221
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009222void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009223{
9224 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009225 if (mSource == record->getSource()) {
9226 mSource = mInput;
9227 }
Eric Laurent83b88082014-06-20 18:31:16 -07009228 destroyTrack_l(record);
9229}
9230
Mikhail Naganovdc769682018-05-04 15:34:08 -07009231void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009232{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009233 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009234 config->role = AUDIO_PORT_ROLE_SINK;
9235 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9236 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009237 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9238 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9239 config->flags.input = mInput->flags;
9240 }
Eric Laurent83b88082014-06-20 18:31:16 -07009241}
Eric Laurent1c333e22014-05-20 10:48:17 -07009242
Eric Laurent6acd1d42017-01-04 14:23:29 -08009243// ----------------------------------------------------------------------------
9244// Mmap
9245// ----------------------------------------------------------------------------
9246
9247AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9248 : mThread(thread)
9249{
Phil Burk9fabbf82017-08-03 12:02:00 -07009250 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009251}
9252
9253AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9254{
Phil Burk9fabbf82017-08-03 12:02:00 -07009255 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009256}
9257
9258status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9259 struct audio_mmap_buffer_info *info)
9260{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009261 return mThread->createMmapBuffer(minSizeFrames, info);
9262}
9263
9264status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9265{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009266 return mThread->getMmapPosition(position);
9267}
9268
jiabinb7d8c5a2020-08-26 17:24:52 -07009269status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9270 int64_t *timeNanos) {
9271 return mThread->getExternalPosition(position, timeNanos);
9272}
9273
Eric Laurenta54f1282017-07-01 19:39:32 -07009274status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009275 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009276
9277{
jiabind1f1cb62020-03-24 11:57:57 -07009278 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009279}
9280
9281status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9282{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009283 return mThread->stop(handle);
9284}
9285
Eric Laurent18b57012017-02-13 16:23:52 -08009286status_t AudioFlinger::MmapThreadHandle::standby()
9287{
Eric Laurent18b57012017-02-13 16:23:52 -08009288 return mThread->standby();
9289}
9290
Eric Laurent6acd1d42017-01-04 14:23:29 -08009291
9292AudioFlinger::MmapThread::MmapThread(
9293 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009294 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009295 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009296 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009297 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009298 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009299 mActiveTracks(&this->mLocalLog),
9300 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9301 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009302{
Eric Laurent18b57012017-02-13 16:23:52 -08009303 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009304 readHalParameters_l();
9305}
9306
9307AudioFlinger::MmapThread::~MmapThread()
9308{
9309}
9310
9311void AudioFlinger::MmapThread::onFirstRef()
9312{
9313 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9314}
9315
9316void AudioFlinger::MmapThread::disconnect()
9317{
Eric Laurent331679c2018-04-16 17:03:16 -07009318 ActiveTracks<MmapTrack> activeTracks;
9319 {
9320 Mutex::Autolock _l(mLock);
9321 for (const sp<MmapTrack> &t : mActiveTracks) {
9322 activeTracks.add(t);
9323 }
9324 }
9325 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009326 stop(t->portId());
9327 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009328 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009329 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009330 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009331 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009332 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009333 }
9334}
9335
9336
9337void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9338 audio_stream_type_t streamType __unused,
9339 audio_session_t sessionId,
9340 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009341 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009342 audio_port_handle_t portId)
9343{
9344 mAttr = *attr;
9345 mSessionId = sessionId;
9346 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009347 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009348 mPortId = portId;
9349}
9350
9351status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9352 struct audio_mmap_buffer_info *info)
9353{
9354 if (mHalStream == 0) {
9355 return NO_INIT;
9356 }
Eric Laurent18b57012017-02-13 16:23:52 -08009357 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009358 return mHalStream->createMmapBuffer(minSizeFrames, info);
9359}
9360
9361status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9362{
9363 if (mHalStream == 0) {
9364 return NO_INIT;
9365 }
9366 return mHalStream->getMmapPosition(position);
9367}
9368
Eric Laurent331679c2018-04-16 17:03:16 -07009369status_t AudioFlinger::MmapThread::exitStandby()
9370{
9371 status_t ret = mHalStream->start();
9372 if (ret != NO_ERROR) {
9373 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9374 return ret;
9375 }
Andy Hungcf10d742020-04-28 15:38:24 -07009376 if (mStandby) {
9377 mThreadMetrics.logBeginInterval();
9378 mStandby = false;
9379 }
Eric Laurent331679c2018-04-16 17:03:16 -07009380 return NO_ERROR;
9381}
9382
Eric Laurenta54f1282017-07-01 19:39:32 -07009383status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009384 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009385 audio_port_handle_t *handle)
9386{
Eric Laurenta54f1282017-07-01 19:39:32 -07009387 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009388 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009389 if (mHalStream == 0) {
9390 return NO_INIT;
9391 }
9392
9393 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009394
Eric Laurenta54f1282017-07-01 19:39:32 -07009395 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009396 // For the first track, reuse portId and session allocated when the stream was opened.
9397 ret = exitStandby();
9398 if (ret == NO_ERROR) {
9399 acquireWakeLock();
9400 }
9401 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009402 }
9403
9404 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9405
9406 audio_io_handle_t io = mId;
9407 if (isOutput()) {
9408 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9409 config.sample_rate = mSampleRate;
9410 config.channel_mask = mChannelMask;
9411 config.format = mFormat;
9412 audio_stream_type_t stream = streamType();
9413 audio_output_flags_t flags =
9414 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009415 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009416 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009417 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9418 mSessionId,
9419 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009420 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009421 &config,
9422 flags,
9423 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009424 &portId,
9425 &secondaryOutputs);
9426 ALOGD_IF(!secondaryOutputs.empty(),
9427 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009428 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009429 audio_config_base_t config;
9430 config.sample_rate = mSampleRate;
9431 config.channel_mask = mChannelMask;
9432 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009433 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009434 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009435 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009436 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009437 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009438 &config,
9439 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9440 &deviceId,
9441 &portId);
9442 }
9443 // APM should not chose a different input or output stream for the same set of attributes
9444 // and audo configuration
9445 if (ret != NO_ERROR || io != mId) {
9446 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9447 __FUNCTION__, ret, io, mId);
9448 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009449 }
9450
9451 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009452 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009453 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009454 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009455 }
9456
Eric Laurent331679c2018-04-16 17:03:16 -07009457 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009458 // abort if start is rejected by audio policy manager
9459 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009460 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009461 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009462 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009463 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009464 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009465 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009466 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009467 }
Eric Laurent331679c2018-04-16 17:03:16 -07009468 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009469 } else {
9470 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009471 }
9472 return PERMISSION_DENIED;
9473 }
9474
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009475 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009476 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009477 mChannelMask, mSessionId, isOutput(),
9478 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009479 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009480
Eric Laurent4eb58f12018-12-07 16:41:02 -08009481 if (isOutput()) {
9482 // force volume update when a new track is added
9483 mHalVolFloat = -1.0f;
9484 } else if (!track->isSilenced_l()) {
9485 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009486 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009487 t->invalidate();
9488 }
9489 }
9490
9491
Eric Laurent6acd1d42017-01-04 14:23:29 -08009492 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009493 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009494 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009495 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009496 chain->incTrackCnt();
9497 chain->incActiveTrackCnt();
9498 }
9499
Andy Hungc2b11cb2020-04-22 09:04:01 -07009500 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009501 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009502 broadcast_l();
9503
Eric Laurenta54f1282017-07-01 19:39:32 -07009504 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009505
9506 return NO_ERROR;
9507}
9508
9509status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9510{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009511 ALOGV("%s handle %d", __FUNCTION__, handle);
9512
9513 if (mHalStream == 0) {
9514 return NO_INIT;
9515 }
9516
Eric Laurenta54f1282017-07-01 19:39:32 -07009517 if (handle == mPortId) {
9518 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009519 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009520 return NO_ERROR;
9521 }
9522
Eric Laurent331679c2018-04-16 17:03:16 -07009523 Mutex::Autolock _l(mLock);
9524
Eric Laurent6acd1d42017-01-04 14:23:29 -08009525 sp<MmapTrack> track;
9526 for (const sp<MmapTrack> &t : mActiveTracks) {
9527 if (handle == t->portId()) {
9528 track = t;
9529 break;
9530 }
9531 }
9532 if (track == 0) {
9533 return BAD_VALUE;
9534 }
9535
9536 mActiveTracks.remove(track);
9537
Eric Laurent331679c2018-04-16 17:03:16 -07009538 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009539 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009540 AudioSystem::stopOutput(track->portId());
9541 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009542 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009543 AudioSystem::stopInput(track->portId());
9544 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009545 }
Eric Laurent331679c2018-04-16 17:03:16 -07009546 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009547
9548 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9549 if (chain != 0) {
9550 chain->decActiveTrackCnt();
9551 chain->decTrackCnt();
9552 }
9553
9554 broadcast_l();
9555
Eric Laurent6acd1d42017-01-04 14:23:29 -08009556 return NO_ERROR;
9557}
9558
Eric Laurent18b57012017-02-13 16:23:52 -08009559status_t AudioFlinger::MmapThread::standby()
9560{
9561 ALOGV("%s", __FUNCTION__);
9562
9563 if (mHalStream == 0) {
9564 return NO_INIT;
9565 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009566 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009567 return INVALID_OPERATION;
9568 }
9569 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009570 if (!mStandby) {
9571 mThreadMetrics.logEndInterval();
9572 mStandby = true;
9573 }
Eric Laurent18b57012017-02-13 16:23:52 -08009574 releaseWakeLock();
9575 return NO_ERROR;
9576}
9577
Eric Laurent6acd1d42017-01-04 14:23:29 -08009578
9579void AudioFlinger::MmapThread::readHalParameters_l()
9580{
9581 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9582 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9583 mFormat = mHALFormat;
9584 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9585 result = mHalStream->getFrameSize(&mFrameSize);
9586 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009587 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9588 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009589 result = mHalStream->getBufferSize(&mBufferSize);
9590 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9591 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009592
Andy Hungcf10d742020-04-28 15:38:24 -07009593 // TODO: make a readHalParameters call?
9594 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009595 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9596 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9597 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9598 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9599 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9600 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9601 /*
9602 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9603 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9604 (int32_t)mHapticChannelMask)
9605 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9606 (int32_t)mHapticChannelCount)
9607 */
9608 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9609 formatToString(mHALFormat).c_str())
9610 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9611 (int32_t)mFrameCount) // sic - added HAL
9612 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009613}
9614
9615bool AudioFlinger::MmapThread::threadLoop()
9616{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009617 checkSilentMode_l();
9618
9619 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9620
9621 while (!exitPending())
9622 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009623 Vector< sp<EffectChain> > effectChains;
9624
Andy Hung13850be2019-03-14 11:33:09 -07009625 { // under Thread lock
9626 Mutex::Autolock _l(mLock);
9627
Eric Laurent6acd1d42017-01-04 14:23:29 -08009628 if (mSignalPending) {
9629 // A signal was raised while we were unlocked
9630 mSignalPending = false;
9631 } else {
9632 if (mConfigEvents.isEmpty()) {
9633 // we're about to wait, flush the binder command buffer
9634 IPCThreadState::self()->flushCommands();
9635
9636 if (exitPending()) {
9637 break;
9638 }
9639
Eric Laurent6acd1d42017-01-04 14:23:29 -08009640 // wait until we have something to do...
9641 ALOGV("%s going to sleep", myName.string());
9642 mWaitWorkCV.wait(mLock);
9643 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009644
9645 checkSilentMode_l();
9646
9647 continue;
9648 }
9649 }
9650
9651 processConfigEvents_l();
9652
9653 processVolume_l();
9654
9655 checkInvalidTracks_l();
9656
9657 mActiveTracks.updatePowerState(this);
9658
Kevin Rocard069c2712018-03-29 19:09:14 -07009659 updateMetadata_l();
9660
Eric Laurent6acd1d42017-01-04 14:23:29 -08009661 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009662 } // release Thread lock
9663
Eric Laurent6acd1d42017-01-04 14:23:29 -08009664 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009665 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009666 }
Andy Hung13850be2019-03-14 11:33:09 -07009667
9668 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009669 unlockEffectChains(effectChains);
9670 // Effect chains will be actually deleted here if they were removed from
9671 // mEffectChains list during mixing or effects processing
9672 }
9673
9674 threadLoop_exit();
9675
9676 if (!mStandby) {
9677 threadLoop_standby();
9678 mStandby = true;
9679 }
9680
Eric Laurent6acd1d42017-01-04 14:23:29 -08009681 ALOGV("Thread %p type %d exiting", this, mType);
9682 return false;
9683}
9684
9685// checkForNewParameter_l() must be called with ThreadBase::mLock held
9686bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9687 status_t& status)
9688{
9689 AudioParameter param = AudioParameter(keyValuePair);
9690 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009691 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009692 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009693 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009694 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009695 if (sendToHal) {
9696 status = mHalStream->setParameters(keyValuePair);
9697 } else {
9698 status = NO_ERROR;
9699 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009700
9701 return false;
9702}
9703
9704String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9705{
9706 Mutex::Autolock _l(mLock);
9707 String8 out_s8;
9708 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9709 return out_s8;
9710 }
9711 return String8();
9712}
9713
Eric Laurent09f1ed22019-04-24 17:45:17 -07009714void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
9715 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009716 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
9717
9718 desc->mIoHandle = mId;
9719
9720 switch (event) {
9721 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009722 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009723 case AUDIO_INPUT_CONFIG_CHANGED:
9724 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009725 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009726 case AUDIO_OUTPUT_CONFIG_CHANGED:
9727 desc->mPatch = mPatch;
9728 desc->mChannelMask = mChannelMask;
9729 desc->mSamplingRate = mSampleRate;
9730 desc->mFormat = mFormat;
9731 desc->mFrameCount = mFrameCount;
9732 desc->mFrameCountHAL = mFrameCount;
9733 desc->mLatency = 0;
9734 break;
9735
9736 case AUDIO_INPUT_CLOSED:
9737 case AUDIO_OUTPUT_CLOSED:
9738 default:
9739 break;
9740 }
9741 mAudioFlinger->ioConfigChanged(event, desc, pid);
9742}
9743
9744status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9745 audio_patch_handle_t *handle)
9746{
9747 status_t status = NO_ERROR;
9748
9749 // store new device and send to effects
9750 audio_devices_t type = AUDIO_DEVICE_NONE;
9751 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009752 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9753 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9754 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009755 if (isOutput()) {
9756 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009757 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9758 && !mAudioHwDev->supportsAudioPatches(),
9759 "Enumerated device type(%#x) must not be used "
9760 "as it does not support audio patches",
9761 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009762 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009763 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9764 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009765 }
9766 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009767 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009768 } else {
9769 type = patch->sources[0].ext.device.type;
9770 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009771 numDevices = mPatch.num_sources;
9772 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009773 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009774 }
9775
9776 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009777 if (isOutput()) {
9778 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9779 } else {
9780 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9781 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009782 }
9783
jiabinc52b1ff2019-10-31 17:20:42 -07009784 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009785 // store new source and send to effects
9786 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9787 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9788 for (size_t i = 0; i < mEffectChains.size(); i++) {
9789 mEffectChains[i]->setAudioSource_l(mAudioSource);
9790 }
9791 }
9792 }
9793
9794 if (mAudioHwDev->supportsAudioPatches()) {
9795 status = mHalDevice->createAudioPatch(patch->num_sources,
9796 patch->sources,
9797 patch->num_sinks,
9798 patch->sinks,
9799 handle);
9800 } else {
9801 char *address;
9802 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9803 //FIXME: we only support address on first sink with HAL version < 3.0
9804 address = audio_device_address_to_parameter(
9805 patch->sinks[0].ext.device.type,
9806 patch->sinks[0].ext.device.address);
9807 } else {
9808 address = (char *)calloc(1, 1);
9809 }
9810 AudioParameter param = AudioParameter(String8(address));
9811 free(address);
9812 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9813 if (!isOutput()) {
9814 param.addInt(String8(AudioParameter::keyInputSource),
9815 (int)patch->sinks[0].ext.mix.usecase.source);
9816 }
9817 status = mHalStream->setParameters(param.toString());
9818 *handle = AUDIO_PATCH_HANDLE_NONE;
9819 }
9820
jiabinc52b1ff2019-10-31 17:20:42 -07009821 if (numDevices == 0 || mDeviceId != deviceId) {
9822 if (isOutput()) {
9823 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9824 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009825 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009826 } else {
9827 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9828 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9829 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009830 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009831 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009832 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009833 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009834 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009835 }
jiabinc52b1ff2019-10-31 17:20:42 -07009836 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009837 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009838 }
9839 return status;
9840}
9841
9842status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9843{
9844 status_t status = NO_ERROR;
9845
jiabinc52b1ff2019-10-31 17:20:42 -07009846 mPatch = audio_patch{};
9847 mOutDeviceTypeAddrs.clear();
9848 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009849
9850 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9851 supportsAudioPatches : false;
9852
9853 if (supportsAudioPatches) {
9854 status = mHalDevice->releaseAudioPatch(handle);
9855 } else {
9856 AudioParameter param;
9857 param.addInt(String8(AudioParameter::keyRouting), 0);
9858 status = mHalStream->setParameters(param.toString());
9859 }
9860 return status;
9861}
9862
Mikhail Naganovdc769682018-05-04 15:34:08 -07009863void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009864{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009865 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009866 if (isOutput()) {
9867 config->role = AUDIO_PORT_ROLE_SOURCE;
9868 config->ext.mix.hw_module = mAudioHwDev->handle();
9869 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9870 } else {
9871 config->role = AUDIO_PORT_ROLE_SINK;
9872 config->ext.mix.hw_module = mAudioHwDev->handle();
9873 config->ext.mix.usecase.source = mAudioSource;
9874 }
9875}
9876
9877status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9878{
9879 audio_session_t session = chain->sessionId();
9880
9881 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9882 // Attach all tracks with same session ID to this chain.
9883 // indicate all active tracks in the chain
9884 for (const sp<MmapTrack> &track : mActiveTracks) {
9885 if (session == track->sessionId()) {
9886 chain->incTrackCnt();
9887 chain->incActiveTrackCnt();
9888 }
9889 }
9890
9891 chain->setThread(this);
9892 chain->setInBuffer(nullptr);
9893 chain->setOutBuffer(nullptr);
9894 chain->syncHalEffectsState();
9895
9896 mEffectChains.add(chain);
9897 checkSuspendOnAddEffectChain_l(chain);
9898 return NO_ERROR;
9899}
9900
9901size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9902{
9903 audio_session_t session = chain->sessionId();
9904
9905 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9906
9907 for (size_t i = 0; i < mEffectChains.size(); i++) {
9908 if (chain == mEffectChains[i]) {
9909 mEffectChains.removeAt(i);
9910 // detach all active tracks from the chain
9911 // detach all tracks with same session ID from this chain
9912 for (const sp<MmapTrack> &track : mActiveTracks) {
9913 if (session == track->sessionId()) {
9914 chain->decActiveTrackCnt();
9915 chain->decTrackCnt();
9916 }
9917 }
9918 break;
9919 }
9920 }
9921 return mEffectChains.size();
9922}
9923
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924void AudioFlinger::MmapThread::threadLoop_standby()
9925{
9926 mHalStream->standby();
9927}
9928
9929void AudioFlinger::MmapThread::threadLoop_exit()
9930{
Phil Burk7dce7282017-09-27 13:51:41 -07009931 // Do not call callback->onTearDown() because it is redundant for thread exit
9932 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009933}
9934
9935status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9936{
9937 return BAD_VALUE;
9938}
9939
9940bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9941{
9942 return false;
9943}
9944
9945status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9946 const effect_descriptor_t *desc, audio_session_t sessionId)
9947{
9948 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009949 if (audio_is_global_session(sessionId)) {
9950 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009951 desc->name, mThreadName);
9952 return BAD_VALUE;
9953 }
9954
9955 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9956 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9957 desc->name);
9958 return BAD_VALUE;
9959 }
9960 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009961 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9962 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963 return BAD_VALUE;
9964 }
9965
9966 // Only allow effects without processing load or latency
9967 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9968 return BAD_VALUE;
9969 }
9970
jiabineb3bda02020-06-30 14:07:03 -07009971 if (EffectModule::isHapticGenerator(&desc->type)) {
9972 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9973 return BAD_VALUE;
9974 }
9975
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009977}
9978
9979void AudioFlinger::MmapThread::checkInvalidTracks_l()
9980{
9981 for (const sp<MmapTrack> &track : mActiveTracks) {
9982 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009983 sp<MmapStreamCallback> callback = mCallback.promote();
9984 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009985 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009986 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009987 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009988 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9989 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9990 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009991 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009992 }
9993 }
9994}
9995
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009996void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009997{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009998 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9999 mAttr.content_type, mAttr.usage, mAttr.source);
10000 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010001 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010002 dprintf(fd, " No active clients\n");
10003 }
10004}
10005
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010006void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010007{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010008 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010010 dprintf(fd, " %zu Tracks\n", numtracks);
10011 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010012 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010013 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010014 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010015 for (size_t i = 0; i < numtracks ; ++i) {
10016 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010017 result.append(prefix);
10018 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010019 }
10020 } else {
10021 dprintf(fd, "\n");
10022 }
10023 write(fd, result.string(), result.size());
10024}
10025
10026AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10027 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010028 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010029 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010030 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010031 mStreamVolume(1.0),
10032 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010033 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010034{
10035 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10036 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10037 mMasterVolume = audioFlinger->masterVolume_l();
10038 mMasterMute = audioFlinger->masterMute_l();
10039 if (mAudioHwDev) {
10040 if (mAudioHwDev->canSetMasterVolume()) {
10041 mMasterVolume = 1.0;
10042 }
10043
10044 if (mAudioHwDev->canSetMasterMute()) {
10045 mMasterMute = false;
10046 }
10047 }
10048}
10049
10050void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10051 audio_stream_type_t streamType,
10052 audio_session_t sessionId,
10053 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010054 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 audio_port_handle_t portId)
10056{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010057 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058 mStreamType = streamType;
10059}
10060
10061AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10062{
10063 Mutex::Autolock _l(mLock);
10064 AudioStreamOut *output = mOutput;
10065 mOutput = NULL;
10066 return output;
10067}
10068
10069void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10070{
10071 Mutex::Autolock _l(mLock);
10072 // Don't apply master volume in SW if our HAL can do it for us.
10073 if (mAudioHwDev &&
10074 mAudioHwDev->canSetMasterVolume()) {
10075 mMasterVolume = 1.0;
10076 } else {
10077 mMasterVolume = value;
10078 }
10079}
10080
10081void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10082{
10083 Mutex::Autolock _l(mLock);
10084 // Don't apply master mute in SW if our HAL can do it for us.
10085 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10086 mMasterMute = false;
10087 } else {
10088 mMasterMute = muted;
10089 }
10090}
10091
10092void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10093{
10094 Mutex::Autolock _l(mLock);
10095 if (stream == mStreamType) {
10096 mStreamVolume = value;
10097 broadcast_l();
10098 }
10099}
10100
10101float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10102{
10103 Mutex::Autolock _l(mLock);
10104 if (stream == mStreamType) {
10105 return mStreamVolume;
10106 }
10107 return 0.0f;
10108}
10109
10110void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10111{
10112 Mutex::Autolock _l(mLock);
10113 if (stream == mStreamType) {
10114 mStreamMute= muted;
10115 broadcast_l();
10116 }
10117}
10118
10119void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10120{
10121 Mutex::Autolock _l(mLock);
10122 if (streamType == mStreamType) {
10123 for (const sp<MmapTrack> &track : mActiveTracks) {
10124 track->invalidate();
10125 }
10126 broadcast_l();
10127 }
10128}
10129
10130void AudioFlinger::MmapPlaybackThread::processVolume_l()
10131{
10132 float volume;
10133
10134 if (mMasterMute || mStreamMute) {
10135 volume = 0;
10136 } else {
10137 volume = mMasterVolume * mStreamVolume;
10138 }
10139
10140 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141
10142 // Convert volumes from float to 8.24
10143 uint32_t vol = (uint32_t)(volume * (1 << 24));
10144
10145 // Delegate volume control to effect in track effect chain if needed
10146 // only one effect chain can be present on DirectOutputThread, so if
10147 // there is one, the track is connected to it
10148 if (!mEffectChains.isEmpty()) {
10149 mEffectChains[0]->setVolume_l(&vol, &vol);
10150 volume = (float)vol / (1 << 24);
10151 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010152 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010153 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10154 mHalVolFloat = volume; // HW volume control worked, so update value.
10155 mNoCallbackWarningCount = 0;
10156 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010157 sp<MmapStreamCallback> callback = mCallback.promote();
10158 if (callback != 0) {
10159 int channelCount;
10160 if (isOutput()) {
10161 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10162 } else {
10163 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10164 }
10165 Vector<float> values;
10166 for (int i = 0; i < channelCount; i++) {
10167 values.add(volume);
10168 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010169 mHalVolFloat = volume; // SW volume control worked, so update value.
10170 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010171 mLock.unlock();
10172 callback->onVolumeChanged(mChannelMask, values);
10173 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010175 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10176 ALOGW("Could not set MMAP stream volume: no volume callback!");
10177 mNoCallbackWarningCount++;
10178 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010180 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010181 for (const sp<MmapTrack> &track : mActiveTracks) {
10182 track->setMetadataHasChanged();
10183 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010184 }
10185}
10186
Kevin Rocard069c2712018-03-29 19:09:14 -070010187void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10188{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010189 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10190 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010191 }
10192 StreamOutHalInterface::SourceMetadata metadata;
10193 for (const sp<MmapTrack> &track : mActiveTracks) {
10194 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010195 playback_track_metadata_v7_t trackMetadata;
10196 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010197 .usage = track->attributes().usage,
10198 .content_type = track->attributes().content_type,
10199 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010200 };
10201 trackMetadata.channel_mask = track->channelMask(),
10202 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10203 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010204 }
10205 mOutput->stream->updateSourceMetadata(metadata);
10206}
10207
Eric Laurent6acd1d42017-01-04 14:23:29 -080010208void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10209{
10210 if (!mMasterMute) {
10211 char value[PROPERTY_VALUE_MAX];
10212 if (property_get("ro.audio.silent", value, "0") > 0) {
10213 char *endptr;
10214 unsigned long ul = strtoul(value, &endptr, 0);
10215 if (*endptr == '\0' && ul != 0) {
10216 ALOGD("Silence is golden");
10217 // The setprop command will not allow a property to be changed after
10218 // the first time it is set, so we don't have to worry about un-muting.
10219 setMasterMute_l(true);
10220 }
10221 }
10222 }
10223}
10224
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010225void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10226{
10227 MmapThread::toAudioPortConfig(config);
10228 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10229 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10230 config->flags.output = mOutput->flags;
10231 }
10232}
10233
jiabinb7d8c5a2020-08-26 17:24:52 -070010234status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10235 int64_t *timeNanos)
10236{
10237 if (mOutput == nullptr) {
10238 return NO_INIT;
10239 }
10240 struct timespec timestamp;
10241 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10242 if (status == NO_ERROR) {
10243 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10244 }
10245 return status;
10246}
10247
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010248void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010249{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010250 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251
Glenn Kastend3bb6452016-12-05 18:14:37 -080010252 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10253 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10255}
10256
10257AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10258 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010259 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010260 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261 mInput(input)
10262{
10263 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10264 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10265}
10266
Eric Laurent331679c2018-04-16 17:03:16 -070010267status_t AudioFlinger::MmapCaptureThread::exitStandby()
10268{
Phil Burkf054fc32018-12-06 09:45:59 -080010269 {
10270 // mInput might have been cleared by clearInput()
10271 Mutex::Autolock _l(mLock);
10272 if (mInput != nullptr && mInput->stream != nullptr) {
10273 mInput->stream->setGain(1.0f);
10274 }
10275 }
Eric Laurent331679c2018-04-16 17:03:16 -070010276 return MmapThread::exitStandby();
10277}
10278
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10280{
10281 Mutex::Autolock _l(mLock);
10282 AudioStreamIn *input = mInput;
10283 mInput = NULL;
10284 return input;
10285}
Kevin Rocard069c2712018-03-29 19:09:14 -070010286
Eric Laurent331679c2018-04-16 17:03:16 -070010287
10288void AudioFlinger::MmapCaptureThread::processVolume_l()
10289{
10290 bool changed = false;
10291 bool silenced = false;
10292
10293 sp<MmapStreamCallback> callback = mCallback.promote();
10294 if (callback == 0) {
10295 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10296 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10297 mNoCallbackWarningCount++;
10298 }
10299 }
10300
10301 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10302 // track is silenced and unmute otherwise
10303 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10304 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10305 changed = true;
10306 silenced = mActiveTracks[i]->isSilenced_l();
10307 }
10308 }
10309
10310 if (changed) {
10311 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10312 }
10313}
10314
Kevin Rocard069c2712018-03-29 19:09:14 -070010315void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10316{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010317 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10318 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010319 }
10320 StreamInHalInterface::SinkMetadata metadata;
10321 for (const sp<MmapTrack> &track : mActiveTracks) {
10322 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010323 record_track_metadata_v7_t trackMetadata;
10324 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010325 .source = track->attributes().source,
10326 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010327 };
10328 trackMetadata.channel_mask = track->channelMask(),
10329 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10330 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010331 }
10332 mInput->stream->updateSinkMetadata(metadata);
10333}
10334
Eric Laurent5ada82e2019-08-29 17:53:54 -070010335void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010336{
10337 Mutex::Autolock _l(mLock);
10338 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010339 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010340 mActiveTracks[i]->setSilenced_l(silenced);
10341 broadcast_l();
10342 }
10343 }
10344}
10345
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010346void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10347{
10348 MmapThread::toAudioPortConfig(config);
10349 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10350 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10351 config->flags.input = mInput->flags;
10352 }
10353}
10354
jiabinb7d8c5a2020-08-26 17:24:52 -070010355status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10356 uint64_t *position, int64_t *timeNanos)
10357{
10358 if (mInput == nullptr) {
10359 return NO_INIT;
10360 }
10361 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10362}
10363
Glenn Kasten63238ef2015-03-02 15:50:29 -080010364} // namespace android