blob: 43fa781104c9a828e58450e9d87e6ccdd08a4702 [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
Mikhail Naganov88536df2021-07-26 17:30:29 -0700629void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700630 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
Mikhail Naganov88536df2021-07-26 17:30:29 -0700637void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700638 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();
Robert Wu06db0a32021-08-10 19:05:34 +0000647 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100648 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800649
Eric Laurent09f1ed22019-04-24 17:45:17 -0700650 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700651 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Mikhail Naganov83f04272017-02-07 10:45:09 -0800654void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700655{
656 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800657 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700658}
659
Eric Laurent81784c32012-11-19 14:55:58 -0800660// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800661void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
662 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800663{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800664 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700665 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800666}
667
Eric Laurent10351942014-05-08 18:49:52 -0700668// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
669status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800670{
Andy Hung2ddee192015-12-18 17:34:44 -0800671 sp<ConfigEvent> configEvent;
672 AudioParameter param(keyValuePair);
673 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700674 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800675 setMasterMono_l(value != 0);
676 if (param.size() == 1) {
677 return NO_ERROR; // should be a solo parameter - we don't pass down
678 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700679 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800680 configEvent = new SetParameterConfigEvent(param.toString());
681 } else {
682 configEvent = new SetParameterConfigEvent(keyValuePair);
683 }
Eric Laurent10351942014-05-08 18:49:52 -0700684 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700685}
686
Eric Laurent1c333e22014-05-20 10:48:17 -0700687status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
688 const struct audio_patch *patch,
689 audio_patch_handle_t *handle)
690{
691 Mutex::Autolock _l(mLock);
692 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
693 status_t status = sendConfigEvent_l(configEvent);
694 if (status == NO_ERROR) {
695 CreateAudioPatchConfigEventData *data =
696 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
697 *handle = data->mHandle;
698 }
699 return status;
700}
701
702status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
703 const audio_patch_handle_t handle)
704{
705 Mutex::Autolock _l(mLock);
706 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
707 return sendConfigEvent_l(configEvent);
708}
709
jiabinc52b1ff2019-10-31 17:20:42 -0700710status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
711 const DeviceDescriptorBaseVector& outDevices)
712{
713 if (type() != RECORD) {
714 // The update out device operation is only for record thread.
715 return INVALID_OPERATION;
716 }
717 Mutex::Autolock _l(mLock);
718 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
719 return sendConfigEvent_l(configEvent);
720}
721
Eric Laurentec376dc2021-04-08 20:41:22 +0200722void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
723{
724 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
725 sp<ConfigEvent> configEvent =
726 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
727 sendConfigEvent_l(configEvent);
728}
Eric Laurent1c333e22014-05-20 10:48:17 -0700729
Eric Laurentb3f315a2021-07-13 15:09:05 +0200730void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
731{
732 Mutex::Autolock _l(mLock);
733 sendCheckOutputStageEffectsEvent_l();
734}
735
736void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
737{
738 sp<ConfigEvent> configEvent =
739 (ConfigEvent *)new CheckOutputStageEffectsEvent();
740 sendConfigEvent_l(configEvent);
741}
742
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700743// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700744void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700745{
Eric Laurent10351942014-05-08 18:49:52 -0700746 bool configChanged = false;
747
Eric Laurent81784c32012-11-19 14:55:58 -0800748 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700749 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700750 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800751 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700752 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700753 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700754 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
755 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800756 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700757 true /*asynchronous*/);
758 if (err != 0) {
759 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700760 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700761 }
762 } break;
763 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700764 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700765 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700766 } break;
767 case CFG_EVENT_SET_PARAMETER: {
768 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
769 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
770 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700771 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
772 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700773 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700774 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700775 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700776 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700777 CreateAudioPatchConfigEventData *data =
778 (CreateAudioPatchConfigEventData *)event->mData.get();
779 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700780 const DeviceTypeSet newDevices = getDeviceTypes();
781 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
782 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
783 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700784 } break;
785 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700786 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700787 ReleaseAudioPatchConfigEventData *data =
788 (ReleaseAudioPatchConfigEventData *)event->mData.get();
789 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700790 const DeviceTypeSet newDevices = getDeviceTypes();
791 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
792 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
793 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
794 } break;
795 case CFG_EVENT_UPDATE_OUT_DEVICE: {
796 UpdateOutDevicesConfigEventData *data =
797 (UpdateOutDevicesConfigEventData *)event->mData.get();
798 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200800 case CFG_EVENT_RESIZE_BUFFER: {
801 ResizeBufferConfigEventData *data =
802 (ResizeBufferConfigEventData *)event->mData.get();
803 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
804 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200805
806 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
807 setCheckOutputStageEffects();
808 } break;
809
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700810 default:
Eric Laurent10351942014-05-08 18:49:52 -0700811 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700812 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800813 }
Eric Laurent10351942014-05-08 18:49:52 -0700814 {
815 Mutex::Autolock _l(event->mLock);
816 if (event->mWaitStatus) {
817 event->mWaitStatus = false;
818 event->mCond.signal();
819 }
820 }
821 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
822 }
823
824 if (configChanged) {
825 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800826 }
Eric Laurent81784c32012-11-19 14:55:58 -0800827}
828
Marco Nelissenb2208842014-02-07 14:00:50 -0800829String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
830 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700831 const audio_channel_representation_t representation =
832 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700833
834 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800835 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700836 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
837 if (output) {
838 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
839 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
840 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700841 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700842 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
843 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
844 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
845 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
846 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
847 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
848 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
849 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
850 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
851 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
852 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
853 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700854 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
855 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
856 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
857 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
858 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
859 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
860 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700861 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700862 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
863 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700864 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
865 } else {
866 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
867 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
868 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
869 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
870 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
871 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
872 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
873 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
874 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
875 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
876 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
877 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700878 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
879 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
880 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700881 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700882 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
883 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700884 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
885 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
886 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
887 }
888 const int len = s.length();
889 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700890 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700891 s.unlockBuffer(len - 2); // remove trailing ", "
892 }
893 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800894 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700895 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
896 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
897 return s;
898 default:
899 s.appendFormat("unknown mask, representation:%d bits:%#x",
900 representation, audio_channel_mask_get_bits(mask));
901 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800902 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800903}
904
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700905void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800906{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800907 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
908 this, mThreadName, getTid(), type(), threadTypeToString(type()));
909
Eric Laurent81784c32012-11-19 14:55:58 -0800910 bool locked = AudioFlinger::dumpTryLock(mLock);
911 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800912 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800913 }
914
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700915 dumpBase_l(fd, args);
916 dumpInternals_l(fd, args);
917 dumpTracks_l(fd, args);
918 dumpEffectChains_l(fd, args);
919
920 if (locked) {
921 mLock.unlock();
922 }
923
924 dprintf(fd, " Local log:\n");
925 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
926}
927
928void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
929{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700930 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700931 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700932 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700933 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700934 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700935 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700936 dprintf(fd, " Channel count: %u\n", mChannelCount);
937 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800938 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700939 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700940 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700941 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800942 size_t numConfig = mConfigEvents.size();
943 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700944 const size_t SIZE = 256;
945 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800946 for (size_t i = 0; i < numConfig; i++) {
947 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800949 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700950 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800951 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
Andy Hung293558a2017-03-21 12:19:20 -0700954 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700955 dprintf(fd, " Output devices: %s (%s)\n",
956 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
957 dprintf(fd, " Input device: %#x (%s)\n",
958 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800959 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800960
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700961 // Dump timestamp statistics for the Thread types that support it.
962 if (mType == RECORD
963 || mType == MIXER
964 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700965 || mType == DIRECT
966 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700967 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700968 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700969 }
970
Andy Hung446f4df2019-02-21 12:26:41 -0800971 if (mLastIoBeginNs > 0) { // MMAP may not set this
972 dprintf(fd, " Last %s occurred (msecs): %lld\n",
973 isOutput() ? "write" : "read",
974 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
975 }
976
977 if (mProcessTimeMs.getN() > 0) {
978 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
979 }
980
981 if (mIoJitterMs.getN() > 0) {
982 dprintf(fd, " Hal %s jitter ms stats: %s\n",
983 isOutput() ? "write" : "read",
984 mIoJitterMs.toString().c_str());
985 }
986
Andy Hunge6c37112019-02-26 17:38:10 -0800987 if (mLatencyMs.getN() > 0) {
988 dprintf(fd, " Threadloop %s latency stats: %s\n",
989 isOutput() ? "write" : "read",
990 mLatencyMs.toString().c_str());
991 }
Robert Wu06db0a32021-08-10 19:05:34 +0000992
993 if (mMonopipePipeDepthStats.getN() > 0) {
994 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
995 isOutput() ? "write" : "read",
996 mMonopipePipeDepthStats.toString().c_str());
997 }
Eric Laurent81784c32012-11-19 14:55:58 -0800998}
999
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001000void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001001{
1002 const size_t SIZE = 256;
1003 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001004
Marco Nelissenb2208842014-02-07 14:00:50 -08001005 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001006 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001007 write(fd, buffer, strlen(buffer));
1008
Marco Nelissenb2208842014-02-07 14:00:50 -08001009 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001010 sp<EffectChain> chain = mEffectChains[i];
1011 if (chain != 0) {
1012 chain->dump(fd, args);
1013 }
1014 }
1015}
1016
Andy Hungdae27702016-10-31 14:01:16 -07001017void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
1019 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001020 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001021}
1022
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001023String16 AudioFlinger::ThreadBase::getWakeLockTag()
1024{
1025 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001026 case MIXER:
1027 return String16("AudioMix");
1028 case DIRECT:
1029 return String16("AudioDirectOut");
1030 case DUPLICATING:
1031 return String16("AudioDup");
1032 case RECORD:
1033 return String16("AudioIn");
1034 case OFFLOAD:
1035 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001036 case MMAP_PLAYBACK:
1037 return String16("MmapPlayback");
1038 case MMAP_CAPTURE:
1039 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001040 case SPATIALIZER:
1041 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001042 default:
1043 ALOG_ASSERT(false);
1044 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001045 }
1046}
1047
Andy Hungdae27702016-10-31 14:01:16 -07001048void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001049{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001050 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (mPowerManager != 0) {
1052 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001053 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001054 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1055 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001056 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001057 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001058 {} /* workSource */,
1059 {} /* historyTag */);
1060 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001061 mWakeLockToken = binder;
1062 }
Chris Ye6597d732020-02-28 22:38:25 -08001063 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001064 }
Wei Jia3f273d12015-11-24 09:06:49 -08001065
Andy Hung3f0c9022016-01-15 17:49:46 -08001066 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001067 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1068 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001069}
1070
1071void AudioFlinger::ThreadBase::releaseWakeLock()
1072{
1073 Mutex::Autolock _l(mLock);
1074 releaseWakeLock_l();
1075}
1076
1077void AudioFlinger::ThreadBase::releaseWakeLock_l()
1078{
Andy Hung3f0c9022016-01-15 17:49:46 -08001079 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001080 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001081 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001082 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001083 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001084 }
1085 mWakeLockToken.clear();
1086 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001087}
1088
1089void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001090 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001091 // use checkService() to avoid blocking if power service is not up yet
1092 sp<IBinder> binder =
1093 defaultServiceManager()->checkService(String16("power"));
1094 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001095 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001097 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001098 binder->linkToDeath(mDeathRecipient);
1099 }
1100 }
1101}
1102
Andy Hungd01b0f12016-11-07 16:10:30 -08001103void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001105
1106#if !LOG_NDEBUG
1107 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001108 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001109 s << uid << " ";
1110 }
1111 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1112#endif
1113
Andy Hung438e7572015-12-14 15:51:17 -08001114 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1115 if (mSystemReady) {
1116 ALOGE("no wake lock to update, but system ready!");
1117 } else {
1118 ALOGW("no wake lock to update, system not ready yet");
1119 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001120 return;
1121 }
1122 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001123 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001124 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1125 mWakeLockToken, uidsAsInt);
1126 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001127 }
1128}
1129
Eric Laurent81784c32012-11-19 14:55:58 -08001130void AudioFlinger::ThreadBase::clearPowerManager()
1131{
1132 Mutex::Autolock _l(mLock);
1133 releaseWakeLock_l();
1134 mPowerManager.clear();
1135}
1136
jiabinc52b1ff2019-10-31 17:20:42 -07001137void AudioFlinger::ThreadBase::updateOutDevices(
1138 const DeviceDescriptorBaseVector& outDevices __unused)
1139{
1140 ALOGE("%s should only be called in RecordThread", __func__);
1141}
1142
Eric Laurentec376dc2021-04-08 20:41:22 +02001143void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1144{
1145 ALOGE("%s should only be called in RecordThread", __func__);
1146}
1147
Glenn Kasten0f11b512014-01-31 16:18:54 -08001148void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001149{
1150 sp<ThreadBase> thread = mThread.promote();
1151 if (thread != 0) {
1152 thread->clearPowerManager();
1153 }
1154 ALOGW("power manager service died !!!");
1155}
1156
Eric Laurent81784c32012-11-19 14:55:58 -08001157void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001158 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001159{
1160 sp<EffectChain> chain = getEffectChain_l(sessionId);
1161 if (chain != 0) {
1162 if (type != NULL) {
1163 chain->setEffectSuspended_l(type, suspend);
1164 } else {
1165 chain->setEffectSuspendedAll_l(suspend);
1166 }
1167 }
1168
1169 updateSuspendedSessions_l(type, suspend, sessionId);
1170}
1171
1172void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1173{
1174 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1175 if (index < 0) {
1176 return;
1177 }
1178
1179 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1180 mSuspendedSessions.valueAt(index);
1181
1182 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001183 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001184 for (int j = 0; j < desc->mRefCount; j++) {
1185 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1186 chain->setEffectSuspendedAll_l(true);
1187 } else {
1188 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1189 desc->mType.timeLow);
1190 chain->setEffectSuspended_l(&desc->mType, true);
1191 }
1192 }
1193 }
1194}
1195
1196void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1197 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001198 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
1200 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1201
1202 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1203
1204 if (suspend) {
1205 if (index >= 0) {
1206 sessionEffects = mSuspendedSessions.valueAt(index);
1207 } else {
1208 mSuspendedSessions.add(sessionId, sessionEffects);
1209 }
1210 } else {
1211 if (index < 0) {
1212 return;
1213 }
1214 sessionEffects = mSuspendedSessions.valueAt(index);
1215 }
1216
1217
1218 int key = EffectChain::kKeyForSuspendAll;
1219 if (type != NULL) {
1220 key = type->timeLow;
1221 }
1222 index = sessionEffects.indexOfKey(key);
1223
1224 sp<SuspendedSessionDesc> desc;
1225 if (suspend) {
1226 if (index >= 0) {
1227 desc = sessionEffects.valueAt(index);
1228 } else {
1229 desc = new SuspendedSessionDesc();
1230 if (type != NULL) {
1231 desc->mType = *type;
1232 }
1233 sessionEffects.add(key, desc);
1234 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1235 }
1236 desc->mRefCount++;
1237 } else {
1238 if (index < 0) {
1239 return;
1240 }
1241 desc = sessionEffects.valueAt(index);
1242 if (--desc->mRefCount == 0) {
1243 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1244 sessionEffects.removeItemsAt(index);
1245 if (sessionEffects.isEmpty()) {
1246 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1247 sessionId);
1248 mSuspendedSessions.removeItem(sessionId);
1249 }
1250 }
1251 }
1252 if (!sessionEffects.isEmpty()) {
1253 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1254 }
1255}
1256
Eric Laurent6b446ce2019-12-13 10:56:31 -08001257void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1258 audio_session_t sessionId,
1259 bool threadLocked) {
1260 if (!threadLocked) {
1261 mLock.lock();
1262 }
Eric Laurent81784c32012-11-19 14:55:58 -08001263
Eric Laurent81784c32012-11-19 14:55:58 -08001264 if (mType != RECORD) {
1265 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1266 // another session. This gives the priority to well behaved effect control panels
1267 // and applications not using global effects.
1268 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1269 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001270 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001271 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1272 }
1273 }
1274
Eric Laurent6b446ce2019-12-13 10:56:31 -08001275 if (!threadLocked) {
1276 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001277 }
1278}
1279
Eric Laurent4c415062016-06-17 16:14:16 -07001280// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1281status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1282 const effect_descriptor_t *desc, audio_session_t sessionId)
1283{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001284 // No global output effect sessions on record threads
1285 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1286 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001287 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1288 desc->name, mThreadName);
1289 return BAD_VALUE;
1290 }
1291 // only pre processing effects on record thread
1292 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1293 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1294 desc->name, mThreadName);
1295 return BAD_VALUE;
1296 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001297
1298 // always allow effects without processing load or latency
1299 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1300 return NO_ERROR;
1301 }
1302
Eric Laurent4c415062016-06-17 16:14:16 -07001303 audio_input_flags_t flags = mInput->flags;
1304 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1305 if (flags & AUDIO_INPUT_FLAG_RAW) {
1306 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1307 desc->name, mThreadName);
1308 return BAD_VALUE;
1309 }
1310 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1311 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1312 desc->name, mThreadName);
1313 return BAD_VALUE;
1314 }
1315 }
jiabineb3bda02020-06-30 14:07:03 -07001316
1317 if (EffectModule::isHapticGenerator(&desc->type)) {
1318 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1319 return BAD_VALUE;
1320 }
Eric Laurent4c415062016-06-17 16:14:16 -07001321 return NO_ERROR;
1322}
1323
1324// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1325status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1326 const effect_descriptor_t *desc, audio_session_t sessionId)
1327{
1328 // no preprocessing on playback threads
1329 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001330 ALOGW("%s: pre processing effect %s created on playback"
1331 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001332 return BAD_VALUE;
1333 }
1334
Eric Laurent3e4de772017-07-16 16:55:08 -07001335 // always allow effects without processing load or latency
1336 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1337 return NO_ERROR;
1338 }
1339
jiabineb3bda02020-06-30 14:07:03 -07001340 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1341 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1342 __func__);
1343 return BAD_VALUE;
1344 }
1345
Eric Laurentf690c462021-09-17 14:47:03 +02001346 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1347 && mType != SPATIALIZER) {
1348 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1349 __func__, mType);
1350 return BAD_VALUE;
1351 }
1352
Eric Laurent4c415062016-06-17 16:14:16 -07001353 switch (mType) {
1354 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001355#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001356 // Reject any effect on mixer multichannel sinks.
1357 // TODO: fix both format and multichannel issues with effects.
1358 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001359 ALOGW("%s: effect %s for multichannel(%d) on MIXER thread %s",
1360 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001361 return BAD_VALUE;
1362 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001363#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001364 audio_output_flags_t flags = mOutput->flags;
1365 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1366 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1367 // global effects are applied only to non fast tracks if they are SW
1368 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1369 break;
1370 }
1371 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1372 // only post processing on output stage session
1373 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001374 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1375 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001376 return BAD_VALUE;
1377 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001378 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1379 // only post processing on output stage session
1380 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001381 ALOGW("%s: non post processing effect %s not allowed on device session",
1382 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001383 return BAD_VALUE;
1384 }
Eric Laurent4c415062016-06-17 16:14:16 -07001385 } else {
1386 // no restriction on effects applied on non fast tracks
1387 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1388 break;
1389 }
1390 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001391
Eric Laurent4c415062016-06-17 16:14:16 -07001392 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001393 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001394 return BAD_VALUE;
1395 }
1396 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001397 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1398 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001399 return BAD_VALUE;
1400 }
1401 }
1402 } break;
1403 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001404 // nothing actionable on offload threads, if the effect:
1405 // - is offloadable: the effect can be created
1406 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1407 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001408 break;
1409 case DIRECT:
1410 // Reject any effect on Direct output threads for now, since the format of
1411 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001412 ALOGW("%s: effect %s on DIRECT output thread %s",
1413 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001414 return BAD_VALUE;
1415 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001416#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001417 // Reject any effect on mixer multichannel sinks.
1418 // TODO: fix both format and multichannel issues with effects.
1419 if (mChannelCount != FCC_2) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001420 ALOGW("%s: effect %s for multichannel(%d) on DUPLICATING thread %s",
1421 __func__, desc->name, mChannelCount, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001422 return BAD_VALUE;
1423 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001424#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001425 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001426 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1427 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001428 return BAD_VALUE;
1429 }
1430 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001431 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1432 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001433 return BAD_VALUE;
1434 }
1435 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001436 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1437 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001438 return BAD_VALUE;
1439 }
1440 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001441 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001442 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1443 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1444 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1445 // are supported and added after the spatializer.
1446 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1447 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1448 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001449 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001450 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1451 // only post processing , downmixer or spatializer effects on output stage session
1452 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1453 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1454 break;
1455 }
1456 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1457 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1458 __func__, desc->name);
1459 return BAD_VALUE;
1460 }
1461 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1462 // only post processing on output stage session
1463 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1464 ALOGW("%s: non post processing effect %s not allowed on device session",
1465 __func__, desc->name);
1466 return BAD_VALUE;
1467 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001468 }
1469 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001470 default:
1471 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1472 }
1473
1474 return NO_ERROR;
1475}
1476
Eric Laurent81784c32012-11-19 14:55:58 -08001477// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1478sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1479 const sp<AudioFlinger::Client>& client,
1480 const sp<IEffectClient>& effectClient,
1481 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001482 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001483 effect_descriptor_t *desc,
1484 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001485 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001486 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001487 bool probe,
1488 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 sp<EffectModule> effect;
1491 sp<EffectHandle> handle;
1492 status_t lStatus;
1493 sp<EffectChain> chain;
1494 bool chainCreated = false;
1495 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001496 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001497
1498 lStatus = initCheck();
1499 if (lStatus != NO_ERROR) {
1500 ALOGW("createEffect_l() Audio driver not initialized.");
1501 goto Exit;
1502 }
1503
Eric Laurent81784c32012-11-19 14:55:58 -08001504 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1505
1506 { // scope for mLock
1507 Mutex::Autolock _l(mLock);
1508
Eric Laurent4c415062016-06-17 16:14:16 -07001509 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001510 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001511 goto Exit;
1512 }
1513
Eric Laurent81784c32012-11-19 14:55:58 -08001514 // check for existing effect chain with the requested audio session
1515 chain = getEffectChain_l(sessionId);
1516 if (chain == 0) {
1517 // create a new chain for this session
1518 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1519 chain = new EffectChain(this, sessionId);
1520 addEffectChain_l(chain);
1521 chain->setStrategy(getStrategyForSession_l(sessionId));
1522 chainCreated = true;
1523 } else {
1524 effect = chain->getEffectFromDesc_l(desc);
1525 }
1526
1527 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1528
1529 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001530 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001531 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001532 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001533 if (lStatus != NO_ERROR) {
1534 goto Exit;
1535 }
1536 effectCreated = true;
1537
jiabinc52b1ff2019-10-31 17:20:42 -07001538 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001539 effect->setDevices(outDeviceTypeAddrs());
1540 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001541 effect->setMode(mAudioFlinger->getMode());
1542 effect->setAudioSource(mAudioSource);
1543 }
jiabin1319f5a2021-03-30 22:21:24 +00001544 if (effect->isHapticGenerator()) {
1545 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1546 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001547 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1548 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1549 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001550 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001551 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001552 }
1553 }
Eric Laurent81784c32012-11-19 14:55:58 -08001554 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001555 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001556 lStatus = handle->initCheck();
1557 if (lStatus == OK) {
1558 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001559 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001560 }
Eric Laurent81784c32012-11-19 14:55:58 -08001561 if (enabled != NULL) {
1562 *enabled = (int)effect->isEnabled();
1563 }
1564 }
1565
1566Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001567 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001568 Mutex::Autolock _l(mLock);
1569 if (effectCreated) {
1570 chain->removeEffect_l(effect);
1571 }
Eric Laurent81784c32012-11-19 14:55:58 -08001572 if (chainCreated) {
1573 removeEffectChain_l(chain);
1574 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001575 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001576 }
1577
Glenn Kasten9156ef32013-08-06 15:39:08 -07001578 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001579 return handle;
1580}
1581
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001582void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1583 bool unpinIfLast)
1584{
1585 bool remove = false;
1586 sp<EffectModule> effect;
1587 {
1588 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001589 sp<EffectBase> effectBase = handle->effect().promote();
1590 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001591 return;
1592 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001593 effect = effectBase->asEffectModule();
1594 if (effect == nullptr) {
1595 return;
1596 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001597 // restore suspended effects if the disconnected handle was enabled and the last one.
1598 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1599 if (remove) {
1600 removeEffect_l(effect, true);
1601 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001602 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001603 }
1604 if (remove) {
1605 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001606 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001607 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001608 }
1609 }
1610}
1611
Eric Laurent6b446ce2019-12-13 10:56:31 -08001612void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001613 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001614 Mutex::Autolock _l(mLock);
1615 broadcast_l();
1616 }
1617 if (!effect->isOffloadable()) {
1618 if (mType == ThreadBase::OFFLOAD) {
1619 PlaybackThread *t = (PlaybackThread *)this;
1620 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1621 }
1622 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1623 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1624 }
1625 }
1626}
1627
1628void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001629 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001630 Mutex::Autolock _l(mLock);
1631 broadcast_l();
1632 }
1633}
1634
Glenn Kastend848eb42016-03-08 13:42:11 -08001635sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1636 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001637{
1638 Mutex::Autolock _l(mLock);
1639 return getEffect_l(sessionId, effectId);
1640}
1641
Glenn Kastend848eb42016-03-08 13:42:11 -08001642sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1643 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001644{
1645 sp<EffectChain> chain = getEffectChain_l(sessionId);
1646 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1647}
1648
Eric Laurent6c796322019-04-09 14:13:17 -07001649std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1650{
1651 sp<EffectChain> chain = getEffectChain_l(sessionId);
1652 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1653}
1654
Eric Laurent81784c32012-11-19 14:55:58 -08001655// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1656// PlaybackThread::mLock held
1657status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1658{
1659 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001660 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001661 sp<EffectChain> chain = getEffectChain_l(sessionId);
1662 bool chainCreated = false;
1663
Eric Laurent5baf2af2013-09-12 17:37:00 -07001664 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001665 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001666 this, effect->desc().name, effect->desc().flags);
1667
Eric Laurent81784c32012-11-19 14:55:58 -08001668 if (chain == 0) {
1669 // create a new chain for this session
1670 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1671 chain = new EffectChain(this, sessionId);
1672 addEffectChain_l(chain);
1673 chain->setStrategy(getStrategyForSession_l(sessionId));
1674 chainCreated = true;
1675 }
1676 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1677
1678 if (chain->getEffectFromId_l(effect->id()) != 0) {
1679 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1680 this, effect->desc().name, chain.get());
1681 return BAD_VALUE;
1682 }
1683
Eric Laurent5baf2af2013-09-12 17:37:00 -07001684 effect->setOffloaded(mType == OFFLOAD, mId);
1685
Eric Laurent81784c32012-11-19 14:55:58 -08001686 status_t status = chain->addEffect_l(effect);
1687 if (status != NO_ERROR) {
1688 if (chainCreated) {
1689 removeEffectChain_l(chain);
1690 }
1691 return status;
1692 }
1693
jiabin8f278ee2019-11-11 12:16:27 -08001694 effect->setDevices(outDeviceTypeAddrs());
1695 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001696 effect->setMode(mAudioFlinger->getMode());
1697 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001698
Eric Laurent81784c32012-11-19 14:55:58 -08001699 return NO_ERROR;
1700}
1701
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001702void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001703
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001704 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001705 effect_descriptor_t desc = effect->desc();
1706 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1707 detachAuxEffect_l(effect->id());
1708 }
1709
Andy Hungfda44002021-06-03 17:23:16 -07001710 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001711 if (chain != 0) {
1712 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001713 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001714 removeEffectChain_l(chain);
1715 }
1716 } else {
1717 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1718 }
1719}
1720
1721void AudioFlinger::ThreadBase::lockEffectChains_l(
1722 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1723{
1724 effectChains = mEffectChains;
1725 for (size_t i = 0; i < mEffectChains.size(); i++) {
1726 mEffectChains[i]->lock();
1727 }
1728}
1729
1730void AudioFlinger::ThreadBase::unlockEffectChains(
1731 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1732{
1733 for (size_t i = 0; i < effectChains.size(); i++) {
1734 effectChains[i]->unlock();
1735 }
1736}
1737
Glenn Kastend848eb42016-03-08 13:42:11 -08001738sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001739{
1740 Mutex::Autolock _l(mLock);
1741 return getEffectChain_l(sessionId);
1742}
1743
Glenn Kastend848eb42016-03-08 13:42:11 -08001744sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1745 const
Eric Laurent81784c32012-11-19 14:55:58 -08001746{
1747 size_t size = mEffectChains.size();
1748 for (size_t i = 0; i < size; i++) {
1749 if (mEffectChains[i]->sessionId() == sessionId) {
1750 return mEffectChains[i];
1751 }
1752 }
1753 return 0;
1754}
1755
1756void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1757{
1758 Mutex::Autolock _l(mLock);
1759 size_t size = mEffectChains.size();
1760 for (size_t i = 0; i < size; i++) {
1761 mEffectChains[i]->setMode_l(mode);
1762 }
1763}
1764
Mikhail Naganovdc769682018-05-04 15:34:08 -07001765void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001766{
1767 config->type = AUDIO_PORT_TYPE_MIX;
1768 config->ext.mix.handle = mId;
1769 config->sample_rate = mSampleRate;
1770 config->format = mFormat;
1771 config->channel_mask = mChannelMask;
1772 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1773 AUDIO_PORT_CONFIG_FORMAT;
1774}
1775
Eric Laurent72e3f392015-05-20 14:43:50 -07001776void AudioFlinger::ThreadBase::systemReady()
1777{
1778 Mutex::Autolock _l(mLock);
1779 if (mSystemReady) {
1780 return;
1781 }
1782 mSystemReady = true;
1783
1784 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1785 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1786 }
1787 mPendingConfigEvents.clear();
1788}
1789
Andy Hungdae27702016-10-31 14:01:16 -07001790template <typename T>
1791ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1792 ssize_t index = mActiveTracks.indexOf(track);
1793 if (index >= 0) {
1794 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1795 return index;
1796 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001797 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001798 mActiveTracksGeneration++;
1799 mLatestActiveTrack = track;
1800 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001801 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001802 return mActiveTracks.add(track);
1803}
1804
1805template <typename T>
1806ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1807 ssize_t index = mActiveTracks.remove(track);
1808 if (index < 0) {
1809 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1810 return index;
1811 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001812 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001813 mActiveTracksGeneration++;
1814 --mBatteryCounter[track->uid()].second;
1815 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001816 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001817#ifdef TEE_SINK
1818 track->dumpTee(-1 /* fd */, "_REMOVE");
1819#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001820 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001821 return index;
1822}
1823
1824template <typename T>
1825void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1826 for (const sp<T> &track : mActiveTracks) {
1827 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001828 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001829 }
1830 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001831 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001832 mActiveTracks.clear();
1833 mLatestActiveTrack.clear();
1834 mBatteryCounter.clear();
1835}
1836
1837template <typename T>
1838void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1839 sp<ThreadBase> thread, bool force) {
1840 // Updates ActiveTracks client uids to the thread wakelock.
1841 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1842 thread->updateWakeLockUids_l(getWakeLockUids());
1843 mLastActiveTracksGeneration = mActiveTracksGeneration;
1844 }
1845
1846 // Updates BatteryNotifier uids
1847 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1848 const uid_t uid = it->first;
1849 ssize_t &previous = it->second.first;
1850 ssize_t &current = it->second.second;
1851 if (current > 0) {
1852 if (previous == 0) {
1853 BatteryNotifier::getInstance().noteStartAudio(uid);
1854 }
1855 previous = current;
1856 ++it;
1857 } else if (current == 0) {
1858 if (previous > 0) {
1859 BatteryNotifier::getInstance().noteStopAudio(uid);
1860 }
1861 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1862 } else /* (current < 0) */ {
1863 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1864 }
1865 }
1866}
Eric Laurent83b88082014-06-20 18:31:16 -07001867
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001868template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001869bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001870 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001871 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001872
1873 for (const sp<T> &track : mActiveTracks) {
1874 // Do not short-circuit as all hasChanged states must be reset
1875 // as all the metadata are going to be sent
1876 hasChanged |= track->readAndClearHasChanged();
1877 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001878 return hasChanged;
1879}
1880
1881template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001882void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1883 const char *funcName, const sp<T> &track) const {
1884 if (mLocalLog != nullptr) {
1885 String8 result;
1886 track->appendDump(result, false /* active */);
1887 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1888 }
1889}
1890
Eric Laurent6acd1d42017-01-04 14:23:29 -08001891void AudioFlinger::ThreadBase::broadcast_l()
1892{
1893 // Thread could be blocked waiting for async
1894 // so signal it to handle state changes immediately
1895 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1896 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1897 mSignalPending = true;
1898 mWaitWorkCV.broadcast();
1899}
1900
Andy Hungd0979812019-02-21 15:51:44 -08001901// Call only from threadLoop() or when it is idle.
1902// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1903void AudioFlinger::ThreadBase::sendStatistics(bool force)
1904{
1905 // Do not log if we have no stats.
1906 // We choose the timestamp verifier because it is the most likely item to be present.
1907 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1908 if (nstats == 0) {
1909 return;
1910 }
1911
1912 // Don't log more frequently than once per 12 hours.
1913 // We use BOOTTIME to include suspend time.
1914 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1915 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1916 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1917 return;
1918 }
1919
1920 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1921 mLastRecordedTimeNs = timeNs;
1922
Ray Essickf27e9872019-12-07 06:28:46 -08001923 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001924
1925#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1926
1927 // thread configuration
1928 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1929 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1930 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1931 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1932 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1933 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1934 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001935 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1936 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001937
1938 // thread statistics
1939 if (mIoJitterMs.getN() > 0) {
1940 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1941 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1942 }
1943 if (mProcessTimeMs.getN() > 0) {
1944 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1945 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1946 }
1947 const auto tsjitter = mTimestampVerifier.getJitterMs();
1948 if (tsjitter.getN() > 0) {
1949 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1950 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1951 }
1952 if (mLatencyMs.getN() > 0) {
1953 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1954 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1955 }
Robert Wu06db0a32021-08-10 19:05:34 +00001956 if (mMonopipePipeDepthStats.getN() > 0) {
1957 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1958 mMonopipePipeDepthStats.getMean());
1959 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1960 mMonopipePipeDepthStats.getStdDev());
1961 }
Andy Hungd0979812019-02-21 15:51:44 -08001962
1963 item->selfrecord();
1964}
1965
Eric Laurentd66d7a12021-07-13 13:35:32 +02001966product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1967{
1968 if (!mAudioFlinger->isAudioPolicyReady()) {
1969 return PRODUCT_STRATEGY_NONE;
1970 }
1971 return AudioSystem::getStrategyForStream(stream);
1972}
1973
Eric Laurent81784c32012-11-19 14:55:58 -08001974// ----------------------------------------------------------------------------
1975// Playback
1976// ----------------------------------------------------------------------------
1977
1978AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1979 AudioStreamOut* output,
1980 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001981 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001982 bool systemReady,
1983 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07001984 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001985 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001986 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08001987 mMixerBuffer(NULL),
1988 mMixerBufferSize(0),
1989 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1990 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001991 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08001992 mEffectBuffer(NULL),
1993 mEffectBufferSize(0),
1994 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1995 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001996 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001997 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001998 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001999 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002000 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002001 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002002 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002003 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002004 mMixerStatus(MIXER_IDLE),
2005 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002006 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002007 mBytesRemaining(0),
2008 mCurrentWriteLength(0),
2009 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002010 mWriteAckSequence(0),
2011 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002012 mScreenState(AudioFlinger::mScreenState),
2013 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002014 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002015 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002016 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
2017 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08002018{
Glenn Kastend7dca052015-03-05 16:05:54 -08002019 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2020 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002021
2022 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2023 // it would be safer to explicitly pass initial masterVolume/masterMute as
2024 // parameter.
2025 //
2026 // If the HAL we are using has support for master volume or master mute,
2027 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2028 // and the mute set to false).
2029 mMasterVolume = audioFlinger->masterVolume_l();
2030 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002031 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002032 if (mOutput->audioHwDev->canSetMasterVolume()) {
2033 mMasterVolume = 1.0;
2034 }
2035
2036 if (mOutput->audioHwDev->canSetMasterMute()) {
2037 mMasterMute = false;
2038 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002039 mIsMsdDevice = strcmp(
2040 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002041 }
2042
Eric Laurentf1f22e72021-07-13 14:04:14 +02002043 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2044 mMixerChannelMask = mixerConfig->channel_mask;
2045 }
2046
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002047 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002048
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002049 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002050 && mMixerChannelMask != mChannelMask) {
2051 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2052 mChannelMask, mMixerChannelMask);
2053 }
2054
Andy Hungc8fddf32018-08-08 18:32:37 -07002055 // TODO: We may also match on address as well as device type for
2056 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002057 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002058 // TODO: This property should be ensure that only contains one single device type.
2059 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2060 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002061 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2062 : AUDIO_DEVICE_NONE));
2063 }
2064
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002065 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2066 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002067 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002068 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2069 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002070 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002071 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2072 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002073 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2074 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002075}
2076
2077AudioFlinger::PlaybackThread::~PlaybackThread()
2078{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002079 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002080 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002081 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002082 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002083 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002084}
2085
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002086// Thread virtuals
2087
2088void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002089{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002090 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002091 ALOGE("The stream is not open yet"); // This should not happen.
2092 } else {
2093 // setEventCallback will need a strong pointer as a parameter. Calling it
2094 // here instead of constructor of PlaybackThread so that the onFirstRef
2095 // callback would not be made on an incompletely constructed object.
2096 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002097 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002098 }
2099 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002100 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002101}
2102
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002103// ThreadBase virtuals
2104void AudioFlinger::PlaybackThread::preExit()
2105{
2106 ALOGV(" preExit()");
2107 // FIXME this is using hard-coded strings but in the future, this functionality will be
2108 // converted to use audio HAL extensions required to support tunneling
2109 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2110 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2111}
2112
2113void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002114{
Eric Laurent81784c32012-11-19 14:55:58 -08002115 String8 result;
2116
Marco Nelissenb2208842014-02-07 14:00:50 -08002117 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002118 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2119 const stream_type_t *st = &mStreamTypes[i];
2120 if (i > 0) {
2121 result.appendFormat(", ");
2122 }
2123 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2124 if (st->mute) {
2125 result.append("M");
2126 }
2127 }
2128 result.append("\n");
2129 write(fd, result.string(), result.length());
2130 result.clear();
2131
Eric Laurent81784c32012-11-19 14:55:58 -08002132 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2133 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002134 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002135 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002136
2137 size_t numtracks = mTracks.size();
2138 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002139 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002140 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002141 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002142 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002143 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002144 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002145 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002146 for (size_t i = 0; i < numtracks; ++i) {
2147 sp<Track> track = mTracks[i];
2148 if (track != 0) {
2149 bool active = mActiveTracks.indexOf(track) >= 0;
2150 if (active) {
2151 numactiveseen++;
2152 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002153 result.append(prefix);
2154 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002155 }
2156 }
2157 } else {
2158 result.append("\n");
2159 }
2160 if (numactiveseen != numactive) {
2161 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002162 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002163 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002164 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002165 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002166 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002167 sp<Track> track = mActiveTracks[i];
2168 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002169 result.append(prefix);
2170 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002171 }
2172 }
2173 }
2174
2175 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002176}
2177
Andy Hung61589a42021-06-16 09:37:53 -07002178void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002179{
Andy Hung04cb8f72020-03-20 13:44:33 -07002180 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002181 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002182 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2183 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002184 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2185 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2186 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2187 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002188 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002189 dprintf(fd, " Total writes: %d\n", mNumWrites);
2190 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2191 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2192 dprintf(fd, " Suspend count: %d\n", mSuspended);
2193 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2194 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2195 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2196 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002197 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002198 AudioStreamOut *output = mOutput;
2199 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002200 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002201 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002202 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2203 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2204 if (mPipeSink.get() != nullptr) {
2205 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2206 }
2207 if (output != nullptr) {
2208 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002209 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002210 }
Eric Laurent81784c32012-11-19 14:55:58 -08002211}
2212
Eric Laurent81784c32012-11-19 14:55:58 -08002213// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2214sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2215 const sp<AudioFlinger::Client>& client,
2216 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002217 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002218 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002219 audio_format_t format,
2220 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002221 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002222 size_t *pNotificationFrameCount,
2223 uint32_t notificationsPerBuffer,
2224 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002225 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002226 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002227 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002228 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002229 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002230 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002231 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002232 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002233 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002234{
Glenn Kasten74935e42013-12-19 08:56:45 -08002235 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002236 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002237 sp<Track> track;
2238 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002239 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002240 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002241 uint32_t sampleRate;
2242
2243 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2244 lStatus = BAD_VALUE;
2245 goto Exit;
2246 }
Eric Laurent21da6472017-11-09 16:29:26 -08002247
2248 if (*pSampleRate == 0) {
2249 *pSampleRate = mSampleRate;
2250 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002251 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002252
2253 // special case for FAST flag considered OK if fast mixer is present
2254 if (hasFastMixer()) {
2255 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2256 }
2257
2258 // Check if requested flags are compatible with output stream flags
2259 if ((*flags & outputFlags) != *flags) {
2260 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2261 *flags, outputFlags);
2262 *flags = (audio_output_flags_t)(*flags & outputFlags);
2263 }
Eric Laurent81784c32012-11-19 14:55:58 -08002264
Eric Laurent81784c32012-11-19 14:55:58 -08002265 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002266 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002267 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002268 // PCM data
2269 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002270 // TODO: extract as a data library function that checks that a computationally
2271 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002272 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002273 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2274 (channelMask == AUDIO_CHANNEL_OUT_MONO
2275 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002276 // hardware sample rate
2277 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002278 // normal mixer has an associated fast mixer
2279 hasFastMixer() &&
2280 // there are sufficient fast track slots available
2281 (mFastTrackAvailMask != 0)
2282 // FIXME test that MixerThread for this fast track has a capable output HAL
2283 // FIXME add a permission test also?
2284 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002285 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2286 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002287 // read the fast track multiplier property the first time it is needed
2288 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2289 if (ok != 0) {
2290 ALOGE("%s pthread_once failed: %d", __func__, ok);
2291 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002292 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002293 }
Eric Laurent4c415062016-06-17 16:14:16 -07002294
2295 // check compatibility with audio effects.
2296 { // scope for mLock
2297 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002298 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002299 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002300 AUDIO_SESSION_OUTPUT_STAGE,
2301 AUDIO_SESSION_OUTPUT_MIX,
2302 sessionId,
2303 }) {
2304 sp<EffectChain> chain = getEffectChain_l(session);
2305 if (chain.get() != nullptr) {
2306 audio_output_flags_t old = *flags;
2307 chain->checkOutputFlagCompatibility(flags);
2308 if (old != *flags) {
2309 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2310 (int)session, (int)old, (int)*flags);
2311 }
Eric Laurent4c415062016-06-17 16:14:16 -07002312 }
2313 }
2314 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002315 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002316 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2317 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002318 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002319 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002320 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002321 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002322 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002323 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002324 audio_is_linear_pcm(format), channelMask, sampleRate,
2325 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002326 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002327 }
2328 }
Eric Laurent21da6472017-11-09 16:29:26 -08002329
2330 if (!audio_has_proportional_frames(format)) {
2331 if (sharedBuffer != 0) {
2332 // Same comment as below about ignoring frameCount parameter for set()
2333 frameCount = sharedBuffer->size();
2334 } else if (frameCount == 0) {
2335 frameCount = mNormalFrameCount;
2336 }
2337 if (notificationFrameCount != frameCount) {
2338 notificationFrameCount = frameCount;
2339 }
2340 } else if (sharedBuffer != 0) {
2341 // FIXME: Ensure client side memory buffers need
2342 // not have additional alignment beyond sample
2343 // (e.g. 16 bit stereo accessed as 32 bit frame).
2344 size_t alignment = audio_bytes_per_sample(format);
2345 if (alignment & 1) {
2346 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2347 alignment = 1;
2348 }
2349 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2350 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2351 if (channelCount > 1) {
2352 // More than 2 channels does not require stronger alignment than stereo
2353 alignment <<= 1;
2354 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002355 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002356 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002357 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002358 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002359 goto Exit;
2360 }
Eric Laurent21da6472017-11-09 16:29:26 -08002361
2362 // When initializing a shared buffer AudioTrack via constructors,
2363 // there's no frameCount parameter.
2364 // But when initializing a shared buffer AudioTrack via set(),
2365 // there _is_ a frameCount parameter. We silently ignore it.
2366 frameCount = sharedBuffer->size() / frameSize;
2367 } else {
2368 size_t minFrameCount = 0;
2369 // For fast tracks we try to respect the application's request for notifications per buffer.
2370 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2371 if (notificationsPerBuffer > 0) {
2372 // Avoid possible arithmetic overflow during multiplication.
2373 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2374 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2375 notificationsPerBuffer, mFrameCount);
2376 } else {
2377 minFrameCount = mFrameCount * notificationsPerBuffer;
2378 }
2379 }
2380 } else {
2381 // For normal PCM streaming tracks, update minimum frame count.
2382 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2383 // cover audio hardware latency.
2384 // This is probably too conservative, but legacy application code may depend on it.
2385 // If you change this calculation, also review the start threshold which is related.
2386 uint32_t latencyMs = latency_l();
2387 if (latencyMs == 0) {
2388 ALOGE("Error when retrieving output stream latency");
2389 lStatus = UNKNOWN_ERROR;
2390 goto Exit;
2391 }
2392
2393 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2394 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2395
Eric Laurent81784c32012-11-19 14:55:58 -08002396 }
Eric Laurent21da6472017-11-09 16:29:26 -08002397 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002398 frameCount = minFrameCount;
2399 }
Eric Laurent81784c32012-11-19 14:55:58 -08002400 }
Eric Laurent21da6472017-11-09 16:29:26 -08002401
2402 // Make sure that application is notified with sufficient margin before underrun.
2403 // The client can divide the AudioTrack buffer into sub-buffers,
2404 // and expresses its desire to server as the notification frame count.
2405 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2406 size_t maxNotificationFrames;
2407 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2408 // notify every HAL buffer, regardless of the size of the track buffer
2409 maxNotificationFrames = mFrameCount;
2410 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002411 // Triple buffer the notification period for a triple buffered mixer period;
2412 // otherwise, double buffering for the notification period is fine.
2413 //
2414 // TODO: This should be moved to AudioTrack to modify the notification period
2415 // on AudioTrack::setBufferSizeInFrames() changes.
2416 const int nBuffering =
2417 (uint64_t{frameCount} * mSampleRate)
2418 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2419
Eric Laurent21da6472017-11-09 16:29:26 -08002420 maxNotificationFrames = frameCount / nBuffering;
2421 // If client requested a fast track but this was denied, then use the smaller maximum.
2422 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2423 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2424 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2425 maxNotificationFrames = maxNotificationFramesFastDenied;
2426 }
2427 }
2428 }
2429 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2430 if (notificationFrameCount == 0) {
2431 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2432 maxNotificationFrames, frameCount);
2433 } else {
2434 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2435 notificationFrameCount, maxNotificationFrames, frameCount);
2436 }
2437 notificationFrameCount = maxNotificationFrames;
2438 }
2439 }
2440
Glenn Kasten74935e42013-12-19 08:56:45 -08002441 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002442 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002443
Glenn Kastenc3df8382014-03-13 15:05:25 -07002444 switch (mType) {
2445
2446 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002447 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002448 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002449 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2450 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002451 sampleRate, format, channelMask, mOutput, mFormat);
2452 lStatus = BAD_VALUE;
2453 goto Exit;
2454 }
2455 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002456 break;
2457
2458 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002460 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2461 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462 sampleRate, format, channelMask, mOutput, mFormat);
2463 lStatus = BAD_VALUE;
2464 goto Exit;
2465 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002466 break;
2467
2468 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002469 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002470 ALOGE("createTrack_l() Bad parameter: format %#x \""
2471 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002472 format, mOutput, mFormat);
2473 lStatus = BAD_VALUE;
2474 goto Exit;
2475 }
Andy Hungcd044842014-08-07 11:04:34 -07002476 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002477 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2478 lStatus = BAD_VALUE;
2479 goto Exit;
2480 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002481 break;
2482
Eric Laurent81784c32012-11-19 14:55:58 -08002483 }
2484
2485 lStatus = initCheck();
2486 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002487 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002488 goto Exit;
2489 }
2490
2491 { // scope for mLock
2492 Mutex::Autolock _l(mLock);
2493
2494 // all tracks in same audio session must share the same routing strategy otherwise
2495 // conflicts will happen when tracks are moved from one output to another by audio policy
2496 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002497 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002498 for (size_t i = 0; i < mTracks.size(); ++i) {
2499 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002500 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002501 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002502 if (sessionId == t->sessionId() && strategy != actual) {
2503 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2504 strategy, actual);
2505 lStatus = BAD_VALUE;
2506 goto Exit;
2507 }
2508 }
2509 }
2510
yucliuc9c49cd2020-07-13 16:25:21 -07002511 // Set DIRECT flag if current thread is DirectOutputThread. This can
2512 // happen when the playback is rerouted to direct output thread by
2513 // dynamic audio policy.
2514 // Do NOT report the flag changes back to client, since the client
2515 // doesn't explicitly request a direct flag.
2516 audio_output_flags_t trackFlags = *flags;
2517 if (mType == DIRECT) {
2518 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2519 }
2520
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002521 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002522 channelMask, frameCount,
2523 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002524 sessionId, creatorPid, attributionSource, trackFlags,
2525 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002526
Glenn Kasten03003332013-08-06 15:40:54 -07002527 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2528 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002529 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002530 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002531 goto Exit;
2532 }
2533 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002534 {
2535 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2536 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002537 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002538 }
2539 }
Eric Laurent81784c32012-11-19 14:55:58 -08002540
2541 sp<EffectChain> chain = getEffectChain_l(sessionId);
2542 if (chain != 0) {
2543 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2544 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002545 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002546 chain->incTrackCnt();
2547 }
2548
Eric Laurent05067782016-06-01 18:27:28 -07002549 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002550 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2551 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2552 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002553 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002554 }
2555 }
2556
2557 lStatus = NO_ERROR;
2558
2559Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002560 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002561 return track;
2562}
2563
Andy Hung1bc088a2018-02-09 15:57:31 -08002564template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002565ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2566{
Andy Hungc0691382018-09-12 18:01:57 -07002567 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002568 const ssize_t index = mTracks.remove(track);
2569 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002570 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002571 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002572 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002573 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002574 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002575 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002576 }
2577 return index;
2578}
2579
Eric Laurent81784c32012-11-19 14:55:58 -08002580uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2581{
2582 return latency;
2583}
2584
2585uint32_t AudioFlinger::PlaybackThread::latency() const
2586{
2587 Mutex::Autolock _l(mLock);
2588 return latency_l();
2589}
2590uint32_t AudioFlinger::PlaybackThread::latency_l() const
2591{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002592 uint32_t latency;
2593 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2594 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002595 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002596 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002597}
2598
2599void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2600{
2601 Mutex::Autolock _l(mLock);
2602 // Don't apply master volume in SW if our HAL can do it for us.
2603 if (mOutput && mOutput->audioHwDev &&
2604 mOutput->audioHwDev->canSetMasterVolume()) {
2605 mMasterVolume = 1.0;
2606 } else {
2607 mMasterVolume = value;
2608 }
2609}
2610
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002611void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2612{
2613 mMasterBalance.store(balance);
2614}
2615
Eric Laurent81784c32012-11-19 14:55:58 -08002616void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2617{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002618 if (isDuplicating()) {
2619 return;
2620 }
Eric Laurent81784c32012-11-19 14:55:58 -08002621 Mutex::Autolock _l(mLock);
2622 // Don't apply master mute in SW if our HAL can do it for us.
2623 if (mOutput && mOutput->audioHwDev &&
2624 mOutput->audioHwDev->canSetMasterMute()) {
2625 mMasterMute = false;
2626 } else {
2627 mMasterMute = muted;
2628 }
2629}
2630
2631void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2632{
2633 Mutex::Autolock _l(mLock);
2634 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002635 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002636}
2637
2638void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2639{
2640 Mutex::Autolock _l(mLock);
2641 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002642 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002643}
2644
2645float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2646{
2647 Mutex::Autolock _l(mLock);
2648 return mStreamTypes[stream].volume;
2649}
2650
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002651void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2652{
2653 mOutput->stream->setVolume(left, right);
2654}
2655
Eric Laurent81784c32012-11-19 14:55:58 -08002656// addTrack_l() must be called with ThreadBase::mLock held
2657status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2658{
2659 status_t status = ALREADY_EXISTS;
2660
Eric Laurent81784c32012-11-19 14:55:58 -08002661 if (mActiveTracks.indexOf(track) < 0) {
2662 // the track is newly added, make sure it fills up all its
2663 // buffers before playing. This is to ensure the client will
2664 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002665 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 TrackBase::track_state state = track->mState;
2667 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002668 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 mLock.lock();
2670 // abort track was stopped/paused while we released the lock
2671 if (state != track->mState) {
2672 if (status == NO_ERROR) {
2673 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002674 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 mLock.lock();
2676 }
2677 return INVALID_OPERATION;
2678 }
2679 // abort if start is rejected by audio policy manager
2680 if (status != NO_ERROR) {
2681 return PERMISSION_DENIED;
2682 }
2683#ifdef ADD_BATTERY_DATA
2684 // to track the speaker usage
2685 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2686#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002687 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 }
2689
Eric Laurent51716182016-02-29 18:00:56 -08002690 // set retry count for buffer fill
2691 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002692 if (track->isStopping_1()) {
2693 track->mRetryCount = kMaxTrackStopRetriesOffload;
2694 } else {
2695 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2696 }
2697 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002698 } else {
2699 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002700 track->mFillingUpStatus =
2701 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002702 }
2703
jiabineb3bda02020-06-30 14:07:03 -07002704 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2705 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2706 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2707 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002708 // Unlock due to VibratorService will lock for this call and will
2709 // call Tracks.mute/unmute which also require thread's lock.
2710 mLock.unlock();
2711 const int intensity = AudioFlinger::onExternalVibrationStart(
2712 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002713 std::optional<media::AudioVibratorInfo> vibratorInfo;
2714 {
2715 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2716 // used to play this track.
2717 Mutex::Autolock _l(mAudioFlinger->mLock);
2718 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2719 }
jiabin57303cc2018-12-18 15:45:57 -08002720 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002721 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002722 if (vibratorInfo) {
2723 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2724 }
2725
jiabin57303cc2018-12-18 15:45:57 -08002726 // Haptic playback should be enabled by vibrator service.
2727 if (track->getHapticPlaybackEnabled()) {
2728 // Disable haptic playback of all active track to ensure only
2729 // one track playing haptic if current track should play haptic.
2730 for (const auto &t : mActiveTracks) {
2731 t->setHapticPlaybackEnabled(false);
2732 }
jiabin245cdd92018-12-07 17:55:15 -08002733 }
jiabine70bc7f2020-06-30 22:07:55 -07002734
2735 // Set haptic intensity for effect
2736 if (chain != nullptr) {
2737 chain->setHapticIntensity_l(track->id(), intensity);
2738 }
jiabin245cdd92018-12-07 17:55:15 -08002739 }
2740
Eric Laurent81784c32012-11-19 14:55:58 -08002741 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002742 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002743 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002744 if (chain != 0) {
2745 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2746 track->sessionId());
2747 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002748 }
2749
Andy Hungc2b11cb2020-04-22 09:04:01 -07002750 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002751 status = NO_ERROR;
2752 }
2753
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002754 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002755 return status;
2756}
2757
Eric Laurentbfb1b832013-01-07 09:53:42 -08002758bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002759{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002760 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002761 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002762 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2763 track->mState = TrackBase::STOPPED;
2764 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002765 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002766 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002768 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769
2770 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002771}
2772
2773void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2774{
2775 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002776
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002777 String8 result;
2778 track->appendDump(result, false /* active */);
2779 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002780
Eric Laurent81784c32012-11-19 14:55:58 -08002781 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002782 {
2783 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2784 mAudioTrackCallbacks.erase(track);
2785 }
Eric Laurent81784c32012-11-19 14:55:58 -08002786 if (track->isFastTrack()) {
2787 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002788 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002789 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2790 mFastTrackAvailMask |= 1 << index;
2791 // redundant as track is about to be destroyed, for dumpsys only
2792 track->mFastIndex = -1;
2793 }
2794 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2795 if (chain != 0) {
2796 chain->decTrackCnt();
2797 }
2798}
2799
2800String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2801{
Eric Laurent81784c32012-11-19 14:55:58 -08002802 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002803 String8 out_s8;
2804 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2805 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002806 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002807 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002808}
2809
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002810status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2811 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002812 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002813 return NO_INIT;
2814 }
2815 return mOutput->stream->selectPresentation(presentationId, programId);
2816}
2817
Mikhail Naganov88536df2021-07-26 17:30:29 -07002818void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002819 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002820 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002821 sp<AudioIoDescriptor> desc;
2822 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002823 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002824 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002825 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002826 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002827 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2828 mSampleRate, mFormat, mChannelMask,
2829 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2830 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002831 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002832 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002833 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002834 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002835 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002836 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002837 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002838 break;
2839 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002840 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002841}
2842
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002843void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002844{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002845 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002846}
2847
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002848void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002849{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002850 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002851}
2852
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002853void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002854{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002855 mCallbackThread->setAsyncError();
2856}
2857
jiabinf6eb4c32020-02-25 14:06:25 -08002858void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2859 const std::basic_string<uint8_t>& metadataBs)
2860{
2861 std::thread([this, metadataBs]() {
2862 audio_utils::metadata::Data metadata =
2863 audio_utils::metadata::dataFromByteString(metadataBs);
2864 if (metadata.empty()) {
2865 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2866 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2867 (int)metadataBs.size());
2868 return;
2869 }
2870
2871 audio_utils::metadata::ByteString metaDataStr =
2872 audio_utils::metadata::byteStringFromData(metadata);
2873 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2874 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002875 for (const auto& callbackPair : mAudioTrackCallbacks) {
2876 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002877 }
2878 }).detach();
2879}
2880
Eric Laurent3b4529e2013-09-05 18:09:19 -07002881void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882{
2883 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002884 // reject out of sequence requests
2885 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2886 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 mWaitWorkCV.signal();
2888 }
2889}
2890
Eric Laurent3b4529e2013-09-05 18:09:19 -07002891void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892{
2893 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002894 // reject out of sequence requests
2895 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002896 // Register discontinuity when HW drain is completed because that can cause
2897 // the timestamp frame position to reset to 0 for direct and offload threads.
2898 // (Out of sequence requests are ignored, since the discontinuity would be handled
2899 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002900 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002901 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902 mWaitWorkCV.signal();
2903 }
2904}
2905
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002906void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002907{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002908 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002909 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2910 mSampleRate = audioConfig.sample_rate;
2911 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002912 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002913 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002914 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002915 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002916 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2917 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002918 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002919
2920 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2921 mMixerChannelMask = mChannelMask;
2922 }
2923
Andy Hunge5412692014-05-16 11:25:07 -07002924 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002925 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002926
Eric Laurentf1f22e72021-07-13 14:04:14 +02002927 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2928
Phil Burkca5e6142015-07-14 09:42:29 -07002929 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002930 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002931 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002932 // Get format from the shim, which will be different than the HAL format
2933 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002934 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002935 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002936 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002937 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002938 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002939 LOG_FATAL("HAL format %#x not supported for mixed output",
2940 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002941 }
Phil Burk062e67a2015-02-11 13:40:50 -08002942 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002943 result = mOutput->stream->getBufferSize(&mBufferSize);
2944 LOG_ALWAYS_FATAL_IF(result != OK,
2945 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002946 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002947 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002948 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002949 mFrameCount);
2950 }
2951
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002952 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2953 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002954 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002955 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002956 }
2957 }
2958
Eric Laurentd1f69b02014-12-15 14:33:13 -08002959 mHwSupportsPause = false;
2960 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002961 bool supportsPause = false, supportsResume = false;
2962 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2963 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002964 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002965 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002966 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002967 } else if (supportsResume) {
2968 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002969 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002970 }
2971 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002972 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2973 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2974 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002975
Andy Hungfbfc3952015-01-15 13:33:51 -08002976 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2977 // For best precision, we use float instead of the associated output
2978 // device format (typically PCM 16 bit).
2979
2980 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2981 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2982 mBufferSize = mFrameSize * mFrameCount;
2983
2984 // TODO: We currently use the associated output device channel mask and sample rate.
2985 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2986 // (if a valid mask) to avoid premature downmix.
2987 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2988 // instead of the output device sample rate to avoid loss of high frequency information.
2989 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2990 }
2991
Andy Hung09a50072014-02-27 14:30:47 -08002992 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002993 double multiplier = 1.0;
2994 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2995 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002996 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2997 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002998
Eric Laurent81784c32012-11-19 14:55:58 -08002999 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3000 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3001 maxNormalFrameCount = maxNormalFrameCount & ~15;
3002 if (maxNormalFrameCount < minNormalFrameCount) {
3003 maxNormalFrameCount = minNormalFrameCount;
3004 }
3005 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3006 if (multiplier <= 1.0) {
3007 multiplier = 1.0;
3008 } else if (multiplier <= 2.0) {
3009 if (2 * mFrameCount <= maxNormalFrameCount) {
3010 multiplier = 2.0;
3011 } else {
3012 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3013 }
3014 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003015 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003016 }
3017 }
3018 mNormalFrameCount = multiplier * mFrameCount;
3019 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003020 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003021 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3022 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003023 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003024 mNormalFrameCount);
3025
Andy Hung08fb1742015-05-31 23:22:10 -07003026 // Check if we want to throttle the processing to no more than 2x normal rate
3027 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003028 mThreadThrottleTimeMs = 0;
3029 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003030 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3031
Andy Hung010a1a12014-03-13 13:57:33 -07003032 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3033 // Originally this was int16_t[] array, need to remove legacy implications.
3034 free(mSinkBuffer);
3035 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003036
Andy Hung5b10a202014-03-13 13:59:29 -07003037 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3038 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3039 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003040 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003041
Andy Hung69aed5f2014-02-25 17:24:40 -08003042 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3043 // drives the output.
3044 free(mMixerBuffer);
3045 mMixerBuffer = NULL;
3046 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003047 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003048 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003049 * audio_bytes_per_sample(mMixerBufferFormat);
3050 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3051 }
Andy Hung98ef9782014-03-04 14:46:50 -08003052 free(mEffectBuffer);
3053 mEffectBuffer = NULL;
3054 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003055 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003056 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003057 * audio_bytes_per_sample(mEffectBufferFormat);
3058 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3059 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003060
Eric Laurentb62d0362021-10-26 17:40:18 +02003061 if (mType == SPATIALIZER) {
3062 free(mPostSpatializerBuffer);
3063 mPostSpatializerBuffer = nullptr;
3064 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3065 * audio_bytes_per_sample(mEffectBufferFormat);
3066 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3067 }
3068
Mikhail Naganov55773032020-10-01 15:08:13 -07003069 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3070 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003071 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3072 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003073 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003074
Eric Laurent81784c32012-11-19 14:55:58 -08003075 // force reconfiguration of effect chains and engines to take new buffer size and audio
3076 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003077 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003078 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3079 // matter.
3080 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3081 Vector< sp<EffectChain> > effectChains = mEffectChains;
3082 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003083 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3084 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003085 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003086
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003087 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003088 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003089 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3090 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3091 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3092 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3093 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3094 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3095 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3096 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3097 (int32_t)mHapticChannelMask)
3098 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3099 (int32_t)mHapticChannelCount)
3100 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3101 formatToString(mHALFormat).c_str())
3102 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3103 (int32_t)mFrameCount) // sic - added HAL
3104 ;
3105 uint32_t latencyMs;
3106 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3107 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3108 }
3109 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003110}
3111
Kevin Rocard069c2712018-03-29 19:09:14 -07003112void AudioFlinger::PlaybackThread::updateMetadata_l()
3113{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003114 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003115 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003116 }
3117 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003118 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003119 for (const sp<Track> &track : mActiveTracks) {
3120 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003121 // Do not forward metadata for PatchTrack with unspecified stream type
3122 if (track->streamType() != AUDIO_STREAM_PATCH) {
3123 track->copyMetadataTo(backInserter);
3124 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003125 }
Kevin Rocard12381092018-04-11 09:19:59 -07003126 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003127}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003128
Kevin Rocard12381092018-04-11 09:19:59 -07003129void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3130 const StreamOutHalInterface::SourceMetadata& metadata)
3131{
3132 mOutput->stream->updateSourceMetadata(metadata);
3133};
3134
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003135status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003136{
3137 if (halFrames == NULL || dspFrames == NULL) {
3138 return BAD_VALUE;
3139 }
3140 Mutex::Autolock _l(mLock);
3141 if (initCheck() != NO_ERROR) {
3142 return INVALID_OPERATION;
3143 }
Andy Hung818e7a32016-02-16 18:08:07 -08003144 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003145 *halFrames = framesWritten;
3146
3147 if (isSuspended()) {
3148 // return an estimation of rendered frames when the output is suspended
3149 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003150 *dspFrames = (uint32_t)
3151 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003152 return NO_ERROR;
3153 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003154 status_t status;
3155 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003156 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003157 *dspFrames = (size_t)frames;
3158 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003159 }
3160}
3161
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003162product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003163{
3164 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3165 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3166 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003167 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003168 }
3169 for (size_t i = 0; i < mTracks.size(); i++) {
3170 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003171 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003172 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003173 }
3174 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003175 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003176}
3177
3178
Phil Burk062e67a2015-02-11 13:40:50 -08003179AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003180{
3181 Mutex::Autolock _l(mLock);
3182 return mOutput;
3183}
3184
Phil Burk062e67a2015-02-11 13:40:50 -08003185AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003186{
3187 Mutex::Autolock _l(mLock);
3188 AudioStreamOut *output = mOutput;
3189 mOutput = NULL;
3190 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3191 // must push a NULL and wait for ack
3192 mOutputSink.clear();
3193 mPipeSink.clear();
3194 mNormalSink.clear();
3195 return output;
3196}
3197
3198// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003199sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003200{
3201 if (mOutput == NULL) {
3202 return NULL;
3203 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003204 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003205}
3206
3207uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3208{
3209 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3210}
3211
3212status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3213{
3214 if (!isValidSyncEvent(event)) {
3215 return BAD_VALUE;
3216 }
3217
3218 Mutex::Autolock _l(mLock);
3219
3220 for (size_t i = 0; i < mTracks.size(); ++i) {
3221 sp<Track> track = mTracks[i];
3222 if (event->triggerSession() == track->sessionId()) {
3223 (void) track->setSyncEvent(event);
3224 return NO_ERROR;
3225 }
3226 }
3227
3228 return NAME_NOT_FOUND;
3229}
3230
3231bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3232{
3233 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3234}
3235
3236void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3237 const Vector< sp<Track> >& tracksToRemove)
3238{
Andy Hungfe726a62018-09-27 15:17:25 -07003239 // Miscellaneous track cleanup when removed from the active list,
3240 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003241#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003242 for (const auto& track : tracksToRemove) {
3243 if (track->isExternalTrack()) {
3244 // to track the speaker usage
3245 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003246 }
3247 }
Andy Hungfe726a62018-09-27 15:17:25 -07003248#else
3249 (void)tracksToRemove; // suppress unused warning
3250#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003251}
3252
3253void AudioFlinger::PlaybackThread::checkSilentMode_l()
3254{
3255 if (!mMasterMute) {
3256 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003257 if (mOutDeviceTypeAddrs.empty()) {
3258 ALOGD("ro.audio.silent is ignored since no output device is set");
3259 return;
3260 }
jiabinc52b1ff2019-10-31 17:20:42 -07003261 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003262 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3263 return;
3264 }
Eric Laurent81784c32012-11-19 14:55:58 -08003265 if (property_get("ro.audio.silent", value, "0") > 0) {
3266 char *endptr;
3267 unsigned long ul = strtoul(value, &endptr, 0);
3268 if (*endptr == '\0' && ul != 0) {
3269 ALOGD("Silence is golden");
3270 // The setprop command will not allow a property to be changed after
3271 // the first time it is set, so we don't have to worry about un-muting.
3272 setMasterMute_l(true);
3273 }
3274 }
3275 }
3276}
3277
3278// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003279ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003280{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003281 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003282 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003283 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003284 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003285
3286 // If an NBAIO sink is present, use it to write the normal mixer's submix
3287 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003288
Andy Hung010a1a12014-03-13 13:57:33 -07003289 const size_t count = mBytesRemaining / mFrameSize;
3290
Simon Wilson2d590962012-11-29 15:18:50 -08003291 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003292 // update the setpoint when AudioFlinger::mScreenState changes
3293 uint32_t screenState = AudioFlinger::mScreenState;
3294 if (screenState != mScreenState) {
3295 mScreenState = screenState;
3296 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3297 if (pipe != NULL) {
3298 pipe->setAvgFrames((mScreenState & 1) ?
3299 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3300 }
3301 }
Andy Hung010a1a12014-03-13 13:57:33 -07003302 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003303 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003304 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003305 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003306#ifdef TEE_SINK
3307 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3308#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003309 } else {
3310 bytesWritten = framesWritten;
3311 }
3312 // otherwise use the HAL / AudioStreamOut directly
3313 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003314 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003315
Eric Laurentbfb1b832013-01-07 09:53:42 -08003316 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003317 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3318 mWriteAckSequence += 2;
3319 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003320 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003321 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003322 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003323 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003324 // FIXME We should have an implementation of timestamps for direct output threads.
3325 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003326 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003327 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003328
Eric Laurentbfb1b832013-01-07 09:53:42 -08003329 if (mUseAsyncWrite &&
3330 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3331 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003332 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003333 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003334 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003335 }
Eric Laurent81784c32012-11-19 14:55:58 -08003336 }
3337
Eric Laurent81784c32012-11-19 14:55:58 -08003338 mNumWrites++;
3339 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003340 if (mStandby) {
3341 mThreadMetrics.logBeginInterval();
3342 mStandby = false;
3343 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003344 return bytesWritten;
3345}
3346
3347void AudioFlinger::PlaybackThread::threadLoop_drain()
3348{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003349 bool supportsDrain = false;
3350 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003351 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3352 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003353 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3354 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003356 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003357 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003358 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003359 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 }
3361}
3362
3363void AudioFlinger::PlaybackThread::threadLoop_exit()
3364{
Eric Laurent275e8e92014-11-30 15:14:47 -08003365 {
3366 Mutex::Autolock _l(mLock);
3367 for (size_t i = 0; i < mTracks.size(); i++) {
3368 sp<Track> track = mTracks[i];
3369 track->invalidate();
3370 }
Andy Hungdae27702016-10-31 14:01:16 -07003371 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3372 // After we exit there are no more track changes sent to BatteryNotifier
3373 // because that requires an active threadLoop.
3374 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3375 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003376 }
Eric Laurent81784c32012-11-19 14:55:58 -08003377}
3378
3379/*
3380The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003381 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003382 - mActiveSleepTimeUs from activeSleepTimeUs()
3383 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003384 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3385 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003386 - maxPeriod from frame count and sample rate (MIXER only)
3387
3388The parameters that affect these derived values are:
3389 - frame count
3390 - frame size
3391 - sample rate
3392 - device type: A2DP or not
3393 - device latency
3394 - format: PCM or not
3395 - active sleep time
3396 - idle sleep time
3397*/
3398
3399void AudioFlinger::PlaybackThread::cacheParameters_l()
3400{
Andy Hung25c2dac2014-02-27 14:56:00 -08003401 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003402 mActiveSleepTimeUs = activeSleepTimeUs();
3403 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003404
3405 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3406 // truncating audio when going to standby.
3407 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003408 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003409 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3410 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3411 }
3412 }
Eric Laurent81784c32012-11-19 14:55:58 -08003413}
3414
Eric Laurent13084622016-05-17 10:51:49 -07003415bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003416{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003417 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003418 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003419 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003420 size_t size = mTracks.size();
3421 for (size_t i = 0; i < size; i++) {
3422 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003423 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003424 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003425 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003426 }
3427 }
Eric Laurent13084622016-05-17 10:51:49 -07003428 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003429}
3430
Haynes Mathew George05317d22016-05-03 16:34:26 -07003431void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3432{
3433 Mutex::Autolock _l(mLock);
3434 invalidateTracks_l(streamType);
3435}
3436
jiabinf042b9b2021-05-07 23:46:28 +00003437// getTrackById_l must be called with holding thread lock
3438AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3439 audio_port_handle_t trackPortId) {
3440 for (size_t i = 0; i < mTracks.size(); i++) {
3441 if (mTracks[i]->portId() == trackPortId) {
3442 return mTracks[i].get();
3443 }
3444 }
3445 return nullptr;
3446}
3447
Eric Laurent81784c32012-11-19 14:55:58 -08003448status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3449{
Glenn Kastend848eb42016-03-08 13:42:11 -08003450 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003451 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003452 effect_buffer_t *buffer = nullptr; // only used for non global sessions
3453
3454 if (mType == SPATIALIZER ) {
3455 if (!audio_is_global_session(session)) {
3456 // player sessions on a spatializer output will use a dedicated input buffer and
3457 // will either output multi channel to mEffectBuffer if the track is spatilaized
3458 // or stereo to mPostSpatializerBuffer if not spatialized.
3459 uint32_t channelMask;
3460 bool isSessionSpatialized =
3461 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3462 if (isSessionSpatialized) {
3463 channelMask = mMixerChannelMask;
3464 } else {
3465 channelMask = mChannelMask;
3466 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003467 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003468 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003469 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003470 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003471 &halInBuffer);
3472 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003473
3474 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3475 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3476 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3477 &halOutBuffer);
3478 if (result != OK) return result;
3479
rago94a1ee82017-07-21 15:11:02 -07003480#ifdef FLOAT_EFFECT_CHAIN
3481 buffer = halInBuffer->audioBuffer()->f32;
3482#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003483 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003484#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003485 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3486 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003487 } else {
3488 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3489 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3490 // mPostSpatializerBuffer as output buffer
3491 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3492 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3493 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3494 if (result != OK) return result;
3495 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3496 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3497 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003498
Eric Laurentb62d0362021-10-26 17:40:18 +02003499 if (session == AUDIO_SESSION_DEVICE) {
3500 halInBuffer = halOutBuffer;
3501 }
3502 }
3503 } else {
3504 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3505 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3506 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3507 &halInBuffer);
3508 if (result != OK) return result;
3509 halOutBuffer = halInBuffer;
3510 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3511 if (!audio_is_global_session(session)) {
3512 buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
3513 // Only one effect chain can be present in direct output thread and it uses
3514 // the sink buffer as input
3515 if (mType != DIRECT) {
3516 size_t numSamples = mNormalFrameCount
3517 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3518 + mHapticChannelCount);
3519 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
3520 numSamples * sizeof(effect_buffer_t),
3521 &halInBuffer);
3522 if (result != OK) return result;
3523#ifdef FLOAT_EFFECT_CHAIN
3524 buffer = halInBuffer->audioBuffer()->f32;
3525#else
3526 buffer = halInBuffer->audioBuffer()->s16;
3527#endif
3528 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3529 buffer, session);
3530 }
3531 }
3532 }
3533
3534 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003535 // Attach all tracks with same session ID to this chain.
3536 for (size_t i = 0; i < mTracks.size(); ++i) {
3537 sp<Track> track = mTracks[i];
3538 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003539 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3540 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003541 track->setMainBuffer(buffer);
3542 chain->incTrackCnt();
3543 }
3544 }
3545
3546 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003547 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003548 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003549 ALOGV("addEffectChain_l() activating track %p on session %d",
3550 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003551 chain->incActiveTrackCnt();
3552 }
3553 }
3554 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003555
Eric Laurentaaa44472014-09-12 17:41:50 -07003556 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003557 chain->setInBuffer(halInBuffer);
3558 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003559 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3560 // chains list in order to be processed last as it contains output device effects.
3561 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3562 // processing effects specific to an output stream before effects applied to all streams
3563 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003564 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3565 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003566 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003567 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003568 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003569 // Effect chain for other sessions are inserted at beginning of effect
3570 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003571 // sessions is not important.
3572 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003573 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3574 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003575 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003576 size_t size = mEffectChains.size();
3577 size_t i = 0;
3578 for (i = 0; i < size; i++) {
3579 if (mEffectChains[i]->sessionId() < session) {
3580 break;
3581 }
3582 }
3583 mEffectChains.insertAt(chain, i);
3584 checkSuspendOnAddEffectChain_l(chain);
3585
3586 return NO_ERROR;
3587}
3588
3589size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3590{
Glenn Kastend848eb42016-03-08 13:42:11 -08003591 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003592
3593 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3594
3595 for (size_t i = 0; i < mEffectChains.size(); i++) {
3596 if (chain == mEffectChains[i]) {
3597 mEffectChains.removeAt(i);
3598 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003599 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003600 if (session == track->sessionId()) {
3601 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3602 chain.get(), session);
3603 chain->decActiveTrackCnt();
3604 }
3605 }
3606
3607 // detach all tracks with same session ID from this chain
3608 for (size_t i = 0; i < mTracks.size(); ++i) {
3609 sp<Track> track = mTracks[i];
3610 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003611 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003612 chain->decTrackCnt();
3613 }
3614 }
3615 break;
3616 }
3617 }
3618 return mEffectChains.size();
3619}
3620
3621status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003622 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003623{
3624 Mutex::Autolock _l(mLock);
3625 return attachAuxEffect_l(track, EffectId);
3626}
3627
3628status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003629 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003630{
3631 status_t status = NO_ERROR;
3632
3633 if (EffectId == 0) {
3634 track->setAuxBuffer(0, NULL);
3635 } else {
3636 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3637 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3638 if (effect != 0) {
3639 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3640 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3641 } else {
3642 status = INVALID_OPERATION;
3643 }
3644 } else {
3645 status = BAD_VALUE;
3646 }
3647 }
3648 return status;
3649}
3650
3651void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3652{
3653 for (size_t i = 0; i < mTracks.size(); ++i) {
3654 sp<Track> track = mTracks[i];
3655 if (track->auxEffectId() == effectId) {
3656 attachAuxEffect_l(track, 0);
3657 }
3658 }
3659}
3660
3661bool AudioFlinger::PlaybackThread::threadLoop()
3662{
Glenn Kasten388d5712017-04-07 14:38:41 -07003663 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003664
Eric Laurent81784c32012-11-19 14:55:58 -08003665 Vector< sp<Track> > tracksToRemove;
3666
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003667 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003668 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003669
3670 // MIXER
3671 nsecs_t lastWarning = 0;
3672
3673 // DUPLICATING
3674 // FIXME could this be made local to while loop?
3675 writeFrames = 0;
3676
3677 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003678 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003679
3680 if (mType == MIXER) {
3681 sleepTimeShift = 0;
3682 }
3683
3684 CpuStats cpuStats;
3685 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3686
3687 acquireWakeLock();
3688
Glenn Kasteneef598c2017-04-03 14:41:13 -07003689 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3690 // thread associated with this PlaybackThread.
3691 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3692 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003693 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3694 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003695 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003696 const char *logString = NULL;
3697
rago1bb90822017-05-02 18:31:48 -07003698 // Estimated time for next buffer to be written to hal. This is used only on
3699 // suspended mode (for now) to help schedule the wait time until next iteration.
3700 nsecs_t timeLoopNextNs = 0;
3701
Eric Laurent664539d2013-09-23 18:24:31 -07003702 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003703
Andy Hung2dbffc22018-08-08 18:50:41 -07003704 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003705
Eric Laurentb3f315a2021-07-13 15:09:05 +02003706 sendCheckOutputStageEffectsEvent();
3707
Andy Hung446f4df2019-02-21 12:26:41 -08003708 // loopCount is used for statistics and diagnostics.
3709 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003710 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003711 // Log merge requests are performed during AudioFlinger binder transactions, but
3712 // that does not cover audio playback. It's requested here for that reason.
3713 mAudioFlinger->requestLogMerge();
3714
Eric Laurent81784c32012-11-19 14:55:58 -08003715 cpuStats.sample(myName);
3716
3717 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003718 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003719 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003720 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003721
Andy Hung2dbffc22018-08-08 18:50:41 -07003722 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3723 //
jiabinc52b1ff2019-10-31 17:20:42 -07003724 // Note: we access outDeviceTypes() outside of mLock.
3725 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003726 // Here, we try for the AF lock, but do not block on it as the latency
3727 // is more informational.
3728 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3729 std::vector<PatchPanel::SoftwarePatch> swPatches;
3730 double latencyMs;
3731 status_t status = INVALID_OPERATION;
3732 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3733 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3734 && swPatches.size() > 0) {
3735 status = swPatches[0].getLatencyMs_l(&latencyMs);
3736 downstreamPatchHandle = swPatches[0].getPatchHandle();
3737 }
3738 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003739 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003740 lastDownstreamPatchHandle = downstreamPatchHandle;
3741 }
3742 if (status == OK) {
3743 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003744 // latency of 5 seconds).
3745 const double minLatency = 0., maxLatency = 5000.;
3746 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003747 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003748 } else {
3749 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003750 if (latencyMs < minLatency) latencyMs = minLatency;
3751 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003752 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003753 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003754 }
3755 mAudioFlinger->mLock.unlock();
3756 }
3757 } else {
3758 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3759 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003760 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003761 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3762 }
3763 }
3764
Eric Laurentb3f315a2021-07-13 15:09:05 +02003765 if (mCheckOutputStageEffects.exchange(false)) {
3766 checkOutputStageEffects();
3767 }
3768
Eric Laurent81784c32012-11-19 14:55:58 -08003769 { // scope for mLock
3770
3771 Mutex::Autolock _l(mLock);
3772
Eric Laurent021cf962014-05-13 10:18:14 -07003773 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003774 if (mCheckOutputStageEffects.load()) {
3775 continue;
3776 }
Eric Laurent10351942014-05-08 18:49:52 -07003777
Glenn Kasteneef598c2017-04-03 14:41:13 -07003778 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003779 if (logString != NULL) {
3780 mNBLogWriter->logTimestamp();
3781 mNBLogWriter->log(logString);
3782 logString = NULL;
3783 }
3784
Dean Wheatley12473e92021-03-18 23:00:55 +11003785 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003786
Eric Laurent81784c32012-11-19 14:55:58 -08003787 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003788 if (mSignalPending) {
3789 // A signal was raised while we were unlocked
3790 mSignalPending = false;
3791 } else if (waitingAsyncCallback_l()) {
3792 if (exitPending()) {
3793 break;
3794 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003795 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003796 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003797 releaseWakeLock_l();
3798 released = true;
3799 }
Andy Hung10cbff12017-02-21 17:30:14 -08003800
3801 const int64_t waitNs = computeWaitTimeNs_l();
3802 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3803 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3804 if (status == TIMED_OUT) {
3805 mSignalPending = true; // if timeout recheck everything
3806 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003808 if (released) {
3809 acquireWakeLock_l();
3810 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003811 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3812 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003813
3814 continue;
3815 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003816 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003817 isSuspended()) {
3818 // put audio hardware into standby after short delay
3819 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003820
3821 threadLoop_standby();
3822
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003823 // This is where we go into standby
3824 if (!mStandby) {
3825 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003826 mThreadMetrics.logEndInterval();
3827 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003828 }
Andy Hungd0979812019-02-21 15:51:44 -08003829 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003830 }
3831
Eric Tan39ec8d62018-07-24 09:49:29 -07003832 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003833 // we're about to wait, flush the binder command buffer
3834 IPCThreadState::self()->flushCommands();
3835
3836 clearOutputTracks();
3837
3838 if (exitPending()) {
3839 break;
3840 }
3841
3842 releaseWakeLock_l();
3843 // wait until we have something to do...
3844 ALOGV("%s going to sleep", myName.string());
3845 mWaitWorkCV.wait(mLock);
3846 ALOGV("%s waking up", myName.string());
3847 acquireWakeLock_l();
3848
3849 mMixerStatus = MIXER_IDLE;
3850 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3851 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003852 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003853 checkSilentMode_l();
3854
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003855 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3856 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003857 if (mType == MIXER) {
3858 sleepTimeShift = 0;
3859 }
3860
3861 continue;
3862 }
3863 }
Eric Laurent81784c32012-11-19 14:55:58 -08003864 // mMixerStatusIgnoringFastTracks is also updated internally
3865 mMixerStatus = prepareTracks_l(&tracksToRemove);
3866
Andy Hungdae27702016-10-31 14:01:16 -07003867 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003868
Kevin Rocard069c2712018-03-29 19:09:14 -07003869 updateMetadata_l();
3870
Eric Laurent81784c32012-11-19 14:55:58 -08003871 // prevent any changes in effect chain list and in each effect chain
3872 // during mixing and effect process as the audio buffers could be deleted
3873 // or modified if an effect is created or deleted
3874 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003875
3876 // Determine which session to pick up haptic data.
3877 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003878 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003879 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003880 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003881 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003882 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003883 if (effectChain != nullptr
3884 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003885 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003886 isHapticSessionSpatialized =
3887 mType == SPATIALIZER && track->canBeSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003888 break;
3889 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003890 if (activeHapticSessionId == AUDIO_SESSION_NONE
3891 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003892 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003893 isHapticSessionSpatialized =
3894 mType == SPATIALIZER && track->canBeSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003895 }
3896 }
3897 }
3898
Andy Hungc1646382019-04-30 16:12:10 -07003899 // Acquire a local copy of active tracks with lock (release w/o lock).
3900 //
3901 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3902 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3903 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3904 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003905 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003906
Eric Laurentbfb1b832013-01-07 09:53:42 -08003907 if (mBytesRemaining == 0) {
3908 mCurrentWriteLength = 0;
3909 if (mMixerStatus == MIXER_TRACKS_READY) {
3910 // threadLoop_mix() sets mCurrentWriteLength
3911 threadLoop_mix();
3912 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3913 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003914 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003915 // must be written to HAL
3916 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003917 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003918 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003919
3920 // Tally underrun frames as we are inserting 0s here.
3921 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003922 if (track->mFillingUpStatus == Track::FS_ACTIVE
3923 && !track->isStopped()
3924 && !track->isPaused()
3925 && !track->isTerminated()) {
3926 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3927 __func__, track->id(), track->getTrackStateAsString(),
3928 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003929 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3930 }
3931 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003932 }
3933 }
Andy Hung98ef9782014-03-04 14:46:50 -08003934 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003935 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003936 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3937 // or mSinkBuffer (if there are no effects).
3938 //
3939 // This is done pre-effects computation; if effects change to
3940 // support higher precision, this needs to move.
3941 //
3942 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003943 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003944 uint32_t mixerChannelCount = mEffectBufferValid ?
3945 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003946 if (mMixerBufferValid) {
3947 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3948 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3949
Andy Hung2ddee192015-12-18 17:34:44 -08003950 // mono blend occurs for mixer threads only (not direct or offloaded)
3951 // and is handled here if we're going directly to the sink.
3952 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003953 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3954 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003955 }
3956
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003957 if (!hasFastMixer()) {
3958 // Balance must take effect after mono conversion.
3959 // We do it here if there is no FastMixer.
3960 // mBalance detects zero balance within the class for speed (not needed here).
3961 mBalance.setBalance(mMasterBalance.load());
3962 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3963 }
3964
Andy Hung98ef9782014-03-04 14:46:50 -08003965 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02003966 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08003967
3968 // If we're going directly to the sink and there are haptic channels,
3969 // we should adjust channels as the sample data is partially interleaved
3970 // in this case.
3971 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3972 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3973 mChannelCount + mHapticChannelCount,
3974 audio_bytes_per_sample(format),
3975 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3976 }
Andy Hung98ef9782014-03-04 14:46:50 -08003977 }
3978
Eric Laurentbfb1b832013-01-07 09:53:42 -08003979 mBytesRemaining = mCurrentWriteLength;
3980 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003981 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3982 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3983 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3984 mBytesWritten += mBytesRemaining;
3985 mFramesWritten += framesRemaining;
3986 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003987 mBytesRemaining = 0;
3988 }
Eric Laurent81784c32012-11-19 14:55:58 -08003989
Eric Laurentbfb1b832013-01-07 09:53:42 -08003990 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003991 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003992 for (size_t i = 0; i < effectChains.size(); i ++) {
3993 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003994 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003995 if (activeHapticSessionId != AUDIO_SESSION_NONE
3996 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003997 // Haptic data is active in this case, copy it directly from
3998 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02003999 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4000 audio_channel_count_from_out_mask(mMixerChannelMask) :
4001 mChannelCount;
4002 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4003 hapticSessionChannelCount = mChannelCount;
4004 }
4005
jiabin47affe52019-04-04 18:02:07 -07004006 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004007 * audio_bytes_per_frame(hapticSessionChannelCount,
4008 EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07004009 memcpy_by_audio_format(
4010 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
4011 EFFECT_BUFFER_FORMAT,
4012 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
4013 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
4014 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004015 }
Eric Laurent81784c32012-11-19 14:55:58 -08004016 }
4017 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004018 // Process effect chains for offloaded thread even if no audio
4019 // was read from audio track: process only updates effect state
4020 // and thus does have to be synchronized with audio writes but may have
4021 // to be called while waiting for async write callback
4022 if (mType == OFFLOAD) {
4023 for (size_t i = 0; i < effectChains.size(); i ++) {
4024 effectChains[i]->process_l();
4025 }
4026 }
Eric Laurent81784c32012-11-19 14:55:58 -08004027
Andy Hung98ef9782014-03-04 14:46:50 -08004028 // Only if the Effects buffer is enabled and there is data in the
4029 // Effects buffer (buffer valid), we need to
4030 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004031 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004032 if (mEffectBufferValid) {
4033 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004034 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004035 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004036 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004037 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004038 }
4039
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004040 if (!hasFastMixer()) {
4041 // Balance must take effect after mono conversion.
4042 // We do it here if there is no FastMixer.
4043 // mBalance detects zero balance within the class for speed (not needed here).
4044 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004045 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004046 }
4047
Eric Laurentb62d0362021-10-26 17:40:18 +02004048 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4049 // mPostSpatializerBuffer if the haptics track is spatialized.
4050 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4051 // For other thread types, the haptics channels are already in mEffectBuffer.
4052 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4053 const size_t srcBufferSize = mNormalFrameCount *
4054 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4055 mEffectBufferFormat);
4056 const size_t dstBufferSize = mNormalFrameCount
4057 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4058
4059 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4060 mEffectBufferFormat,
4061 (uint8_t*)mEffectBuffer + srcBufferSize,
4062 mEffectBufferFormat,
4063 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004064 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004065
4066 memcpy_by_audio_format(mSinkBuffer, mFormat, effectBuffer, mEffectBufferFormat,
4067 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
4068
jiabin245cdd92018-12-07 17:55:15 -08004069 // The sample data is partially interleaved when haptic channels exist,
4070 // we need to adjust channels here.
4071 if (mHapticChannelCount > 0) {
4072 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4073 mChannelCount + mHapticChannelCount,
4074 audio_bytes_per_sample(mFormat),
4075 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4076 }
Andy Hung98ef9782014-03-04 14:46:50 -08004077 }
4078
Eric Laurent81784c32012-11-19 14:55:58 -08004079 // enable changes in effect chain
4080 unlockEffectChains(effectChains);
4081
Eric Laurentbfb1b832013-01-07 09:53:42 -08004082 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004083 // mSleepTimeUs == 0 means we must write to audio hardware
4084 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004085 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004086 // writePeriodNs is updated >= 0 when ret > 0.
4087 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004088 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004089 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004090 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004091 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004092 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004093 if (ret < 0) {
4094 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004095 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004096 mBytesWritten += ret;
4097 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004098 const int64_t frames = ret / mFrameSize;
4099 mFramesWritten += frames;
4100
4101 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4102 // process information relating to write time.
4103 if (audio_has_proportional_frames(mFormat)) {
4104 // we are in a continuous mixing cycle
4105 if (mMixerStatus == MIXER_TRACKS_READY &&
4106 loopCount == lastLoopCountWritten + 1) {
4107
4108 const double jitterMs =
4109 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4110 {frames, writePeriodNs},
4111 {0, 0} /* lastTimestamp */, mSampleRate);
4112 const double processMs =
4113 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4114
4115 Mutex::Autolock _l(mLock);
4116 mIoJitterMs.add(jitterMs);
4117 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004118
4119 if (mPipeSink.get() != nullptr) {
4120 // Using the Monopipe availableToWrite, we estimate the current
4121 // buffer size.
4122 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4123 const ssize_t
4124 availableToWrite = mPipeSink->availableToWrite();
4125 const size_t pipeFrames = monoPipe->maxFrames();
4126 const size_t
4127 remainingFrames = pipeFrames - max(availableToWrite, 0);
4128 mMonopipePipeDepthStats.add(remainingFrames);
4129 }
Andy Hung446f4df2019-02-21 12:26:41 -08004130 }
4131
4132 // write blocked detection
4133 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
4134 if (mType == MIXER && deltaWriteNs > maxPeriod) {
4135 mNumDelayedWrites++;
4136 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4137 ATRACE_NAME("underrun");
4138 ALOGW("write blocked for %lld msecs, "
4139 "%d delayed writes, thread %d",
4140 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4141 mNumDelayedWrites, mId);
4142 lastWarning = lastIoEndNs;
4143 }
4144 }
4145 }
4146 // update timing info.
4147 mLastIoBeginNs = lastIoBeginNs;
4148 mLastIoEndNs = lastIoEndNs;
4149 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004150 }
4151 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4152 (mMixerStatus == MIXER_DRAIN_ALL)) {
4153 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004154 }
Andy Hung08fb1742015-05-31 23:22:10 -07004155 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004156
4157 if (mThreadThrottle
4158 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004159 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004160 // Limit MixerThread data processing to no more than twice the
4161 // expected processing rate.
4162 //
4163 // This helps prevent underruns with NuPlayer and other applications
4164 // which may set up buffers that are close to the minimum size, or use
4165 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4166 //
4167 // The throttle smooths out sudden large data drains from the device,
4168 // e.g. when it comes out of standby, which often causes problems with
4169 // (1) mixer threads without a fast mixer (which has its own warm-up)
4170 // (2) minimum buffer sized tracks (even if the track is full,
4171 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004172 //
4173 // Total time spent in last processing cycle equals time spent in
4174 // 1. threadLoop_write, as well as time spent in
4175 // 2. threadLoop_mix (significant for heavy mixing, especially
4176 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004177
Andy Hung446f4df2019-02-21 12:26:41 -08004178 // it's OK if deltaMs is an overestimate.
4179
4180 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004181
Ivan Lozanoea04d392017-11-07 14:37:07 -08004182 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004183 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004184 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004185
Andy Hung08fb1742015-05-31 23:22:10 -07004186 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004187 // notify of throttle start on verbose log
4188 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4189 "mixer(%p) throttle begin:"
4190 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004191 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004192 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004193 // Throttle must be attributed to the previous mixer loop's write time
4194 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004195 // This also ensures proper timing statistics.
4196 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004197 } else {
4198 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4199 if (diff > 0) {
4200 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004201 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004202 ALOGD_IF(!isSingleDeviceType(
4203 outDeviceTypes(), audio_is_a2dp_out_device) &&
4204 !isSingleDeviceType(
4205 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004206 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004207 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4208 }
Andy Hung08fb1742015-05-31 23:22:10 -07004209 }
4210 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004211 }
Eric Laurent81784c32012-11-19 14:55:58 -08004212
Eric Laurentbfb1b832013-01-07 09:53:42 -08004213 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004214 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004215 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004216 // suspended requires accurate metering of sleep time.
4217 if (isSuspended()) {
4218 // advance by expected sleepTime
4219 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4220 const nsecs_t nowNs = systemTime();
4221
4222 // compute expected next time vs current time.
4223 // (negative deltas are treated as delays).
4224 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4225 if (deltaNs < -kMaxNextBufferDelayNs) {
4226 // Delays longer than the max allowed trigger a reset.
4227 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4228 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4229 timeLoopNextNs = nowNs + deltaNs;
4230 } else if (deltaNs < 0) {
4231 // Delays within the max delay allowed: zero the delta/sleepTime
4232 // to help the system catch up in the next iteration(s)
4233 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4234 deltaNs = 0;
4235 }
4236 // update sleep time (which is >= 0)
4237 mSleepTimeUs = deltaNs / 1000;
4238 }
Eric Laurente93cc032016-05-05 10:15:10 -07004239 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4240 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004241 }
Glenn Kastene7754022014-10-31 12:11:26 -07004242 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004243 }
Eric Laurent81784c32012-11-19 14:55:58 -08004244 }
4245
4246 // Finally let go of removed track(s), without the lock held
4247 // since we can't guarantee the destructors won't acquire that
4248 // same lock. This will also mutate and push a new fast mixer state.
4249 threadLoop_removeTracks(tracksToRemove);
4250 tracksToRemove.clear();
4251
4252 // FIXME I don't understand the need for this here;
4253 // it was in the original code but maybe the
4254 // assignment in saveOutputTracks() makes this unnecessary?
4255 clearOutputTracks();
4256
4257 // Effect chains will be actually deleted here if they were removed from
4258 // mEffectChains list during mixing or effects processing
4259 effectChains.clear();
4260
4261 // FIXME Note that the above .clear() is no longer necessary since effectChains
4262 // is now local to this block, but will keep it for now (at least until merge done).
4263 }
4264
Eric Laurentbfb1b832013-01-07 09:53:42 -08004265 threadLoop_exit();
4266
Eric Laurentcf817a22014-08-04 20:36:31 -07004267 if (!mStandby) {
4268 threadLoop_standby();
4269 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004270 }
4271
4272 releaseWakeLock();
4273
4274 ALOGV("Thread %p type %d exiting", this, mType);
4275 return false;
4276}
4277
Dean Wheatley12473e92021-03-18 23:00:55 +11004278void AudioFlinger::PlaybackThread::collectTimestamps_l()
4279{
4280 // Collect timestamp statistics for the Playback Thread types that support it.
4281 if (mType != MIXER
4282 && mType != DUPLICATING
4283 && mType != DIRECT
4284 && mType != OFFLOAD) {
4285 return;
4286 }
4287 if (mStandby) {
4288 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4289 return;
4290 } else if (mHwPaused) {
4291 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4292 return;
4293 }
4294
4295 // Gather the framesReleased counters for all active tracks,
4296 // and associate with the sink frames written out. We need
4297 // this to convert the sink timestamp to the track timestamp.
4298 bool kernelLocationUpdate = false;
4299 ExtendedTimestamp timestamp; // use private copy to fetch
4300
4301 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4302 // HAL may be draining some small duration buffered data for fade out.
4303 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4304 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4305 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4306 mSampleRate);
4307
4308 if (isTimestampCorrectionEnabled()) {
4309 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4310 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4311 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4312 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4313 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4314 = correctedTimestamp.mFrames;
4315 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4316 = correctedTimestamp.mTimeNs;
4317 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4318 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4319 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4320
4321 // Note: Downstream latency only added if timestamp correction enabled.
4322 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4323 const int64_t newPosition =
4324 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4325 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4326 // prevent retrograde
4327 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4328 newPosition,
4329 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4330 - mSuspendedFrames));
4331 }
4332 }
4333
4334 // We always fetch the timestamp here because often the downstream
4335 // sink will block while writing.
4336
4337 // We keep track of the last valid kernel position in case we are in underrun
4338 // and the normal mixer period is the same as the fast mixer period, or there
4339 // is some error from the HAL.
4340 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4341 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4342 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4343 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4344 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4345
4346 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4347 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4348 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4349 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4350 }
4351
4352 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4353 kernelLocationUpdate = true;
4354 } else {
4355 ALOGVV("getTimestamp error - no valid kernel position");
4356 }
4357
4358 // copy over kernel info
4359 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4360 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4361 + mSuspendedFrames; // add frames discarded when suspended
4362 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4363 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4364 } else {
4365 mTimestampVerifier.error();
4366 }
4367
4368 // mFramesWritten for non-offloaded tracks are contiguous
4369 // even after standby() is called. This is useful for the track frame
4370 // to sink frame mapping.
4371 bool serverLocationUpdate = false;
4372 if (mFramesWritten != mLastFramesWritten) {
4373 serverLocationUpdate = true;
4374 mLastFramesWritten = mFramesWritten;
4375 }
4376 // Only update timestamps if there is a meaningful change.
4377 // Either the kernel timestamp must be valid or we have written something.
4378 if (kernelLocationUpdate || serverLocationUpdate) {
4379 if (serverLocationUpdate) {
4380 // use the time before we called the HAL write - it is a bit more accurate
4381 // to when the server last read data than the current time here.
4382 //
4383 // If we haven't written anything, mLastIoBeginNs will be -1
4384 // and we use systemTime().
4385 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4386 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4387 ? systemTime() : mLastIoBeginNs;
4388 }
4389
4390 for (const sp<Track> &t : mActiveTracks) {
4391 if (!t->isFastTrack()) {
4392 t->updateTrackFrameInfo(
4393 t->mAudioTrackServerProxy->framesReleased(),
4394 mFramesWritten,
4395 mSampleRate,
4396 mTimestamp);
4397 }
4398 }
4399 }
4400
4401 if (audio_has_proportional_frames(mFormat)) {
4402 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4403 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4404 mLatencyMs.add(latencyMs);
4405 }
4406 }
4407#if 0
4408 // logFormat example
4409 if (z % 100 == 0) {
4410 timespec ts;
4411 clock_gettime(CLOCK_MONOTONIC, &ts);
4412 LOGT("This is an integer %d, this is a float %f, this is my "
4413 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4414 LOGT("A deceptive null-terminated string %\0");
4415 }
4416 ++z;
4417#endif
4418}
4419
Eric Laurentbfb1b832013-01-07 09:53:42 -08004420// removeTracks_l() must be called with ThreadBase::mLock held
4421void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4422{
Andy Hungfe726a62018-09-27 15:17:25 -07004423 for (const auto& track : tracksToRemove) {
4424 mActiveTracks.remove(track);
4425 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4426 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4427 if (chain != 0) {
4428 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4429 __func__, track->id(), chain.get(), track->sessionId());
4430 chain->decActiveTrackCnt();
4431 }
4432 // If an external client track, inform APM we're no longer active, and remove if needed.
4433 // We do this under lock so that the state is consistent if the Track is destroyed.
4434 if (track->isExternalTrack()) {
4435 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004436 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004437 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004438 }
4439 }
Andy Hungfe726a62018-09-27 15:17:25 -07004440 if (track->isTerminated()) {
4441 // remove from our tracks vector
4442 removeTrack_l(track);
4443 }
jiabineb3bda02020-06-30 14:07:03 -07004444 if (mHapticChannelCount > 0 &&
4445 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4446 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004447 mLock.unlock();
4448 // Unlock due to VibratorService will lock for this call and will
4449 // call Tracks.mute/unmute which also require thread's lock.
4450 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4451 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004452
4453 // When the track is stop, set the haptic intensity as MUTE
4454 // for the HapticGenerator effect.
4455 if (chain != nullptr) {
4456 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4457 }
jiabin245cdd92018-12-07 17:55:15 -08004458 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004459 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004460}
Eric Laurent81784c32012-11-19 14:55:58 -08004461
Eric Laurentaccc1472013-09-20 09:36:34 -07004462status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4463{
4464 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004465 ExtendedTimestamp ets;
4466 status_t status = mNormalSink->getTimestamp(ets);
4467 if (status == NO_ERROR) {
4468 status = ets.getBestTimestamp(&timestamp);
4469 }
4470 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004471 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004472 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004473 collectTimestamps_l();
4474 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4475 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004476 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004477 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4478 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4479 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4480 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4481 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004482 }
4483 return INVALID_OPERATION;
4484}
Eric Laurent1c333e22014-05-20 10:48:17 -07004485
Eric Laurenteab90452019-06-24 15:17:46 -07004486// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4487// still applied by the mixer.
4488// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4489// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4490// if more than one track are active
4491status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4492{
4493 status_t result = NO_ERROR;
4494 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4495 if (*volume != mLeftVolFloat) {
4496 result = mOutput->stream->setVolume(*volume, *volume);
4497 ALOGE_IF(result != OK,
4498 "Error when setting output stream volume: %d", result);
4499 if (result == NO_ERROR) {
4500 mLeftVolFloat = *volume;
4501 }
4502 }
4503 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4504 // remove stream volume contribution from software volume.
4505 if (mLeftVolFloat == *volume) {
4506 *volume = 1.0f;
4507 }
4508 }
4509 return result;
4510}
4511
Eric Laurent054d9d32015-04-24 08:48:48 -07004512status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4513 audio_patch_handle_t *handle)
4514{
Andy Hungf60abce2016-08-26 11:37:54 -07004515 status_t status;
4516 if (property_get_bool("af.patch_park", false /* default_value */)) {
4517 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4518 // or if HAL does not properly lock against access.
4519 AutoPark<FastMixer> park(mFastMixer);
4520 status = PlaybackThread::createAudioPatch_l(patch, handle);
4521 } else {
4522 status = PlaybackThread::createAudioPatch_l(patch, handle);
4523 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004524 return status;
4525}
4526
Eric Laurent1c333e22014-05-20 10:48:17 -07004527status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4528 audio_patch_handle_t *handle)
4529{
4530 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004531
4532 // store new device and send to effects
4533 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004534 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004535 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004536 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4537 && !mOutput->audioHwDev->supportsAudioPatches(),
4538 "Enumerated device type(%#x) must not be used "
4539 "as it does not support audio patches",
4540 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004541 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004542 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4543 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004544 }
4545
François Gaffie0c280aa2018-07-25 10:02:15 +02004546 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004547#ifdef ADD_BATTERY_DATA
4548 // when changing the audio output device, call addBatteryData to notify
4549 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004550 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004551 uint32_t params = 0;
4552 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004553 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004554 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004555 }
4556
Eric Laurent054d9d32015-04-24 08:48:48 -07004557 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004558 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004559 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4560 }
4561
4562 if (params != 0) {
4563 addBatteryData(params);
4564 }
4565 }
4566#endif
4567
4568 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004569 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004570 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004571
jiabinc52b1ff2019-10-31 17:20:42 -07004572 // mPatch.num_sinks is not set when the thread is created so that
4573 // the first patch creation triggers an ioConfigChanged callback
4574 bool configChanged = (mPatch.num_sinks == 0) ||
4575 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004576 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004577 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004578 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004579
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004580 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004581 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4582 status = hwDevice->createAudioPatch(patch->num_sources,
4583 patch->sources,
4584 patch->num_sinks,
4585 patch->sinks,
4586 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004587 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004588 char *address;
4589 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4590 //FIXME: we only support address on first sink with HAL version < 3.0
4591 address = audio_device_address_to_parameter(
4592 patch->sinks[0].ext.device.type,
4593 patch->sinks[0].ext.device.address);
4594 } else {
4595 address = (char *)calloc(1, 1);
4596 }
4597 AudioParameter param = AudioParameter(String8(address));
4598 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004599 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004600 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004601 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004602 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004603 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004604
4605 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004606 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004607 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004608 // also dispatch to active AudioTracks for MediaMetrics
4609 for (const auto &track : mActiveTracks) {
4610 track->logEndInterval();
4611 track->logBeginInterval(patchSinksAsString);
4612 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004613
Eric Laurente8726fe2015-06-26 09:39:24 -07004614 if (configChanged) {
4615 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4616 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004617 return status;
4618}
4619
Eric Laurent054d9d32015-04-24 08:48:48 -07004620status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4621{
Andy Hungf60abce2016-08-26 11:37:54 -07004622 status_t status;
4623 if (property_get_bool("af.patch_park", false /* default_value */)) {
4624 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4625 // or if HAL does not properly lock against access.
4626 AutoPark<FastMixer> park(mFastMixer);
4627 status = PlaybackThread::releaseAudioPatch_l(handle);
4628 } else {
4629 status = PlaybackThread::releaseAudioPatch_l(handle);
4630 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004631 return status;
4632}
4633
Eric Laurent1c333e22014-05-20 10:48:17 -07004634status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4635{
4636 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004637
jiabinc52b1ff2019-10-31 17:20:42 -07004638 mPatch = audio_patch{};
4639 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004640
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004641 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004642 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4643 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004644 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004645 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004646 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004647 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004648 }
4649 return status;
4650}
4651
Eric Laurent83b88082014-06-20 18:31:16 -07004652void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4653{
4654 Mutex::Autolock _l(mLock);
4655 mTracks.add(track);
4656}
4657
4658void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4659{
4660 Mutex::Autolock _l(mLock);
4661 destroyTrack_l(track);
4662}
4663
Mikhail Naganovdc769682018-05-04 15:34:08 -07004664void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004665{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004666 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004667 config->role = AUDIO_PORT_ROLE_SOURCE;
4668 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4669 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004670 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4671 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4672 config->flags.output = mOutput->flags;
4673 }
Eric Laurent83b88082014-06-20 18:31:16 -07004674}
4675
Eric Laurent81784c32012-11-19 14:55:58 -08004676// ----------------------------------------------------------------------------
4677
4678AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004679 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4680 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004681 // mAudioMixer below
4682 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004683 mFastMixerFutex(0),
4684 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004685 // mOutputSink below
4686 // mPipeSink below
4687 // mNormalSink below
4688{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004689 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004690 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004691 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004692 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004693 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4694 mNormalFrameCount);
4695 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4696
Andy Hungfbfc3952015-01-15 13:33:51 -08004697 if (type == DUPLICATING) {
4698 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4699 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4700 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4701 return;
4702 }
Eric Laurent81784c32012-11-19 14:55:58 -08004703 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004704 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004705 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004706 const NBAIO_Format offers[1] = {Format_from_SR_C(
4707 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004708#if !LOG_NDEBUG
4709 ssize_t index =
4710#else
4711 (void)
4712#endif
4713 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004714 ALOG_ASSERT(index == 0);
4715
4716 // initialize fast mixer depending on configuration
4717 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004718 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004719 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004720 } else {
4721 switch (kUseFastMixer) {
4722 case FastMixer_Never:
4723 initFastMixer = false;
4724 break;
4725 case FastMixer_Always:
4726 initFastMixer = true;
4727 break;
4728 case FastMixer_Static:
4729 case FastMixer_Dynamic:
4730 initFastMixer = mFrameCount < mNormalFrameCount;
4731 break;
4732 }
4733 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4734 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4735 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004736 }
4737 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004738 audio_format_t fastMixerFormat;
4739 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4740 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4741 } else {
4742 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4743 }
4744 if (mFormat != fastMixerFormat) {
4745 // change our Sink format to accept our intermediate precision
4746 mFormat = fastMixerFormat;
4747 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004748 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004749 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4750 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4751 }
Eric Laurent81784c32012-11-19 14:55:58 -08004752
4753 // create a MonoPipe to connect our submix to FastMixer
4754 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004755
Andy Hung1258c1a2014-05-23 21:22:17 -07004756 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004757 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004758 format.mFormat = fastMixerFormat;
4759 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4760
Eric Laurent81784c32012-11-19 14:55:58 -08004761 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4762 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4763 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4764 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4765 const NBAIO_Format offers[1] = {format};
4766 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004767#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004768 ssize_t index =
4769#else
4770 (void)
4771#endif
4772 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004773 ALOG_ASSERT(index == 0);
4774 monoPipe->setAvgFrames((mScreenState & 1) ?
4775 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4776 mPipeSink = monoPipe;
4777
Eric Laurent81784c32012-11-19 14:55:58 -08004778 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004779 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004780 FastMixerStateQueue *sq = mFastMixer->sq();
4781#ifdef STATE_QUEUE_DUMP
4782 sq->setObserverDump(&mStateQueueObserverDump);
4783 sq->setMutatorDump(&mStateQueueMutatorDump);
4784#endif
4785 FastMixerState *state = sq->begin();
4786 FastTrack *fastTrack = &state->mFastTracks[0];
4787 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4788 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4789 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004790 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4791 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4792 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004793 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004794 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004795 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004796 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004797 fastTrack->mGeneration++;
4798 state->mFastTracksGen++;
4799 state->mTrackMask = 1;
4800 // fast mixer will use the HAL output sink
4801 state->mOutputSink = mOutputSink.get();
4802 state->mOutputSinkGen++;
4803 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004804 // specify sink channel mask when haptic channel mask present as it can not
4805 // be calculated directly from channel count
4806 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004807 ? AUDIO_CHANNEL_NONE
4808 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004809 state->mCommand = FastMixerState::COLD_IDLE;
4810 // already done in constructor initialization list
4811 //mFastMixerFutex = 0;
4812 state->mColdFutexAddr = &mFastMixerFutex;
4813 state->mColdGen++;
4814 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004815 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4816 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004817 sq->end();
4818 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4819
Eric Tan0513b5d2018-09-17 10:32:48 -07004820 NBLog::thread_info_t info;
4821 info.id = mId;
4822 info.type = NBLog::FASTMIXER;
4823 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4824
Eric Laurent81784c32012-11-19 14:55:58 -08004825 // start the fast mixer
4826 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4827 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004828 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004829 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004830
4831#ifdef AUDIO_WATCHDOG
4832 // create and start the watchdog
4833 mAudioWatchdog = new AudioWatchdog();
4834 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4835 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4836 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004837 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004838#endif
Andy Hung8946a282018-04-19 20:04:56 -07004839 } else {
4840#ifdef TEE_SINK
4841 // Only use the MixerThread tee if there is no FastMixer.
4842 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4843 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4844#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004845 }
4846
4847 switch (kUseFastMixer) {
4848 case FastMixer_Never:
4849 case FastMixer_Dynamic:
4850 mNormalSink = mOutputSink;
4851 break;
4852 case FastMixer_Always:
4853 mNormalSink = mPipeSink;
4854 break;
4855 case FastMixer_Static:
4856 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4857 break;
4858 }
4859}
4860
4861AudioFlinger::MixerThread::~MixerThread()
4862{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004863 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004864 FastMixerStateQueue *sq = mFastMixer->sq();
4865 FastMixerState *state = sq->begin();
4866 if (state->mCommand == FastMixerState::COLD_IDLE) {
4867 int32_t old = android_atomic_inc(&mFastMixerFutex);
4868 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004869 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004870 }
4871 }
4872 state->mCommand = FastMixerState::EXIT;
4873 sq->end();
4874 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4875 mFastMixer->join();
4876 // Though the fast mixer thread has exited, it's state queue is still valid.
4877 // We'll use that extract the final state which contains one remaining fast track
4878 // corresponding to our sub-mix.
4879 state = sq->begin();
4880 ALOG_ASSERT(state->mTrackMask == 1);
4881 FastTrack *fastTrack = &state->mFastTracks[0];
4882 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4883 delete fastTrack->mBufferProvider;
4884 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004885 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004886#ifdef AUDIO_WATCHDOG
4887 if (mAudioWatchdog != 0) {
4888 mAudioWatchdog->requestExit();
4889 mAudioWatchdog->requestExitAndWait();
4890 mAudioWatchdog.clear();
4891 }
4892#endif
4893 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004894 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004895 delete mAudioMixer;
4896}
4897
4898
4899uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4900{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004901 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004902 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4903 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4904 }
4905 return latency;
4906}
4907
Eric Laurentbfb1b832013-01-07 09:53:42 -08004908ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004909{
4910 // FIXME we should only do one push per cycle; confirm this is true
4911 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004912 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004913 FastMixerStateQueue *sq = mFastMixer->sq();
4914 FastMixerState *state = sq->begin();
4915 if (state->mCommand != FastMixerState::MIX_WRITE &&
4916 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4917 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004918
4919 // FIXME workaround for first HAL write being CPU bound on some devices
4920 ATRACE_BEGIN("write");
4921 mOutput->write((char *)mSinkBuffer, 0);
4922 ATRACE_END();
4923
Eric Laurent81784c32012-11-19 14:55:58 -08004924 int32_t old = android_atomic_inc(&mFastMixerFutex);
4925 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004926 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004927 }
4928#ifdef AUDIO_WATCHDOG
4929 if (mAudioWatchdog != 0) {
4930 mAudioWatchdog->resume();
4931 }
4932#endif
4933 }
4934 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004935#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004936 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004937 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004938#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004939 sq->end();
4940 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4941 if (kUseFastMixer == FastMixer_Dynamic) {
4942 mNormalSink = mPipeSink;
4943 }
4944 } else {
4945 sq->end(false /*didModify*/);
4946 }
4947 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004948 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004949}
4950
4951void AudioFlinger::MixerThread::threadLoop_standby()
4952{
4953 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004954 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004955 FastMixerStateQueue *sq = mFastMixer->sq();
4956 FastMixerState *state = sq->begin();
4957 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004958 // Report any frames trapped in the Monopipe
4959 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4960 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4961 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4962 "monoPipeWritten:%lld monoPipeLeft:%lld",
4963 (long long)mFramesWritten, (long long)mSuspendedFrames,
4964 (long long)mPipeSink->framesWritten(), pipeFrames);
4965 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4966
Eric Laurent81784c32012-11-19 14:55:58 -08004967 state->mCommand = FastMixerState::COLD_IDLE;
4968 state->mColdFutexAddr = &mFastMixerFutex;
4969 state->mColdGen++;
4970 mFastMixerFutex = 0;
4971 sq->end();
4972 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4973 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4974 if (kUseFastMixer == FastMixer_Dynamic) {
4975 mNormalSink = mOutputSink;
4976 }
4977#ifdef AUDIO_WATCHDOG
4978 if (mAudioWatchdog != 0) {
4979 mAudioWatchdog->pause();
4980 }
4981#endif
4982 } else {
4983 sq->end(false /*didModify*/);
4984 }
4985 }
4986 PlaybackThread::threadLoop_standby();
4987}
4988
Eric Laurentbfb1b832013-01-07 09:53:42 -08004989bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4990{
4991 return false;
4992}
4993
4994bool AudioFlinger::PlaybackThread::shouldStandby_l()
4995{
4996 return !mStandby;
4997}
4998
4999bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5000{
5001 Mutex::Autolock _l(mLock);
5002 return waitingAsyncCallback_l();
5003}
5004
Eric Laurent81784c32012-11-19 14:55:58 -08005005// shared by MIXER and DIRECT, overridden by DUPLICATING
5006void AudioFlinger::PlaybackThread::threadLoop_standby()
5007{
5008 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005009 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005010 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005011 // discard any pending drain or write ack by incrementing sequence
5012 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5013 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005014 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005015 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5016 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005017 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005018 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005019}
5020
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005021void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5022{
5023 ALOGV("signal playback thread");
5024 broadcast_l();
5025}
5026
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005027void AudioFlinger::PlaybackThread::onAsyncError()
5028{
5029 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5030 invalidateTracks((audio_stream_type_t)i);
5031 }
5032}
5033
Eric Laurent81784c32012-11-19 14:55:58 -08005034void AudioFlinger::MixerThread::threadLoop_mix()
5035{
Eric Laurent81784c32012-11-19 14:55:58 -08005036 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005037 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005038 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005039 // increase sleep time progressively when application underrun condition clears.
5040 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5041 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5042 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005043 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005044 sleepTimeShift--;
5045 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005046 mSleepTimeUs = 0;
5047 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005048 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005049
Eric Laurent81784c32012-11-19 14:55:58 -08005050}
5051
5052void AudioFlinger::MixerThread::threadLoop_sleepTime()
5053{
5054 // If no tracks are ready, sleep once for the duration of an output
5055 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005056 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005057 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005058 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5059 // Using the Monopipe availableToWrite, we estimate the
5060 // sleep time to retry for more data (before we underrun).
5061 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5062 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5063 const size_t pipeFrames = monoPipe->maxFrames();
5064 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5065 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5066 const size_t framesDelay = std::min(
5067 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5068 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5069 pipeFrames, framesLeft, framesDelay);
5070 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5071 } else {
5072 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5073 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5074 mSleepTimeUs = kMinThreadSleepTimeUs;
5075 }
5076 // reduce sleep time in case of consecutive application underruns to avoid
5077 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5078 // duration we would end up writing less data than needed by the audio HAL if
5079 // the condition persists.
5080 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5081 sleepTimeShift++;
5082 }
Eric Laurent81784c32012-11-19 14:55:58 -08005083 }
5084 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005085 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005086 }
5087 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005088 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5089 // before effects processing or output.
5090 if (mMixerBufferValid) {
5091 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005092 if (mType == SPATIALIZER) {
5093 memset(mSinkBuffer, 0, mSinkBufferSize);
5094 }
Andy Hung98ef9782014-03-04 14:46:50 -08005095 } else {
5096 memset(mSinkBuffer, 0, mSinkBufferSize);
5097 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005098 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005099 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5100 "anticipated start");
5101 }
5102 // TODO add standby time extension fct of effect tail
5103}
5104
5105// prepareTracks_l() must be called with ThreadBase::mLock held
5106AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5107 Vector< sp<Track> > *tracksToRemove)
5108{
Andy Hungc0691382018-09-12 18:01:57 -07005109 // clean up deleted track ids in AudioMixer before allocating new tracks
5110 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5111 // for each trackId, destroy it in the AudioMixer
5112 if (mAudioMixer->exists(trackId)) {
5113 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005114 }
5115 });
Andy Hungc0691382018-09-12 18:01:57 -07005116 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005117
5118 mixer_state mixerStatus = MIXER_IDLE;
5119 // find out which tracks need to be processed
5120 size_t count = mActiveTracks.size();
5121 size_t mixedTracks = 0;
5122 size_t tracksWithEffect = 0;
5123 // counts only _active_ fast tracks
5124 size_t fastTracks = 0;
5125 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5126
5127 float masterVolume = mMasterVolume;
5128 bool masterMute = mMasterMute;
5129
5130 if (masterMute) {
5131 masterVolume = 0;
5132 }
5133 // Delegate master volume control to effect in output mix effect chain if needed
5134 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5135 if (chain != 0) {
5136 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5137 chain->setVolume_l(&v, &v);
5138 masterVolume = (float)((v + (1 << 23)) >> 24);
5139 chain.clear();
5140 }
5141
5142 // prepare a new state to push
5143 FastMixerStateQueue *sq = NULL;
5144 FastMixerState *state = NULL;
5145 bool didModify = false;
5146 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005147 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005148 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005149 sq = mFastMixer->sq();
5150 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005151 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005152 }
5153
Andy Hung69aed5f2014-02-25 17:24:40 -08005154 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005155 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005156
Andy Hungbd3b2b02018-05-21 10:53:11 -07005157 // DeferredOperations handles statistics after setting mixerStatus.
5158 class DeferredOperations {
5159 public:
Andy Hungea840382020-05-05 21:50:17 -07005160 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5161 : mMixerStatus(mixerStatus)
5162 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005163
5164 // when leaving scope, tally frames properly.
5165 ~DeferredOperations() {
5166 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5167 // because that is when the underrun occurs.
5168 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005169 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005170 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005171 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005172 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005173 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005174 }
5175 }
Andy Hungea840382020-05-05 21:50:17 -07005176 // send the max underrun frames for this mixer period
5177 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005178 }
5179
5180 // tallyUnderrunFrames() is called to update the track counters
5181 // with the number of underrun frames for a particular mixer period.
5182 // We defer tallying until we know the final mixer status.
5183 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5184 mUnderrunFrames.emplace_back(track, underrunFrames);
5185 }
5186
5187 private:
5188 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005189 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005190 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005191 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005192 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005193
jiabin245cdd92018-12-07 17:55:15 -08005194 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005195 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005196 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005197
5198 // this const just means the local variable doesn't change
5199 Track* const track = t.get();
5200
5201 // process fast tracks
5202 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005203 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5204 "%s(%d): FastTrack(%d) present without FastMixer",
5205 __func__, id(), track->id());
5206
jiabin245cdd92018-12-07 17:55:15 -08005207 if (track->getHapticPlaybackEnabled()) {
5208 noFastHapticTrack = false;
5209 }
Eric Laurent81784c32012-11-19 14:55:58 -08005210
5211 // It's theoretically possible (though unlikely) for a fast track to be created
5212 // and then removed within the same normal mix cycle. This is not a problem, as
5213 // the track never becomes active so it's fast mixer slot is never touched.
5214 // The converse, of removing an (active) track and then creating a new track
5215 // at the identical fast mixer slot within the same normal mix cycle,
5216 // is impossible because the slot isn't marked available until the end of each cycle.
5217 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005218 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005219 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5220 FastTrack *fastTrack = &state->mFastTracks[j];
5221
5222 // Determine whether the track is currently in underrun condition,
5223 // and whether it had a recent underrun.
5224 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5225 FastTrackUnderruns underruns = ftDump->mUnderruns;
5226 uint32_t recentFull = (underruns.mBitFields.mFull -
5227 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5228 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5229 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5230 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5231 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5232 uint32_t recentUnderruns = recentPartial + recentEmpty;
5233 track->mObservedUnderruns = underruns;
5234 // don't count underruns that occur while stopping or pausing
5235 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005236 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005237 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5238 recentUnderruns > 0) {
5239 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005240 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005241 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005242 // Immediately account for FastTrack underruns.
5243 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005244
5245 // This is similar to the state machine for normal tracks,
5246 // with a few modifications for fast tracks.
5247 bool isActive = true;
5248 switch (track->mState) {
5249 case TrackBase::STOPPING_1:
5250 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005251 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005252 track->mState = TrackBase::STOPPING_2;
5253 }
5254 break;
5255 case TrackBase::PAUSING:
5256 // ramp down is not yet implemented
5257 track->setPaused();
5258 break;
5259 case TrackBase::RESUMING:
5260 // ramp up is not yet implemented
5261 track->mState = TrackBase::ACTIVE;
5262 break;
5263 case TrackBase::ACTIVE:
5264 if (recentFull > 0 || recentPartial > 0) {
5265 // track has provided at least some frames recently: reset retry count
5266 track->mRetryCount = kMaxTrackRetries;
5267 }
5268 if (recentUnderruns == 0) {
5269 // no recent underruns: stay active
5270 break;
5271 }
5272 // there has recently been an underrun of some kind
5273 if (track->sharedBuffer() == 0) {
5274 // were any of the recent underruns "empty" (no frames available)?
5275 if (recentEmpty == 0) {
5276 // no, then ignore the partial underruns as they are allowed indefinitely
5277 break;
5278 }
5279 // there has recently been an "empty" underrun: decrement the retry counter
5280 if (--(track->mRetryCount) > 0) {
5281 break;
5282 }
5283 // indicate to client process that the track was disabled because of underrun;
5284 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005285 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005286 // remove from active list, but state remains ACTIVE [confusing but true]
5287 isActive = false;
5288 break;
5289 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005290 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005291 case TrackBase::STOPPING_2:
5292 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005293 case TrackBase::STOPPED:
5294 case TrackBase::FLUSHED: // flush() while active
5295 // Check for presentation complete if track is inactive
5296 // We have consumed all the buffers of this track.
5297 // This would be incomplete if we auto-paused on underrun
5298 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005299 uint32_t latency = 0;
5300 status_t result = mOutput->stream->getLatency(&latency);
5301 ALOGE_IF(result != OK,
5302 "Error when retrieving output stream latency: %d", result);
5303 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005304 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005305 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5306 // track stays in active list until presentation is complete
5307 break;
5308 }
5309 }
5310 if (track->isStopping_2()) {
5311 track->mState = TrackBase::STOPPED;
5312 }
5313 if (track->isStopped()) {
5314 // Can't reset directly, as fast mixer is still polling this track
5315 // track->reset();
5316 // So instead mark this track as needing to be reset after push with ack
5317 resetMask |= 1 << i;
5318 }
5319 isActive = false;
5320 break;
5321 case TrackBase::IDLE:
5322 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005323 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005324 }
5325
5326 if (isActive) {
5327 // was it previously inactive?
5328 if (!(state->mTrackMask & (1 << j))) {
5329 ExtendedAudioBufferProvider *eabp = track;
5330 VolumeProvider *vp = track;
5331 fastTrack->mBufferProvider = eabp;
5332 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005333 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005334 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005335 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005336 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005337 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005338 fastTrack->mGeneration++;
5339 state->mTrackMask |= 1 << j;
5340 didModify = true;
5341 // no acknowledgement required for newly active tracks
5342 }
Kevin Rocard12381092018-04-11 09:19:59 -07005343 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005344 float volume;
5345 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5346 volume = 0.f;
5347 } else {
5348 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5349 }
5350
5351 handleVoipVolume_l(&volume);
5352
Eric Laurent81784c32012-11-19 14:55:58 -08005353 // cache the combined master volume and stream type volume for fast mixer; this
5354 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005355 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005356 proxy->framesReleased()).first;
5357 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005358 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005359 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5360 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5361 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005362
Kevin Rocard12381092018-04-11 09:19:59 -07005363 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005364 ++fastTracks;
5365 } else {
5366 // was it previously active?
5367 if (state->mTrackMask & (1 << j)) {
5368 fastTrack->mBufferProvider = NULL;
5369 fastTrack->mGeneration++;
5370 state->mTrackMask &= ~(1 << j);
5371 didModify = true;
5372 // If any fast tracks were removed, we must wait for acknowledgement
5373 // because we're about to decrement the last sp<> on those tracks.
5374 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5375 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005376 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5377 // AudioTrack may start (which may not be with a start() but with a write()
5378 // after underrun) and immediately paused or released. In that case the
5379 // FastTrack state hasn't had time to update.
5380 // TODO Remove the ALOGW when this theory is confirmed.
5381 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005382 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005383 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005384 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005385 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005386 }
5387 tracksToRemove->add(track);
5388 // Avoids a misleading display in dumpsys
5389 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5390 }
jiabin245cdd92018-12-07 17:55:15 -08005391 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5392 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5393 didModify = true;
5394 }
Eric Laurent81784c32012-11-19 14:55:58 -08005395 continue;
5396 }
5397
5398 { // local variable scope to avoid goto warning
5399
5400 audio_track_cblk_t* cblk = track->cblk();
5401
5402 // The first time a track is added we wait
5403 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005404 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005405
5406 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005407 // use the trackId as the AudioMixer name.
5408 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005409 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005410 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005411 track->mChannelMask,
5412 track->mFormat,
5413 track->mSessionId);
5414 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005415 ALOGW("%s(): AudioMixer cannot create track(%d)"
5416 " mask %#x, format %#x, sessionId %d",
5417 __func__, trackId,
5418 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005419 tracksToRemove->add(track);
5420 track->invalidate(); // consider it dead.
5421 continue;
5422 }
5423 }
5424
Eric Laurent81784c32012-11-19 14:55:58 -08005425 // make sure that we have enough frames to mix one full buffer.
5426 // enforce this condition only once to enable draining the buffer in case the client
5427 // app does not call stop() and relies on underrun to stop:
5428 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5429 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005430 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005431 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005432 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005433
5434 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005435 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005436 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5437 // add frames already consumed but not yet released by the resampler
5438 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005439 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005440
Eric Laurent81784c32012-11-19 14:55:58 -08005441 uint32_t minFrames = 1;
5442 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5443 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005444 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005445 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005446
5447 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005448 if (ATRACE_ENABLED()) {
5449 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005450 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005451 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005452 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005453 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005454 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005455 !track->isPaused() && !track->isTerminated())
5456 {
Andy Hungc0691382018-09-12 18:01:57 -07005457 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005458
5459 mixedTracks++;
5460
Andy Hung69aed5f2014-02-25 17:24:40 -08005461 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5462 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005463 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005464 if (track->mainBuffer() != mSinkBuffer &&
5465 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005466 if (mEffectBufferEnabled) {
5467 mEffectBufferValid = true; // Later can set directly.
5468 }
Eric Laurent81784c32012-11-19 14:55:58 -08005469 chain = getEffectChain_l(track->sessionId());
5470 // Delegate volume control to effect in track effect chain if needed
5471 if (chain != 0) {
5472 tracksWithEffect++;
5473 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005474 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005475 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005476 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005477 }
5478 }
5479
5480
5481 int param = AudioMixer::VOLUME;
5482 if (track->mFillingUpStatus == Track::FS_FILLED) {
5483 // no ramp for the first volume setting
5484 track->mFillingUpStatus = Track::FS_ACTIVE;
5485 if (track->mState == TrackBase::RESUMING) {
5486 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005487 // If a new track is paused immediately after start, do not ramp on resume.
5488 if (cblk->mServer != 0) {
5489 param = AudioMixer::RAMP_VOLUME;
5490 }
Eric Laurent81784c32012-11-19 14:55:58 -08005491 }
Andy Hungc0691382018-09-12 18:01:57 -07005492 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005493 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005494 // FIXME should not make a decision based on mServer
5495 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005496 // If the track is stopped before the first frame was mixed,
5497 // do not apply ramp
5498 param = AudioMixer::RAMP_VOLUME;
5499 }
5500
5501 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005502 uint32_t vl, vr; // in U8.24 integer format
5503 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005504 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005505 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005506 // Always fetch volumeshaper volume to ensure state is updated.
5507 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5508 const float vh = track->getVolumeHandler()->getVolume(
5509 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005510
Eric Laurenteab90452019-06-24 15:17:46 -07005511 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5512 v = 0;
5513 }
5514
5515 handleVoipVolume_l(&v);
5516
5517 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005518 vl = vr = 0;
5519 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005520 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005521 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005522 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005523 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5524 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005525 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005526 if (vlf > GAIN_FLOAT_UNITY) {
5527 ALOGV("Track left volume out of range: %.3g", vlf);
5528 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005529 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005530 if (vrf > GAIN_FLOAT_UNITY) {
5531 ALOGV("Track right volume out of range: %.3g", vrf);
5532 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005533 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005534 // now apply the master volume and stream type volume and shaper volume
5535 vlf *= v * vh;
5536 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005537 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005538 // then derive vl and vr as U8.24 versions for the effect chain
5539 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5540 vl = (uint32_t) (scaleto8_24 * vlf);
5541 vr = (uint32_t) (scaleto8_24 * vrf);
5542 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005543 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005544 // send level comes from shared memory and so may be corrupt
5545 if (sendLevel > MAX_GAIN_INT) {
5546 ALOGV("Track send level out of range: %04X", sendLevel);
5547 sendLevel = MAX_GAIN_INT;
5548 }
Andy Hung6be49402014-05-30 10:42:03 -07005549 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5550 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005551 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005552
Kevin Rocard12381092018-04-11 09:19:59 -07005553 track->setFinalVolume((vrf + vlf) / 2.f);
5554
Eric Laurent81784c32012-11-19 14:55:58 -08005555 // Delegate volume control to effect in track effect chain if needed
5556 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5557 // Do not ramp volume if volume is controlled by effect
5558 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005559 // Update remaining floating point volume levels
5560 vlf = (float)vl / (1 << 24);
5561 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005562 track->mHasVolumeController = true;
5563 } else {
5564 // force no volume ramp when volume controller was just disabled or removed
5565 // from effect chain to avoid volume spike
5566 if (track->mHasVolumeController) {
5567 param = AudioMixer::VOLUME;
5568 }
5569 track->mHasVolumeController = false;
5570 }
5571
Eric Laurent81784c32012-11-19 14:55:58 -08005572 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005573 mAudioMixer->setBufferProvider(trackId, track);
5574 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005575
Andy Hungc0691382018-09-12 18:01:57 -07005576 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5577 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5578 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005579 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005580 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005581 AudioMixer::TRACK,
5582 AudioMixer::FORMAT, (void *)track->format());
5583 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005584 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005585 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005586 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005587
5588 if (mType == SPATIALIZER && !track->canBeSpatialized()) {
5589 mAudioMixer->setParameter(
5590 trackId,
5591 AudioMixer::TRACK,
5592 AudioMixer::MIXER_CHANNEL_MASK,
5593 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5594 } else {
5595 mAudioMixer->setParameter(
5596 trackId,
5597 AudioMixer::TRACK,
5598 AudioMixer::MIXER_CHANNEL_MASK,
5599 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5600 }
5601
Glenn Kastene3aa6592012-12-04 12:22:46 -08005602 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005603 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005604 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005605 if (reqSampleRate == 0) {
5606 reqSampleRate = mSampleRate;
5607 } else if (reqSampleRate > maxSampleRate) {
5608 reqSampleRate = maxSampleRate;
5609 }
Eric Laurent81784c32012-11-19 14:55:58 -08005610 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005611 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005612 AudioMixer::RESAMPLE,
5613 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005614 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005615
Andy Hung333ab962019-05-28 20:23:35 -07005616 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005617 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005618 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005619 AudioMixer::TIMESTRETCH,
5620 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005621 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005622
Andy Hung69aed5f2014-02-25 17:24:40 -08005623 /*
5624 * Select the appropriate output buffer for the track.
5625 *
Andy Hung98ef9782014-03-04 14:46:50 -08005626 * Tracks with effects go into their own effects chain buffer
5627 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005628 *
5629 * Other tracks can use mMixerBuffer for higher precision
5630 * channel accumulation. If this buffer is enabled
5631 * (mMixerBufferEnabled true), then selected tracks will accumulate
5632 * into it.
5633 *
5634 */
5635 if (mMixerBufferEnabled
5636 && (track->mainBuffer() == mSinkBuffer
5637 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurent39095982021-08-24 18:29:27 +02005638 if (mType == SPATIALIZER && !track->canBeSpatialized()) {
5639 mAudioMixer->setParameter(
5640 trackId,
5641 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005642 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005643 mAudioMixer->setParameter(
5644 trackId,
5645 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005646 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005647 } else {
5648 mAudioMixer->setParameter(
5649 trackId,
5650 AudioMixer::TRACK,
5651 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5652 mAudioMixer->setParameter(
5653 trackId,
5654 AudioMixer::TRACK,
5655 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5656 // TODO: override track->mainBuffer()?
5657 mMixerBufferValid = true;
5658 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005659 } else {
5660 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005661 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005662 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005663 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005664 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005665 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005666 AudioMixer::TRACK,
5667 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5668 }
Eric Laurent81784c32012-11-19 14:55:58 -08005669 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005670 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005671 AudioMixer::TRACK,
5672 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005673 mAudioMixer->setParameter(
5674 trackId,
5675 AudioMixer::TRACK,
5676 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005677 mAudioMixer->setParameter(
5678 trackId,
5679 AudioMixer::TRACK,
5680 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005681 mAudioMixer->setParameter(
5682 trackId,
5683 AudioMixer::TRACK,
5684 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005685
5686 // reset retry count
5687 track->mRetryCount = kMaxTrackRetries;
5688
5689 // If one track is ready, set the mixer ready if:
5690 // - the mixer was not ready during previous round OR
5691 // - no other track is not ready
5692 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5693 mixerStatus != MIXER_TRACKS_ENABLED) {
5694 mixerStatus = MIXER_TRACKS_READY;
5695 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005696
5697 // Enable the next few lines to instrument a test for underrun log handling.
5698 // TODO: Remove when we have a better way of testing the underrun log.
5699#if 0
5700 static int i;
5701 if ((++i & 0xf) == 0) {
5702 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5703 }
5704#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005705 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005706 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005707 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005708 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5709 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005710 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005711 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005712 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005713
Eric Laurent81784c32012-11-19 14:55:58 -08005714 // clear effect chain input buffer if an active track underruns to avoid sending
5715 // previous audio buffer again to effects
5716 chain = getEffectChain_l(track->sessionId());
5717 if (chain != 0) {
5718 chain->clearInputBuffer();
5719 }
5720
Andy Hungc0691382018-09-12 18:01:57 -07005721 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005722 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5723 track->isStopped() || track->isPaused()) {
5724 // We have consumed all the buffers of this track.
5725 // Remove it from the list of active tracks.
5726 // TODO: use actual buffer filling status instead of latency when available from
5727 // audio HAL
5728 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005729 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005730 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5731 if (track->isStopped()) {
5732 track->reset();
5733 }
5734 tracksToRemove->add(track);
5735 }
5736 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005737 // No buffers for this track. Give it a few chances to
5738 // fill a buffer, then remove it from active list.
5739 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005740 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5741 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005742 tracksToRemove->add(track);
5743 // indicate to client process that the track was disabled because of underrun;
5744 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005745 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005746 // If one track is not ready, mark the mixer also not ready if:
5747 // - the mixer was ready during previous round OR
5748 // - no other track is ready
5749 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5750 mixerStatus != MIXER_TRACKS_READY) {
5751 mixerStatus = MIXER_TRACKS_ENABLED;
5752 }
5753 }
Andy Hungc0691382018-09-12 18:01:57 -07005754 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005755 }
5756
5757 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005758
5759 }
5760
jiabin245cdd92018-12-07 17:55:15 -08005761 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5762 // When there is no fast track playing haptic and FastMixer exists,
5763 // enabling the first FastTrack, which provides mixed data from normal
5764 // tracks, to play haptic data.
5765 FastTrack *fastTrack = &state->mFastTracks[0];
5766 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5767 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5768 didModify = true;
5769 }
5770 }
5771
Eric Laurent81784c32012-11-19 14:55:58 -08005772 // Push the new FastMixer state if necessary
5773 bool pauseAudioWatchdog = false;
5774 if (didModify) {
5775 state->mFastTracksGen++;
5776 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5777 if (kUseFastMixer == FastMixer_Dynamic &&
5778 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5779 state->mCommand = FastMixerState::COLD_IDLE;
5780 state->mColdFutexAddr = &mFastMixerFutex;
5781 state->mColdGen++;
5782 mFastMixerFutex = 0;
5783 if (kUseFastMixer == FastMixer_Dynamic) {
5784 mNormalSink = mOutputSink;
5785 }
5786 // If we go into cold idle, need to wait for acknowledgement
5787 // so that fast mixer stops doing I/O.
5788 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5789 pauseAudioWatchdog = true;
5790 }
Eric Laurent81784c32012-11-19 14:55:58 -08005791 }
5792 if (sq != NULL) {
5793 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005794 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5795 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5796 // when bringing the output sink into standby.)
5797 //
5798 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5799 //
5800 // This occurs with BT suspend when we idle the FastMixer with
5801 // active tracks, which may be added or removed.
5802 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005803 }
5804#ifdef AUDIO_WATCHDOG
5805 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5806 mAudioWatchdog->pause();
5807 }
5808#endif
5809
5810 // Now perform the deferred reset on fast tracks that have stopped
5811 while (resetMask != 0) {
5812 size_t i = __builtin_ctz(resetMask);
5813 ALOG_ASSERT(i < count);
5814 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005815 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005816 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5817 track->reset();
5818 }
5819
Andy Hung80d03d22018-04-10 10:32:11 -07005820 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5821 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5822 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5823 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5824 // See also the implementation of destroyTrack_l().
5825 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005826 const int trackId = track->id();
5827 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5828 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005829 }
5830 }
5831
Eric Laurent81784c32012-11-19 14:55:58 -08005832 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005833 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005834
Eric Laurentb3f315a2021-07-13 15:09:05 +02005835 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5836 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005837 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005838 }
5839
5840 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005841 // as long as there are effects we should clear the effects buffer, to avoid
5842 // passing a non-clean buffer to the effect chain
5843 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005844 if (mType == SPATIALIZER) {
5845 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5846 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005847 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005848 // sink or mix buffer must be cleared if all tracks are connected to an
5849 // effect chain as in this case the mixer will not write to the sink or mix buffer
5850 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005851 // always clear sink buffer for spatializer output as the output of the spatializer
5852 // effect will be accumulated into it
5853 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5854 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005855 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005856 if (mMixerBufferValid) {
5857 memset(mMixerBuffer, 0, mMixerBufferSize);
5858 // TODO: In testing, mSinkBuffer below need not be cleared because
5859 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5860 // after mixing.
5861 //
5862 // To enforce this guarantee:
5863 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5864 // (mixedTracks == 0 && fastTracks > 0))
5865 // must imply MIXER_TRACKS_READY.
5866 // Later, we may clear buffers regardless, and skip much of this logic.
5867 }
Andy Hung98ef9782014-03-04 14:46:50 -08005868 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005869 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005870 }
5871
5872 // if any fast tracks, then status is ready
5873 mMixerStatusIgnoringFastTracks = mixerStatus;
5874 if (fastTracks > 0) {
5875 mixerStatus = MIXER_TRACKS_READY;
5876 }
5877 return mixerStatus;
5878}
5879
Eric Laurentad7dd962016-09-22 12:38:37 -07005880// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005881uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005882{
5883 uint32_t trackCount = 0;
5884 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005885 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005886 trackCount++;
5887 }
5888 }
5889 return trackCount;
5890}
5891
Andy Hung1bc088a2018-02-09 15:57:31 -08005892// isTrackAllowed_l() must be called with ThreadBase::mLock held
5893bool AudioFlinger::MixerThread::isTrackAllowed_l(
5894 audio_channel_mask_t channelMask, audio_format_t format,
5895 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005896{
Andy Hung1bc088a2018-02-09 15:57:31 -08005897 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5898 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005899 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005900 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005901 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005902 ALOGW("%s: invalid format: %#x", __func__, format);
5903 return false;
5904 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005905 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005906 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5907 return false;
5908 }
5909 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005910}
5911
Eric Laurent10351942014-05-08 18:49:52 -07005912// checkForNewParameter_l() must be called with ThreadBase::mLock held
5913bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5914 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005915{
Eric Laurent81784c32012-11-19 14:55:58 -08005916 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005917 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005918
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005919 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005920
Eric Laurent10351942014-05-08 18:49:52 -07005921 AudioParameter param = AudioParameter(keyValuePair);
5922 int value;
5923 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5924 reconfig = true;
5925 }
5926 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005927 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005928 status = BAD_VALUE;
5929 } else {
5930 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005931 reconfig = true;
5932 }
Eric Laurent10351942014-05-08 18:49:52 -07005933 }
5934 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005935 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005936 status = BAD_VALUE;
5937 } else {
5938 // no need to save value, since it's constant
5939 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005940 }
Eric Laurent10351942014-05-08 18:49:52 -07005941 }
5942 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5943 // do not accept frame count changes if tracks are open as the track buffer
5944 // size depends on frame count and correct behavior would not be guaranteed
5945 // if frame count is changed after track creation
5946 if (!mTracks.isEmpty()) {
5947 status = INVALID_OPERATION;
5948 } else {
5949 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005950 }
Eric Laurent10351942014-05-08 18:49:52 -07005951 }
5952 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005953 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005954 }
Eric Laurent81784c32012-11-19 14:55:58 -08005955
Eric Laurent10351942014-05-08 18:49:52 -07005956 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005957 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005958 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005959 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005960 if (!mStandby) {
5961 mThreadMetrics.logEndInterval();
5962 mStandby = true;
5963 }
Eric Laurent10351942014-05-08 18:49:52 -07005964 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005965 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005966 }
Eric Laurent10351942014-05-08 18:49:52 -07005967 if (status == NO_ERROR && reconfig) {
5968 readOutputParameters_l();
5969 delete mAudioMixer;
5970 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005971 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005972 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005973 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005974 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005975 track->mChannelMask,
5976 track->mFormat,
5977 track->mSessionId);
5978 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005979 "%s(): AudioMixer cannot create track(%d)"
5980 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005981 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005982 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005983 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005984 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005985 }
Eric Laurent81784c32012-11-19 14:55:58 -08005986 }
5987
Dean Wheatley68918102021-03-19 22:09:19 +11005988 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005989}
5990
5991
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005992void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005993{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005994 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005995 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005996 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005997 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005998 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5999 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6000 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006001 if (hasFastMixer()) {
6002 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6003
6004 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6005 // while we are dumping it. It may be inconsistent, but it won't mutate!
6006 // This is a large object so we place it on the heap.
6007 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006008 const std::unique_ptr<FastMixerDumpState> copy =
6009 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006010 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006011
6012#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006013 // Similar for state queue
6014 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6015 observerCopy.dump(fd);
6016 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6017 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006018#endif
6019
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006020#ifdef AUDIO_WATCHDOG
6021 if (mAudioWatchdog != 0) {
6022 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6023 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6024 wdCopy.dump(fd);
6025 }
6026#endif
6027
6028 } else {
6029 dprintf(fd, " No FastMixer\n");
6030 }
Eric Laurent81784c32012-11-19 14:55:58 -08006031}
6032
6033uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6034{
6035 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6036}
6037
6038uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6039{
6040 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6041}
6042
6043void AudioFlinger::MixerThread::cacheParameters_l()
6044{
6045 PlaybackThread::cacheParameters_l();
6046
6047 // FIXME: Relaxed timing because of a certain device that can't meet latency
6048 // Should be reduced to 2x after the vendor fixes the driver issue
6049 // increase threshold again due to low power audio mode. The way this warning
6050 // threshold is calculated and its usefulness should be reconsidered anyway.
6051 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6052}
6053
6054// ----------------------------------------------------------------------------
6055
6056AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006057 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
6058 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006059{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006060 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006061}
6062
Eric Laurent81784c32012-11-19 14:55:58 -08006063AudioFlinger::DirectOutputThread::~DirectOutputThread()
6064{
6065}
6066
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006067void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006068{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006069 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006070 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6071 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6072}
6073
6074void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6075{
6076 Mutex::Autolock _l(mLock);
6077 if (mMasterBalance != balance) {
6078 mMasterBalance.store(balance);
6079 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6080 broadcast_l();
6081 }
6082}
6083
Eric Laurent5850c4c2016-11-10 13:04:31 -08006084void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006085{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006086 float left, right;
6087
Andy Hung333ab962019-05-28 20:23:35 -07006088 // Ensure volumeshaper state always advances even when muted.
6089 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
6090 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
6091 proxy->framesReleased());
6092 mVolumeShaperActive = shaperActive;
6093
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006094 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006095 left = right = 0;
6096 } else {
6097 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006098 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006099
Glenn Kastenc56f3422014-03-21 17:53:17 -07006100 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6101 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6102 if (left > GAIN_FLOAT_UNITY) {
6103 left = GAIN_FLOAT_UNITY;
6104 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006105 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07006106 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6107 if (right > GAIN_FLOAT_UNITY) {
6108 right = GAIN_FLOAT_UNITY;
6109 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006110 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006111 }
6112
6113 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006114 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006115 if (left != mLeftVolFloat || right != mRightVolFloat) {
6116 mLeftVolFloat = left;
6117 mRightVolFloat = right;
6118
Eric Laurentbfb1b832013-01-07 09:53:42 -08006119 // Delegate volume control to effect in track effect chain if needed
6120 // only one effect chain can be present on DirectOutputThread, so if
6121 // there is one, the track is connected to it
6122 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006123 // if effect chain exists, volume is handled by it.
6124 // Convert volumes from float to 8.24
6125 uint32_t vl = (uint32_t)(left * (1 << 24));
6126 uint32_t vr = (uint32_t)(right * (1 << 24));
6127 // Direct/Offload effect chains set output volume in setVolume_l().
6128 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6129 } else {
6130 // otherwise we directly set the volume.
6131 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006132 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006133 }
6134 }
6135}
6136
Phil Burk43b4dcc2015-06-09 16:53:44 -07006137void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6138{
6139 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006140 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006141
Eric Laurent0f0631e2015-07-06 18:01:25 -07006142 if (previousTrack != 0 && latestTrack != 0) {
6143 if (mType == DIRECT) {
6144 if (previousTrack.get() != latestTrack.get()) {
6145 mFlushPending = true;
6146 }
6147 } else /* mType == OFFLOAD */ {
6148 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6149 mFlushPending = true;
6150 }
6151 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006152 } else if (previousTrack == 0) {
6153 // there could be an old track added back during track transition for direct
6154 // output, so always issues flush to flush data of the previous track if it
6155 // was already destroyed with HAL paused, then flush can resume the playback
6156 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006157 }
6158 PlaybackThread::onAddNewTrack_l();
6159}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006160
Eric Laurent81784c32012-11-19 14:55:58 -08006161AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6162 Vector< sp<Track> > *tracksToRemove
6163)
6164{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006165 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006166 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006167 bool doHwPause = false;
6168 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006169
6170 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006171 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006172 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006173 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006174 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006175 continue;
6176 }
6177
Eric Laurent5850c4c2016-11-10 13:04:31 -08006178 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006179#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006180 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006181#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006182 // Only consider last track started for volume and mixer state control.
6183 // In theory an older track could underrun and restart after the new one starts
6184 // but as we only care about the transition phase between two tracks on a
6185 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006186 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006187 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006188
Kuowei Li23666472021-01-20 10:23:25 +08006189 if (track->isPausePending()) {
6190 track->pauseAck();
6191 // It is possible a track might have been flushed or stopped.
6192 // Other operations such as flush pending might occur on the next prepare.
6193 if (track->isPausing()) {
6194 track->setPaused();
6195 }
6196 // Always perform pause, as an immediate flush will change
6197 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006198 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006199 doHwPause = true;
6200 mHwPaused = true;
6201 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006202 } else if (track->isFlushPending()) {
6203 track->flushAck();
6204 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006205 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006206 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006207 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006208 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006209 if (last) {
6210 mLeftVolFloat = mRightVolFloat = -1.0;
6211 if (mHwPaused) {
6212 doHwResume = true;
6213 mHwPaused = false;
6214 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006215 }
6216 }
6217
Eric Laurent81784c32012-11-19 14:55:58 -08006218 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006219 // for all its buffers to be filled before processing it.
6220 // Allow draining the buffer in case the client
6221 // app does not call stop() and relies on underrun to stop:
6222 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006223 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6224 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6225 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006226 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006227
6228 // target retry count that we will use is based on the time we wait for retries.
6229 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6230 // the retry threshold is when we accept any size for PCM data. This is slightly
6231 // smaller than the retry count so we can push small bits of data without a glitch.
6232 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006233 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006234 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006235 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006236 minFrames = mNormalFrameCount;
6237 } else {
6238 minFrames = 1;
6239 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006240
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006241 const size_t framesReady = track->framesReady();
6242 const int trackId = track->id();
6243 if (ATRACE_ENABLED()) {
6244 std::string traceName("nRdy");
6245 traceName += std::to_string(trackId);
6246 ATRACE_INT(traceName.c_str(), framesReady);
6247 }
6248 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006249 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006250 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006251 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006252
6253 if (track->mFillingUpStatus == Track::FS_FILLED) {
6254 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006255 if (last) {
6256 // make sure processVolume_l() will apply new volume even if 0
6257 mLeftVolFloat = mRightVolFloat = -1.0;
6258 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006259 if (!mHwSupportsPause) {
6260 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006261 }
6262 }
6263
6264 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006265 processVolume_l(track, last);
6266 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006267 sp<Track> previousTrack = mPreviousTrack.promote();
6268 if (previousTrack != 0) {
6269 if (track != previousTrack.get()) {
6270 // Flush any data still being written from last track
6271 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006272 // Invalidate previous track to force a seek when resuming.
6273 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006274 }
6275 }
6276 mPreviousTrack = track;
6277
Eric Laurentd595b7c2013-04-03 17:27:56 -07006278 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006279 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006280 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006281 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006282 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006283 doHwResume = true;
6284 mHwPaused = false;
6285 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006286 }
Eric Laurent81784c32012-11-19 14:55:58 -08006287 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006288 // clear effect chain input buffer if the last active track started underruns
6289 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006290 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006291 mEffectChains[0]->clearInputBuffer();
6292 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006293 if (track->isStopping_1()) {
6294 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006295 if (last && mHwPaused) {
6296 doHwResume = true;
6297 mHwPaused = false;
6298 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006299 }
6300 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6301 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006302 // We have consumed all the buffers of this track.
6303 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006304 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006305 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006306 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006307 if (track->isStopping_2()) {
6308 track->mState = TrackBase::STOPPED;
6309 }
Eric Laurent81784c32012-11-19 14:55:58 -08006310 if (track->isStopped()) {
6311 track->reset();
6312 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006313 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006314 }
6315 } else {
6316 // No buffers for this track. Give it a few chances to
6317 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006318 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006319 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006320 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006321 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006322 // indicate to client process that the track was disabled because of underrun;
6323 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006324 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006325 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6326 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006327 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6328 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006329 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006330 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006331 doHwPause = true;
6332 mHwPaused = true;
6333 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006334 } else if (last) {
6335 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006336 }
6337 }
6338 }
6339 }
6340
Eric Laurentd1f69b02014-12-15 14:33:13 -08006341 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006342 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006343 for (size_t i = 0; i < mTracks.size(); i++) {
6344 if (mTracks[i]->isFlushPending()) {
6345 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006346 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006347 }
6348 }
6349 }
6350
6351 // make sure the pause/flush/resume sequence is executed in the right order.
6352 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6353 // before flush and then resume HW. This can happen in case of pause/flush/resume
6354 // if resume is received before pause is executed.
6355 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006356 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006357 status_t result = mOutput->stream->pause();
6358 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006359 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006360 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006361 flushHw_l();
6362 }
6363 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006364 status_t result = mOutput->stream->resume();
6365 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006366 }
Eric Laurent81784c32012-11-19 14:55:58 -08006367 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006368 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006369
6370 return mixerStatus;
6371}
6372
6373void AudioFlinger::DirectOutputThread::threadLoop_mix()
6374{
Eric Laurent81784c32012-11-19 14:55:58 -08006375 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006376 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006377 // output audio to hardware
6378 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006379 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006380 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006381 status_t status = mActiveTrack->getNextBuffer(&buffer);
6382 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006383 // no need to pad with 0 for compressed audio
6384 if (audio_has_proportional_frames(mFormat)) {
6385 memset(curBuf, 0, frameCount * mFrameSize);
6386 }
Eric Laurent81784c32012-11-19 14:55:58 -08006387 break;
6388 }
6389 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6390 frameCount -= buffer.frameCount;
6391 curBuf += buffer.frameCount * mFrameSize;
6392 mActiveTrack->releaseBuffer(&buffer);
6393 }
Andy Hung2098f272014-02-27 14:00:06 -08006394 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006395 mSleepTimeUs = 0;
6396 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006397 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006398}
6399
6400void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6401{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006402 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006403 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006404 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006405 return;
6406 }
Andy Hung85ba3332021-04-27 17:40:26 -07006407 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6408 mSleepTimeUs = mActiveSleepTimeUs;
6409 } else {
6410 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006411 }
Andy Hung85ba3332021-04-27 17:40:26 -07006412 // Note: In S or later, we do not write zeroes for
6413 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006414}
6415
Eric Laurentd1f69b02014-12-15 14:33:13 -08006416void AudioFlinger::DirectOutputThread::threadLoop_exit()
6417{
6418 {
6419 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006420 for (size_t i = 0; i < mTracks.size(); i++) {
6421 if (mTracks[i]->isFlushPending()) {
6422 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006423 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006424 }
6425 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006426 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006427 flushHw_l();
6428 }
6429 }
6430 PlaybackThread::threadLoop_exit();
6431}
6432
6433// must be called with thread mutex locked
6434bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6435{
6436 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006437 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006438
6439 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6440 // after a timeout and we will enter standby then.
6441 if (mTracks.size() > 0) {
6442 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006443 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6444 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006445 }
6446
Eric Laurent5cff4032015-05-26 13:49:58 -07006447 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006448}
6449
Eric Laurent10351942014-05-08 18:49:52 -07006450// checkForNewParameter_l() must be called with ThreadBase::mLock held
6451bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6452 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006453{
6454 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006455 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006456
Eric Laurent10351942014-05-08 18:49:52 -07006457 AudioParameter param = AudioParameter(keyValuePair);
6458 int value;
6459 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006460 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006461 }
Eric Laurent10351942014-05-08 18:49:52 -07006462 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6463 // do not accept frame count changes if tracks are open as the track buffer
6464 // size depends on frame count and correct behavior would not be garantied
6465 // if frame count is changed after track creation
6466 if (!mTracks.isEmpty()) {
6467 status = INVALID_OPERATION;
6468 } else {
6469 reconfig = true;
6470 }
6471 }
6472 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006473 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006474 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006475 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006476 if (!mStandby) {
6477 mThreadMetrics.logEndInterval();
6478 mStandby = true;
6479 }
Eric Laurent10351942014-05-08 18:49:52 -07006480 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006481 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006482 }
6483 if (status == NO_ERROR && reconfig) {
6484 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006485 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006486 }
6487 }
6488
Dean Wheatley68918102021-03-19 22:09:19 +11006489 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006490}
6491
6492uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6493{
6494 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006495 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006496 time = PlaybackThread::activeSleepTimeUs();
6497 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006498 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006499 }
6500 return time;
6501}
6502
6503uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6504{
6505 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006506 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006507 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6508 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006509 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006510 }
6511 return time;
6512}
6513
6514uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6515{
6516 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006517 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006518 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6519 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006520 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006521 }
6522 return time;
6523}
6524
6525void AudioFlinger::DirectOutputThread::cacheParameters_l()
6526{
6527 PlaybackThread::cacheParameters_l();
6528
6529 // use shorter standby delay as on normal output to release
6530 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006531 // no delay on outputs with HW A/V sync
6532 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006533 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006534 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006535 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006536 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006537 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006538 }
Eric Laurent81784c32012-11-19 14:55:58 -08006539}
6540
Eric Laurente659ef42014-09-29 13:06:46 -07006541void AudioFlinger::DirectOutputThread::flushHw_l()
6542{
Phil Burk062e67a2015-02-11 13:40:50 -08006543 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006544 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006545 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006546 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006547 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006548}
6549
Andy Hung10cbff12017-02-21 17:30:14 -08006550int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6551 // If a VolumeShaper is active, we must wake up periodically to update volume.
6552 const int64_t NS_PER_MS = 1000000;
6553 return mVolumeShaperActive ?
6554 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6555}
6556
Eric Laurent81784c32012-11-19 14:55:58 -08006557// ----------------------------------------------------------------------------
6558
Eric Laurentbfb1b832013-01-07 09:53:42 -08006559AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006560 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006561 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006562 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006563 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006564 mDrainSequence(0),
6565 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006566{
6567}
6568
6569AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6570{
6571}
6572
6573void AudioFlinger::AsyncCallbackThread::onFirstRef()
6574{
6575 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6576}
6577
6578bool AudioFlinger::AsyncCallbackThread::threadLoop()
6579{
6580 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006581 uint32_t writeAckSequence;
6582 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006583 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006584
6585 {
6586 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006587 while (!((mWriteAckSequence & 1) ||
6588 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006589 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006590 exitPending())) {
6591 mWaitWorkCV.wait(mLock);
6592 }
6593
Eric Laurentbfb1b832013-01-07 09:53:42 -08006594 if (exitPending()) {
6595 break;
6596 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006597 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6598 mWriteAckSequence, mDrainSequence);
6599 writeAckSequence = mWriteAckSequence;
6600 mWriteAckSequence &= ~1;
6601 drainSequence = mDrainSequence;
6602 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006603 asyncError = mAsyncError;
6604 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006605 }
6606 {
Eric Laurent4de95592013-09-26 15:28:21 -07006607 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6608 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006609 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006610 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006611 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006612 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006613 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006614 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006615 if (asyncError) {
6616 playbackThread->onAsyncError();
6617 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006618 }
6619 }
6620 }
6621 return false;
6622}
6623
6624void AudioFlinger::AsyncCallbackThread::exit()
6625{
6626 ALOGV("AsyncCallbackThread::exit");
6627 Mutex::Autolock _l(mLock);
6628 requestExit();
6629 mWaitWorkCV.broadcast();
6630}
6631
Eric Laurent3b4529e2013-09-05 18:09:19 -07006632void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006633{
6634 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006635 // bit 0 is cleared
6636 mWriteAckSequence = sequence << 1;
6637}
6638
6639void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6640{
6641 Mutex::Autolock _l(mLock);
6642 // ignore unexpected callbacks
6643 if (mWriteAckSequence & 2) {
6644 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006645 mWaitWorkCV.signal();
6646 }
6647}
6648
Eric Laurent3b4529e2013-09-05 18:09:19 -07006649void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006650{
6651 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006652 // bit 0 is cleared
6653 mDrainSequence = sequence << 1;
6654}
6655
6656void AudioFlinger::AsyncCallbackThread::resetDraining()
6657{
6658 Mutex::Autolock _l(mLock);
6659 // ignore unexpected callbacks
6660 if (mDrainSequence & 2) {
6661 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006662 mWaitWorkCV.signal();
6663 }
6664}
6665
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006666void AudioFlinger::AsyncCallbackThread::setAsyncError()
6667{
6668 Mutex::Autolock _l(mLock);
6669 mAsyncError = true;
6670 mWaitWorkCV.signal();
6671}
6672
Eric Laurentbfb1b832013-01-07 09:53:42 -08006673
6674// ----------------------------------------------------------------------------
6675AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006676 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6677 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006678 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6679 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006680{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006681 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006682 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006683 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006684}
6685
Eric Laurentbfb1b832013-01-07 09:53:42 -08006686void AudioFlinger::OffloadThread::threadLoop_exit()
6687{
6688 if (mFlushPending || mHwPaused) {
6689 // If a flush is pending or track was paused, just discard buffered data
6690 flushHw_l();
6691 } else {
6692 mMixerStatus = MIXER_DRAIN_ALL;
6693 threadLoop_drain();
6694 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006695 if (mUseAsyncWrite) {
6696 ALOG_ASSERT(mCallbackThread != 0);
6697 mCallbackThread->exit();
6698 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006699 PlaybackThread::threadLoop_exit();
6700}
6701
6702AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6703 Vector< sp<Track> > *tracksToRemove
6704)
6705{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006706 size_t count = mActiveTracks.size();
6707
6708 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006709 bool doHwPause = false;
6710 bool doHwResume = false;
6711
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006712 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006713
Eric Laurentbfb1b832013-01-07 09:53:42 -08006714 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006715 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006716 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006717#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006718 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006719#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006720 // Only consider last track started for volume and mixer state control.
6721 // In theory an older track could underrun and restart after the new one starts
6722 // but as we only care about the transition phase between two tracks on a
6723 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006724 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006725 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006726
Haynes Mathew George7844f672014-01-15 12:32:55 -08006727 if (track->isInvalid()) {
6728 ALOGW("An invalidated track shouldn't be in active list");
6729 tracksToRemove->add(track);
6730 continue;
6731 }
6732
6733 if (track->mState == TrackBase::IDLE) {
6734 ALOGW("An idle track shouldn't be in active list");
6735 continue;
6736 }
6737
Kuowei Li23666472021-01-20 10:23:25 +08006738 if (track->isPausePending()) {
6739 track->pauseAck();
6740 // It is possible a track might have been flushed or stopped.
6741 // Other operations such as flush pending might occur on the next prepare.
6742 if (track->isPausing()) {
6743 track->setPaused();
6744 }
6745 // Always perform pause if last, as an immediate flush will change
6746 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006747 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006748 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006749 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006750 mHwPaused = true;
6751 }
6752 // If we were part way through writing the mixbuffer to
6753 // the HAL we must save this until we resume
6754 // BUG - this will be wrong if a different track is made active,
6755 // in that case we want to discard the pending data in the
6756 // mixbuffer and tell the client to present it again when the
6757 // track is resumed
6758 mPausedWriteLength = mCurrentWriteLength;
6759 mPausedBytesRemaining = mBytesRemaining;
6760 mBytesRemaining = 0; // stop writing
6761 }
6762 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006763 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006764 if (track->isStopping_1()) {
6765 track->mRetryCount = kMaxTrackStopRetriesOffload;
6766 } else {
6767 track->mRetryCount = kMaxTrackRetriesOffload;
6768 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006769 track->flushAck();
6770 if (last) {
6771 mFlushPending = true;
6772 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006773 } else if (track->isResumePending()){
6774 track->resumeAck();
6775 if (last) {
6776 if (mPausedBytesRemaining) {
6777 // Need to continue write that was interrupted
6778 mCurrentWriteLength = mPausedWriteLength;
6779 mBytesRemaining = mPausedBytesRemaining;
6780 mPausedBytesRemaining = 0;
6781 }
6782 if (mHwPaused) {
6783 doHwResume = true;
6784 mHwPaused = false;
6785 // threadLoop_mix() will handle the case that we need to
6786 // resume an interrupted write
6787 }
6788 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006789 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006790
Eric Laurent3df841a2016-07-15 15:15:40 -07006791 mLeftVolFloat = mRightVolFloat = -1.0;
6792
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006793 // Do not handle new data in this iteration even if track->framesReady()
6794 mixerStatus = MIXER_TRACKS_ENABLED;
6795 }
6796 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006797 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006798 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006799 if (track->mFillingUpStatus == Track::FS_FILLED) {
6800 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006801 if (last) {
6802 // make sure processVolume_l() will apply new volume even if 0
6803 mLeftVolFloat = mRightVolFloat = -1.0;
6804 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006805 }
6806
6807 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006808 sp<Track> previousTrack = mPreviousTrack.promote();
6809 if (previousTrack != 0) {
6810 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006811 // Flush any data still being written from last track
6812 mBytesRemaining = 0;
6813 if (mPausedBytesRemaining) {
6814 // Last track was paused so we also need to flush saved
6815 // mixbuffer state and invalidate track so that it will
6816 // re-submit that unwritten data when it is next resumed
6817 mPausedBytesRemaining = 0;
6818 // Invalidate is a bit drastic - would be more efficient
6819 // to have a flag to tell client that some of the
6820 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006821 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006822 }
6823 // flush data already sent to the DSP if changing audio session as audio
6824 // comes from a different source. Also invalidate previous track to force a
6825 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006826 if (previousTrack->sessionId() != track->sessionId()) {
6827 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006828 }
6829 }
6830 }
6831 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006832 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006833 if (track->isStopping_1()) {
6834 track->mRetryCount = kMaxTrackStopRetriesOffload;
6835 } else {
6836 track->mRetryCount = kMaxTrackRetriesOffload;
6837 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006838 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006839 mixerStatus = MIXER_TRACKS_READY;
6840 }
6841 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006842 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006843 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006844 if (--(track->mRetryCount) <= 0) {
6845 // Hardware buffer can hold a large amount of audio so we must
6846 // wait for all current track's data to drain before we say
6847 // that the track is stopped.
6848 if (mBytesRemaining == 0) {
6849 // Only start draining when all data in mixbuffer
6850 // has been written
6851 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6852 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6853 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6854 if (last && !mStandby) {
6855 // do not modify drain sequence if we are already draining. This happens
6856 // when resuming from pause after drain.
6857 if ((mDrainSequence & 1) == 0) {
6858 mSleepTimeUs = 0;
6859 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6860 mixerStatus = MIXER_DRAIN_TRACK;
6861 mDrainSequence += 2;
6862 }
6863 if (mHwPaused) {
6864 // It is possible to move from PAUSED to STOPPING_1 without
6865 // a resume so we must ensure hardware is running
6866 doHwResume = true;
6867 mHwPaused = false;
6868 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006869 }
6870 }
Eric Laurente93cc032016-05-05 10:15:10 -07006871 } else if (last) {
6872 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6873 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006874 }
6875 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006876 // Drain has completed or we are in standby, signal presentation complete
6877 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006878 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006879 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006880 track->reset();
6881 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006882 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006883 if (!mUseAsyncWrite) {
6884 // If we don't get explicit drain notification we must
6885 // register discontinuity regardless of whether this is
6886 // the previous (!last) or the upcoming (last) track
6887 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006888 mTimestampVerifier.discontinuity(
6889 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006890 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006891 }
6892 } else {
6893 // No buffers for this track. Give it a few chances to
6894 // fill a buffer, then remove it from active list.
6895 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006896 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006897 uint64_t position = 0;
6898 struct timespec unused;
6899 // The running check restarts the retry counter at least once.
6900 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6901 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6902 running = true;
6903 mOffloadUnderrunPosition = position;
6904 }
6905 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006906 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6907 (long long)position, (long long)mOffloadUnderrunPosition);
6908 }
6909 if (running) { // still running, give us more time.
6910 track->mRetryCount = kMaxTrackRetriesOffload;
6911 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006912 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6913 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006914 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006915 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006916 // it will then automatically call start() when data is available
6917 track->disable();
6918 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006919 } else if (last){
6920 mixerStatus = MIXER_TRACKS_ENABLED;
6921 }
6922 }
6923 }
6924 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006925 if (track->isReady()) { // check ready to prevent premature start.
6926 processVolume_l(track, last);
6927 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006928 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006929
Eric Laurentea0fade2013-10-04 16:23:48 -07006930 // make sure the pause/flush/resume sequence is executed in the right order.
6931 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6932 // before flush and then resume HW. This can happen in case of pause/flush/resume
6933 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006934 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006935 status_t result = mOutput->stream->pause();
6936 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006937 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006938 if (mFlushPending) {
6939 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006940 }
Eric Laurentfd477972013-10-25 18:10:40 -07006941 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006942 status_t result = mOutput->stream->resume();
6943 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006944 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006945
Eric Laurentbfb1b832013-01-07 09:53:42 -08006946 // remove all the tracks that need to be...
6947 removeTracks_l(*tracksToRemove);
6948
6949 return mixerStatus;
6950}
6951
Eric Laurentbfb1b832013-01-07 09:53:42 -08006952// must be called with thread mutex locked
6953bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6954{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006955 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6956 mWriteAckSequence, mDrainSequence);
6957 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006958 return true;
6959 }
6960 return false;
6961}
6962
Eric Laurentbfb1b832013-01-07 09:53:42 -08006963bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6964{
6965 Mutex::Autolock _l(mLock);
6966 return waitingAsyncCallback_l();
6967}
6968
6969void AudioFlinger::OffloadThread::flushHw_l()
6970{
Eric Laurente659ef42014-09-29 13:06:46 -07006971 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006972 // Flush anything still waiting in the mixbuffer
6973 mCurrentWriteLength = 0;
6974 mBytesRemaining = 0;
6975 mPausedWriteLength = 0;
6976 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006977 // reset bytes written count to reflect that DSP buffers are empty after flush.
6978 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006979 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006980
Eric Laurentbfb1b832013-01-07 09:53:42 -08006981 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006982 // discard any pending drain or write ack by incrementing sequence
6983 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6984 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006985 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006986 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6987 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006988 }
6989}
6990
Haynes Mathew George05317d22016-05-03 16:34:26 -07006991void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6992{
6993 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006994 if (PlaybackThread::invalidateTracks_l(streamType)) {
6995 mFlushPending = true;
6996 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006997}
6998
Eric Laurentbfb1b832013-01-07 09:53:42 -08006999// ----------------------------------------------------------------------------
7000
Eric Laurent81784c32012-11-19 14:55:58 -08007001AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007002 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007003 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007004 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007005 mWaitTimeMs(UINT_MAX)
7006{
7007 addOutputTrack(mainThread);
7008}
7009
7010AudioFlinger::DuplicatingThread::~DuplicatingThread()
7011{
7012 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7013 mOutputTracks[i]->destroy();
7014 }
7015}
7016
7017void AudioFlinger::DuplicatingThread::threadLoop_mix()
7018{
7019 // mix buffers...
7020 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007021 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007022 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007023 if (mMixerBufferValid) {
7024 memset(mMixerBuffer, 0, mMixerBufferSize);
7025 } else {
7026 memset(mSinkBuffer, 0, mSinkBufferSize);
7027 }
Eric Laurent81784c32012-11-19 14:55:58 -08007028 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007029 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007030 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007031 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007032 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007033}
7034
7035void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7036{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007037 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007038 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007039 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007040 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007041 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007042 }
7043 } else if (mBytesWritten != 0) {
7044 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7045 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007046 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007047 } else {
7048 // flush remaining overflow buffers in output tracks
7049 writeFrames = 0;
7050 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007051 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007052 }
7053}
7054
Eric Laurentbfb1b832013-01-07 09:53:42 -08007055ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007056{
7057 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007058 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7059
7060 // Consider the first OutputTrack for timestamp and frame counting.
7061
7062 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7063 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7064 // we always claim success.
7065 if (i == 0) {
7066 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7067 ALOGD_IF(correction != 0 && writeFrames != 0,
7068 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7069 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7070 mFramesWritten -= correction;
7071 }
7072
7073 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007074 }
Andy Hungcf10d742020-04-28 15:38:24 -07007075 if (mStandby) {
7076 mThreadMetrics.logBeginInterval();
7077 mStandby = false;
7078 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007079 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007080}
7081
7082void AudioFlinger::DuplicatingThread::threadLoop_standby()
7083{
7084 // DuplicatingThread implements standby by stopping all tracks
7085 for (size_t i = 0; i < outputTracks.size(); i++) {
7086 outputTracks[i]->stop();
7087 }
7088}
7089
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007090void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08007091{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007092 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007093
7094 std::stringstream ss;
7095 const size_t numTracks = mOutputTracks.size();
7096 ss << " " << numTracks << " OutputTracks";
7097 if (numTracks > 0) {
7098 ss << ":";
7099 for (const auto &track : mOutputTracks) {
7100 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007101 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007102 if (thread.get() != nullptr) {
7103 ss << thread.get() << ", " << thread->id();
7104 } else {
7105 ss << "null";
7106 }
7107 ss << ")";
7108 }
7109 }
7110 ss << "\n";
7111 std::string result = ss.str();
7112 write(fd, result.c_str(), result.size());
7113}
7114
Eric Laurent81784c32012-11-19 14:55:58 -08007115void AudioFlinger::DuplicatingThread::saveOutputTracks()
7116{
7117 outputTracks = mOutputTracks;
7118}
7119
7120void AudioFlinger::DuplicatingThread::clearOutputTracks()
7121{
7122 outputTracks.clear();
7123}
7124
7125void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7126{
7127 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007128 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7129 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7130 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7131 const size_t frameCount =
7132 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7133 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7134 // from different OutputTracks and their associated MixerThreads (e.g. one may
7135 // nearly empty and the other may be dropping data).
7136
Svet Ganov33761132021-05-13 22:51:08 +00007137 // TODO b/182392769: use attribution source util, move to server edge
7138 AttributionSourceState attributionSource = AttributionSourceState();
7139 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007140 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007141 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007142 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007143 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007144 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007145 this,
7146 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007147 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007148 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007149 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007150 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007151 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7152 if (status != NO_ERROR) {
7153 ALOGE("addOutputTrack() initCheck failed %d", status);
7154 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007155 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007156 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7157 mOutputTracks.add(outputTrack);
7158 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7159 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007160}
7161
7162void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7163{
7164 Mutex::Autolock _l(mLock);
7165 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7166 if (mOutputTracks[i]->thread() == thread) {
7167 mOutputTracks[i]->destroy();
7168 mOutputTracks.removeAt(i);
7169 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007170 if (thread->getOutput() == mOutput) {
7171 mOutput = NULL;
7172 }
Eric Laurent81784c32012-11-19 14:55:58 -08007173 return;
7174 }
7175 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007176 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007177}
7178
7179// caller must hold mLock
7180void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7181{
7182 mWaitTimeMs = UINT_MAX;
7183 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7184 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7185 if (strong != 0) {
7186 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7187 if (waitTimeMs < mWaitTimeMs) {
7188 mWaitTimeMs = waitTimeMs;
7189 }
7190 }
7191 }
7192}
7193
7194
7195bool AudioFlinger::DuplicatingThread::outputsReady(
7196 const SortedVector< sp<OutputTrack> > &outputTracks)
7197{
7198 for (size_t i = 0; i < outputTracks.size(); i++) {
7199 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7200 if (thread == 0) {
7201 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7202 outputTracks[i].get());
7203 return false;
7204 }
7205 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7206 // see note at standby() declaration
7207 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7208 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7209 thread.get());
7210 return false;
7211 }
7212 }
7213 return true;
7214}
7215
Kevin Rocard12381092018-04-11 09:19:59 -07007216void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7217 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007218{
Kevin Rocard12381092018-04-11 09:19:59 -07007219 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7220 outputTrack->setMetadatas(metadata.tracks);
7221 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007222}
7223
Eric Laurent81784c32012-11-19 14:55:58 -08007224uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7225{
7226 return (mWaitTimeMs * 1000) / 2;
7227}
7228
7229void AudioFlinger::DuplicatingThread::cacheParameters_l()
7230{
7231 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7232 updateWaitTime_l();
7233
7234 MixerThread::cacheParameters_l();
7235}
7236
Eric Laurentb3f315a2021-07-13 15:09:05 +02007237// ----------------------------------------------------------------------------
7238
Eric Laurentfa0f6742021-08-17 18:39:44 +02007239AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007240 AudioStreamOut* output,
7241 audio_io_handle_t id,
7242 bool systemReady,
7243 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007244 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007245{
7246}
7247
Eric Laurentfa0f6742021-08-17 18:39:44 +02007248void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007249{
7250 bool hasVirtualizer = false;
7251 bool hasDownMixer = false;
7252 sp<EffectHandle> finalDownMixer;
7253 {
7254 Mutex::Autolock _l(mLock);
7255 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7256 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007257 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007258 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7259 }
7260
7261 finalDownMixer = mFinalDownMixer;
7262 mFinalDownMixer.clear();
7263 }
7264
7265 if (hasVirtualizer) {
7266 if (finalDownMixer != nullptr) {
7267 int32_t ret;
7268 finalDownMixer->disable(&ret);
7269 }
7270 finalDownMixer.clear();
7271 } else if (!hasDownMixer) {
7272 std::vector<effect_descriptor_t> descriptors;
7273 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7274 EFFECT_UIID_DOWNMIX, &descriptors);
7275 if (status != NO_ERROR) {
7276 return;
7277 }
7278 ALOG_ASSERT(!descriptors.empty(),
7279 "%s getDescriptors() returned no error but empty list", __func__);
7280
7281 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7282 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007283 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007284
7285 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7286 ALOGW("%s error creating downmixer %d", __func__, status);
7287 finalDownMixer.clear();
7288 } else {
7289 int32_t ret;
7290 finalDownMixer->enable(&ret);
7291 }
7292 }
7293
7294 {
7295 Mutex::Autolock _l(mLock);
7296 mFinalDownMixer = finalDownMixer;
7297 }
7298}
7299
Eric Laurent6acd1d42017-01-04 14:23:29 -08007300
Eric Laurent81784c32012-11-19 14:55:58 -08007301// ----------------------------------------------------------------------------
7302// Record
7303// ----------------------------------------------------------------------------
7304
7305AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7306 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007307 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007308 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007309 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007310 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007311 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007312 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007313 mActiveTracks(&this->mLocalLog),
7314 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007315 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007316 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007317 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7318 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007319 // mFastCapture below
7320 , mFastCaptureFutex(0)
7321 // mInputSource
7322 // mPipeSink
7323 // mPipeSource
7324 , mPipeFramesP2(0)
7325 // mPipeMemory
7326 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007327 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007328 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007329{
Glenn Kastend7dca052015-03-05 16:05:54 -08007330 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7331 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007332
George Burgess IVa8f90c12020-05-14 11:27:19 -07007333 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007334 mIsMsdDevice = strcmp(
7335 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7336 }
7337
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007338 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007339
Andy Hungc8fddf32018-08-08 18:32:37 -07007340 // TODO: We may also match on address as well as device type for
7341 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007342 // TODO: This property should be ensure that only contains one single device type.
7343 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7344 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007345 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7346 : AUDIO_DEVICE_NONE));
7347
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007348 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007349 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007350 size_t numCounterOffers = 0;
7351 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007352#if !LOG_NDEBUG
7353 ssize_t index =
7354#else
7355 (void)
7356#endif
7357 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007358 ALOG_ASSERT(index == 0);
7359
7360 // initialize fast capture depending on configuration
7361 bool initFastCapture;
7362 switch (kUseFastCapture) {
7363 case FastCapture_Never:
7364 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007365 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007366 break;
7367 case FastCapture_Always:
7368 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007369 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007370 break;
7371 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007372 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007373 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7374 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7375 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007376 break;
7377 // case FastCapture_Dynamic:
7378 }
7379
7380 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007381 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007382 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007383 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7384 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007385 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007386 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007387 const sp<MemoryDealer> roHeap(readOnlyHeap());
7388 sp<IMemory> pipeMemory;
7389 if ((roHeap == 0) ||
7390 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007391 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007392 ALOGE("not enough memory for pipe buffer size=%zu; "
7393 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7394 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7395 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007396 goto failed;
7397 }
7398 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7399 memset(pipeBuffer, 0, pipeSize);
7400 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7401 const NBAIO_Format offers[1] = {format};
7402 size_t numCounterOffers = 0;
7403 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7404 ALOG_ASSERT(index == 0);
7405 mPipeSink = pipe;
7406 PipeReader *pipeReader = new PipeReader(*pipe);
7407 numCounterOffers = 0;
7408 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7409 ALOG_ASSERT(index == 0);
7410 mPipeSource = pipeReader;
7411 mPipeFramesP2 = pipeFramesP2;
7412 mPipeMemory = pipeMemory;
7413
7414 // create fast capture
7415 mFastCapture = new FastCapture();
7416 FastCaptureStateQueue *sq = mFastCapture->sq();
7417#ifdef STATE_QUEUE_DUMP
7418 // FIXME
7419#endif
7420 FastCaptureState *state = sq->begin();
7421 state->mCblk = NULL;
7422 state->mInputSource = mInputSource.get();
7423 state->mInputSourceGen++;
7424 state->mPipeSink = pipe;
7425 state->mPipeSinkGen++;
7426 state->mFrameCount = mFrameCount;
7427 state->mCommand = FastCaptureState::COLD_IDLE;
7428 // already done in constructor initialization list
7429 //mFastCaptureFutex = 0;
7430 state->mColdFutexAddr = &mFastCaptureFutex;
7431 state->mColdGen++;
7432 state->mDumpState = &mFastCaptureDumpState;
7433#ifdef TEE_SINK
7434 // FIXME
7435#endif
7436 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7437 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7438 sq->end();
7439 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7440
7441 // start the fast capture
7442 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7443 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007444 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007445 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007446#ifdef AUDIO_WATCHDOG
7447 // FIXME
7448#endif
7449
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007450 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007451 }
Andy Hung8946a282018-04-19 20:04:56 -07007452#ifdef TEE_SINK
7453 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7454 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7455#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007456failed: ;
7457
7458 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007459}
7460
Eric Laurent81784c32012-11-19 14:55:58 -08007461AudioFlinger::RecordThread::~RecordThread()
7462{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007463 if (mFastCapture != 0) {
7464 FastCaptureStateQueue *sq = mFastCapture->sq();
7465 FastCaptureState *state = sq->begin();
7466 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7467 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7468 if (old == -1) {
7469 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7470 }
7471 }
7472 state->mCommand = FastCaptureState::EXIT;
7473 sq->end();
7474 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7475 mFastCapture->join();
7476 mFastCapture.clear();
7477 }
7478 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007479 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007480 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007481}
7482
7483void AudioFlinger::RecordThread::onFirstRef()
7484{
Glenn Kastend7dca052015-03-05 16:05:54 -08007485 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007486}
7487
Eric Laurent555530a2017-02-07 18:17:24 -08007488void AudioFlinger::RecordThread::preExit()
7489{
7490 ALOGV(" preExit()");
7491 Mutex::Autolock _l(mLock);
7492 for (size_t i = 0; i < mTracks.size(); i++) {
7493 sp<RecordTrack> track = mTracks[i];
7494 track->invalidate();
7495 }
7496 mActiveTracks.clear();
7497 mStartStopCond.broadcast();
7498}
7499
Eric Laurent81784c32012-11-19 14:55:58 -08007500bool AudioFlinger::RecordThread::threadLoop()
7501{
Eric Laurent81784c32012-11-19 14:55:58 -08007502 nsecs_t lastWarning = 0;
7503
7504 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007505
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007506reacquire_wakelock:
7507 sp<RecordTrack> activeTrack;
7508 {
7509 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007510 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007511 }
7512
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007513 // used to request a deferred sleep, to be executed later while mutex is unlocked
7514 uint32_t sleepUs = 0;
7515
Andy Hung446f4df2019-02-21 12:26:41 -08007516 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7517
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007518 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007519 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007520 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007521
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007522 // activeTracks accumulates a copy of a subset of mActiveTracks
7523 Vector< sp<RecordTrack> > activeTracks;
7524
Glenn Kasten735f45f2014-08-18 15:51:59 -07007525 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007526 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007527
Glenn Kasten735f45f2014-08-18 15:51:59 -07007528 // reference to a fast track which is about to be removed
7529 sp<RecordTrack> fastTrackToRemove;
7530
Eric Laurent33403f02020-05-29 18:35:06 -07007531 bool silenceFastCapture = false;
7532
Eric Laurent81784c32012-11-19 14:55:58 -08007533 { // scope for mLock
7534 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007535
Eric Laurent021cf962014-05-13 10:18:14 -07007536 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007537
Eric Laurent000a4192014-01-29 15:17:32 -08007538 // check exitPending here because checkForNewParameters_l() and
7539 // checkForNewParameters_l() can temporarily release mLock
7540 if (exitPending()) {
7541 break;
7542 }
7543
Eric Laurent5c25d562016-07-13 17:17:45 -07007544 // sleep with mutex unlocked
7545 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007546 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007547 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7548 ATRACE_END();
7549 sleepUs = 0;
7550 continue;
7551 }
7552
Glenn Kasten2b806402013-11-20 16:37:38 -08007553 // if no active track(s), then standby and release wakelock
7554 size_t size = mActiveTracks.size();
7555 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007556 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007557 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007558 releaseWakeLock_l();
7559 ALOGV("RecordThread: loop stopping");
7560 // go to sleep
7561 mWaitWorkCV.wait(mLock);
7562 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007563 goto reacquire_wakelock;
7564 }
7565
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007566 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007567 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007568 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007569
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007570 activeTrack = mActiveTracks[i];
7571 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007572 if (activeTrack->isFastTrack()) {
7573 ALOG_ASSERT(fastTrackToRemove == 0);
7574 fastTrackToRemove = activeTrack;
7575 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007576 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007577 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007578 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007579 continue;
7580 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007581
7582 TrackBase::track_state activeTrackState = activeTrack->mState;
7583 switch (activeTrackState) {
7584
7585 case TrackBase::PAUSING:
7586 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007587 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007588 doBroadcast = true;
7589 size--;
7590 continue;
7591
7592 case TrackBase::STARTING_1:
7593 sleepUs = 10000;
7594 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007595 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007596 continue;
7597
7598 case TrackBase::STARTING_2:
7599 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007600 if (mStandby) {
7601 mThreadMetrics.logBeginInterval();
7602 mStandby = false;
7603 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007604 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007605 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007606 break;
7607
7608 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007609 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007610 break;
7611
Andy Hungce685402018-10-05 17:23:27 -07007612 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7613 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7614 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007615 default:
Andy Hungce685402018-10-05 17:23:27 -07007616 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7617 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007618 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007619
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007620 if (activeTrack->isFastTrack()) {
7621 ALOG_ASSERT(!mFastTrackAvail);
7622 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007623 // if the active fast track is silenced either:
7624 // 1) silence the whole capture from fast capture buffer if this is
7625 // the only active track
7626 // 2) invalidate this track: this will cause the client to reconnect and possibly
7627 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007628 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007629 if (activeTrack->isSilenced()) {
7630 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007631 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007632 } else {
7633 silenceFastCapture = true;
7634 }
7635 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007636 // Invalidate fast tracks if access to audio history is required as this is not
7637 // possible with fast tracks. Once the fast track has been invalidated, no new
7638 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7639 if (mMaxSharedAudioHistoryMs != 0) {
7640 invalidate = true;
7641 }
7642 if (invalidate) {
7643 activeTrack->invalidate();
7644 ALOG_ASSERT(fastTrackToRemove == 0);
7645 fastTrackToRemove = activeTrack;
7646 removeTrack_l(activeTrack);
7647 mActiveTracks.remove(activeTrack);
7648 size--;
7649 continue;
7650 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007651 fastTrack = activeTrack;
7652 }
Eric Laurent33403f02020-05-29 18:35:06 -07007653
7654 activeTracks.add(activeTrack);
7655 i++;
7656
Glenn Kasten9e982352013-08-14 14:39:50 -07007657 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007658
Andy Hungdae27702016-10-31 14:01:16 -07007659 mActiveTracks.updatePowerState(this);
7660
Kevin Rocard069c2712018-03-29 19:09:14 -07007661 updateMetadata_l();
7662
Eric Laurent5c25d562016-07-13 17:17:45 -07007663 if (allStopped) {
7664 standbyIfNotAlreadyInStandby();
7665 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007666 if (doBroadcast) {
7667 mStartStopCond.broadcast();
7668 }
7669
7670 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007671 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007672 if (sleepUs == 0) {
7673 sleepUs = kRecordThreadSleepUs;
7674 }
7675 continue;
7676 }
7677 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007678
Eric Laurent81784c32012-11-19 14:55:58 -08007679 lockEffectChains_l(effectChains);
7680 }
7681
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007682 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007683
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007684 size_t size = effectChains.size();
7685 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007686 // thread mutex is not locked, but effect chain is locked
7687 effectChains[i]->process_l();
7688 }
7689
Glenn Kasten735f45f2014-08-18 15:51:59 -07007690 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007691 if (mFastCapture != 0) {
7692 FastCaptureStateQueue *sq = mFastCapture->sq();
7693 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007694 bool didModify = false;
7695 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007696 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7697 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7698 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7699 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7700 if (old == -1) {
7701 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7702 }
7703 }
7704 state->mCommand = FastCaptureState::READ_WRITE;
7705#if 0 // FIXME
7706 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007707 FastThreadDumpState::kSamplingNforLowRamDevice :
7708 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007709#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007710 didModify = true;
7711 }
7712 audio_track_cblk_t *cblkOld = state->mCblk;
7713 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7714 if (cblkNew != cblkOld) {
7715 state->mCblk = cblkNew;
7716 // block until acked if removing a fast track
7717 if (cblkOld != NULL) {
7718 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7719 }
7720 didModify = true;
7721 }
jiabin01c8f562018-07-19 17:47:28 -07007722 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7723 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7724 if (state->mFastPatchRecordBufferProvider != abp) {
7725 state->mFastPatchRecordBufferProvider = abp;
7726 state->mFastPatchRecordFormat = fastTrack == 0 ?
7727 AUDIO_FORMAT_INVALID : fastTrack->format();
7728 didModify = true;
7729 }
Eric Laurent33403f02020-05-29 18:35:06 -07007730 if (state->mSilenceCapture != silenceFastCapture) {
7731 state->mSilenceCapture = silenceFastCapture;
7732 didModify = true;
7733 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007734 sq->end(didModify);
7735 if (didModify) {
7736 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007737#if 0
7738 if (kUseFastCapture == FastCapture_Dynamic) {
7739 mNormalSource = mPipeSource;
7740 }
7741#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007742 }
7743 }
7744
Glenn Kasten735f45f2014-08-18 15:51:59 -07007745 // now run the fast track destructor with thread mutex unlocked
7746 fastTrackToRemove.clear();
7747
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007748 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7749 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7750 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7751 // If destination is non-contiguous, first read past the nominal end of buffer, then
7752 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007753
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007754 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007755 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007756 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007757
7758 // If an NBAIO source is present, use it to read the normal capture's data
7759 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007760 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007761
7762 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7763 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7764 // we immediately retry the read() to get data and prevent another overflow.
7765 for (int retries = 0; retries <= 2; ++retries) {
7766 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7767 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7768 framesToRead);
7769 if (framesRead != OVERRUN) break;
7770 }
7771
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007772 const ssize_t availableToRead = mPipeSource->availableToRead();
7773 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007774 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007775 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007776 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7777 "more frames to read than fifo size, %zd > %zu",
7778 availableToRead, mPipeFramesP2);
7779 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7780 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7781 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7782 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007783 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7784 }
7785 if (framesRead < 0) {
7786 status_t status = (status_t) framesRead;
7787 switch (status) {
7788 case OVERRUN:
7789 ALOGW("overrun on read from pipe");
7790 framesRead = 0;
7791 break;
7792 case NEGOTIATE:
7793 ALOGE("re-negotiation is needed");
7794 framesRead = -1; // Will cause an attempt to recover.
7795 break;
7796 default:
7797 ALOGE("unknown error %d on read from pipe", status);
7798 break;
7799 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007800 }
7801 // otherwise use the HAL / AudioStreamIn directly
7802 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007803 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007804 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007805 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007806 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007807 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007808 if (result < 0) {
7809 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007810 } else {
7811 framesRead = bytesRead / mFrameSize;
7812 }
7813 }
7814
Andy Hung446f4df2019-02-21 12:26:41 -08007815 const int64_t lastIoEndNs = systemTime(); // end IO timing
7816
Andy Hung3f0c9022016-01-15 17:49:46 -08007817 // Update server timestamp with server stats
7818 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007819 if (framesRead >= 0) {
7820 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7821 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7822 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007823
7824 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007825 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007826 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007827 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007828 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7829 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7830 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007831 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007832 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7833
7834 mTimestampVerifier.add(position, time, mSampleRate);
7835
7836 // Correct timestamps
7837 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007838 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007839 id(), (long long)time, (long long)position);
7840 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7841 position = correctedTimestamp.mFrames;
7842 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007843 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007844 id(), (long long)time, (long long)position);
7845 }
7846
Andy Hung3f0c9022016-01-15 17:49:46 -08007847 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7848 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7849 // Note: In general record buffers should tend to be empty in
7850 // a properly running pipeline.
7851 //
7852 // Also, it is not advantageous to call get_presentation_position during the read
7853 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007854 } else {
7855 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007856 }
7857 }
Andy Hunge6c37112019-02-26 17:38:10 -08007858
7859 // From the timestamp, input read latency is negative output write latency.
7860 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7861 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7862 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7863 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7864 mLatencyMs.add(latencyMs);
7865 }
7866
Andy Hung3f0c9022016-01-15 17:49:46 -08007867 // Use this to track timestamp information
7868 // ALOGD("%s", mTimestamp.toString().c_str());
7869
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007870 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007871 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007872 // Force input into standby so that it tries to recover at next read attempt
7873 inputStandBy();
7874 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007875 }
7876 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007877 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007878 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007879 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007880 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007881
Andy Hung8946a282018-04-19 20:04:56 -07007882#ifdef TEE_SINK
7883 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7884#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007885 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007886 {
7887 size_t part1 = mRsmpInFramesP2 - rear;
7888 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007889 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007890 (framesRead - part1) * mFrameSize);
7891 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007892 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007893 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007894
7895 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007896
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007897 // loop over each active track
7898 for (size_t i = 0; i < size; i++) {
7899 activeTrack = activeTracks[i];
7900
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007901 // skip fast tracks, as those are handled directly by FastCapture
7902 if (activeTrack->isFastTrack()) {
7903 continue;
7904 }
7905
Andy Hung73c02e42015-03-29 01:13:58 -07007906 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007907 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7908
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007909 enum {
7910 OVERRUN_UNKNOWN,
7911 OVERRUN_TRUE,
7912 OVERRUN_FALSE
7913 } overrun = OVERRUN_UNKNOWN;
7914
7915 // loop over getNextBuffer to handle circular sink
7916 for (;;) {
7917
7918 activeTrack->mSink.frameCount = ~0;
7919 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7920 size_t framesOut = activeTrack->mSink.frameCount;
7921 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7922
Andy Hung73c02e42015-03-29 01:13:58 -07007923 // check available frames and handle overrun conditions
7924 // if the record track isn't draining fast enough.
7925 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007926 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007927 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7928 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007929 overrun = OVERRUN_TRUE;
7930 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007931 if (framesOut == 0 || framesIn == 0) {
7932 break;
7933 }
7934
Andy Hung6770c6f2015-04-07 13:43:36 -07007935 // Don't allow framesOut to be larger than what is possible with resampling
7936 // from framesIn.
7937 // This isn't strictly necessary but helps limit buffer resizing in
7938 // RecordBufferConverter. TODO: remove when no longer needed.
7939 framesOut = min(framesOut,
7940 destinationFramesPossible(
7941 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007942
7943 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007944 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007945 // straight from RecordThread buffer to RecordTrack buffer.
7946 AudioBufferProvider::Buffer buffer;
7947 buffer.frameCount = framesOut;
7948 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7949 if (status == OK && buffer.frameCount != 0) {
7950 ALOGV_IF(buffer.frameCount != framesOut,
7951 "%s() read less than expected (%zu vs %zu)",
7952 __func__, buffer.frameCount, framesOut);
7953 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007954 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007955 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7956 } else {
7957 framesOut = 0;
7958 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7959 __func__, status, buffer.frameCount);
7960 }
7961 } else {
7962 // process frames from the RecordThread buffer provider to the RecordTrack
7963 // buffer
7964 framesOut = activeTrack->mRecordBufferConverter->convert(
7965 activeTrack->mSink.raw,
7966 activeTrack->mResamplerBufferProvider,
7967 framesOut);
7968 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007969
7970 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7971 overrun = OVERRUN_FALSE;
7972 }
7973
7974 if (activeTrack->mFramesToDrop == 0) {
7975 if (framesOut > 0) {
7976 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007977 // Sanitize before releasing if the track has no access to the source data
7978 // An idle UID receives silence from non virtual devices until active
7979 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007980 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007981 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007982 activeTrack->releaseBuffer(&activeTrack->mSink);
7983 }
7984 } else {
7985 // FIXME could do a partial drop of framesOut
7986 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007987 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007988 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007989 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007990 }
7991 } else {
7992 activeTrack->mFramesToDrop += framesOut;
7993 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7994 activeTrack->mSyncStartEvent->isCancelled()) {
7995 ALOGW("Synced record %s, session %d, trigger session %d",
7996 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7997 activeTrack->sessionId(),
7998 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007999 activeTrack->mSyncStartEvent->triggerSession() :
8000 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008001 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008002 }
8003 }
8004 }
8005
8006 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008007 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008008 }
8009 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008010
8011 switch (overrun) {
8012 case OVERRUN_TRUE:
8013 // client isn't retrieving buffers fast enough
8014 if (!activeTrack->setOverflow()) {
8015 nsecs_t now = systemTime();
8016 // FIXME should lastWarning per track?
8017 if ((now - lastWarning) > kWarningThrottleNs) {
8018 ALOGW("RecordThread: buffer overflow");
8019 lastWarning = now;
8020 }
8021 }
8022 break;
8023 case OVERRUN_FALSE:
8024 activeTrack->clearOverflow();
8025 break;
8026 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008027 break;
8028 }
8029
Andy Hung3f0c9022016-01-15 17:49:46 -08008030 // update frame information and push timestamp out
8031 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008032 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008033 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8034 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008035 }
8036
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008037unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008038 // enable changes in effect chain
8039 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008040 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008041 if (audio_has_proportional_frames(mFormat)
8042 && loopCount == lastLoopCountRead + 1) {
8043 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8044 const double jitterMs =
8045 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8046 {framesRead, readPeriodNs},
8047 {0, 0} /* lastTimestamp */, mSampleRate);
8048 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8049
8050 Mutex::Autolock _l(mLock);
8051 mIoJitterMs.add(jitterMs);
8052 mProcessTimeMs.add(processMs);
8053 }
8054 // update timing info.
8055 mLastIoBeginNs = lastIoBeginNs;
8056 mLastIoEndNs = lastIoEndNs;
8057 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008058 }
8059
Glenn Kasten93e471f2013-08-19 08:40:07 -07008060 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008061
8062 {
8063 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008064 for (size_t i = 0; i < mTracks.size(); i++) {
8065 sp<RecordTrack> track = mTracks[i];
8066 track->invalidate();
8067 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008068 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008069 mStartStopCond.broadcast();
8070 }
8071
8072 releaseWakeLock();
8073
8074 ALOGV("RecordThread %p exiting", this);
8075 return false;
8076}
8077
Glenn Kasten93e471f2013-08-19 08:40:07 -07008078void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008079{
8080 if (!mStandby) {
8081 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008082 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08008083 mStandby = true;
8084 }
8085}
8086
8087void AudioFlinger::RecordThread::inputStandBy()
8088{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008089 // Idle the fast capture if it's currently running
8090 if (mFastCapture != 0) {
8091 FastCaptureStateQueue *sq = mFastCapture->sq();
8092 FastCaptureState *state = sq->begin();
8093 if (!(state->mCommand & FastCaptureState::IDLE)) {
8094 state->mCommand = FastCaptureState::COLD_IDLE;
8095 state->mColdFutexAddr = &mFastCaptureFutex;
8096 state->mColdGen++;
8097 mFastCaptureFutex = 0;
8098 sq->end();
8099 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8100 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8101#if 0
8102 if (kUseFastCapture == FastCapture_Dynamic) {
8103 // FIXME
8104 }
8105#endif
8106#ifdef AUDIO_WATCHDOG
8107 // FIXME
8108#endif
8109 } else {
8110 sq->end(false /*didModify*/);
8111 }
8112 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008113 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008114 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008115
8116 // If going into standby, flush the pipe source.
8117 if (mPipeSource.get() != nullptr) {
8118 const ssize_t flushed = mPipeSource->flush();
8119 if (flushed > 0) {
8120 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8121 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8122 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8123 }
8124 }
Eric Laurent81784c32012-11-19 14:55:58 -08008125}
8126
Glenn Kasten05997e22014-03-13 15:08:33 -07008127// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008128sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008129 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008130 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008131 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008132 audio_format_t format,
8133 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008134 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008135 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008136 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008137 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008138 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008139 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008140 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008141 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008142 audio_port_handle_t portId,
8143 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008144{
Glenn Kasten74935e42013-12-19 08:56:45 -08008145 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008146 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008147 sp<RecordTrack> track;
8148 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008149 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008150 audio_input_flags_t requestedFlags = *flags;
8151 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00008152 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8153 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008154
8155 lStatus = initCheck();
8156 if (lStatus != NO_ERROR) {
8157 ALOGE("createRecordTrack_l() audio driver not initialized");
8158 goto Exit;
8159 }
8160
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008161 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8162 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8163 lStatus = BAD_VALUE;
8164 goto Exit;
8165 }
8166
Eric Laurentec376dc2021-04-08 20:41:22 +02008167 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00008168 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008169 lStatus = PERMISSION_DENIED;
8170 goto Exit;
8171 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008172 if (maxSharedAudioHistoryMs < 0
8173 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8174 lStatus = BAD_VALUE;
8175 goto Exit;
8176 }
8177 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008178 if (*pSampleRate == 0) {
8179 *pSampleRate = mSampleRate;
8180 }
8181 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008182
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008183 // special case for FAST flag considered OK if fast capture is present and access to
8184 // audio history is not required
8185 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008186 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8187 }
8188
Eric Laurentf14db3c2017-12-08 14:20:36 -08008189 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008190 if ((*flags & inputFlags) != *flags) {
8191 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8192 " input flags (%08x)",
8193 *flags, inputFlags);
8194 *flags = (audio_input_flags_t)(*flags & inputFlags);
8195 }
Eric Laurent81784c32012-11-19 14:55:58 -08008196
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008197 // client expresses a preference for FAST and no access to audio history,
8198 // but we get the final say
8199 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008200 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008201 // we formerly checked for a callback handler (non-0 tid),
8202 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008203 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008204 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008205 // Frame count is not specified (0), or is less than or equal the pipe depth.
8206 // It is OK to provide a higher capacity than requested.
8207 // We will force it to mPipeFramesP2 below.
8208 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008209 // PCM data
8210 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008211 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008212 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008213 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008214 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008215 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008216 hasFastCapture() &&
8217 // there are sufficient fast track slots available
8218 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008219 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008220 // check compatibility with audio effects.
8221 Mutex::Autolock _l(mLock);
8222 // Do not accept FAST flag if the session has software effects
8223 sp<EffectChain> chain = getEffectChain_l(sessionId);
8224 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008225 audio_input_flags_t old = *flags;
8226 chain->checkInputFlagCompatibility(flags);
8227 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008228 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8229 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008230 }
8231 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008232 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008233 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8234 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008235 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008236 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8237 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008238 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008239 this, frameCount, mFrameCount, mPipeFramesP2,
8240 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008241 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008242 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008243 }
8244 }
8245
Eric Laurentf14db3c2017-12-08 14:20:36 -08008246 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8247 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8248 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8249 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8250 lStatus = BAD_TYPE;
8251 goto Exit;
8252 }
8253
Glenn Kasten74105912014-07-03 12:28:53 -07008254 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008255 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008256 // fast track: frame count is exactly the pipe depth
8257 frameCount = mPipeFramesP2;
8258 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008259 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008260 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008261 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8262 // or 20 ms if there is a fast capture
8263 // TODO This could be a roundupRatio inline, and const
8264 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8265 * sampleRate + mSampleRate - 1) / mSampleRate;
8266 // minimum number of notification periods is at least kMinNotifications,
8267 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8268 static const size_t kMinNotifications = 3;
8269 static const uint32_t kMinMs = 30;
8270 // TODO This could be a roundupRatio inline
8271 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8272 // TODO This could be a roundupRatio inline
8273 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8274 maxNotificationFrames;
8275 const size_t minFrameCount = maxNotificationFrames *
8276 max(kMinNotifications, minNotificationsByMs);
8277 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008278 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8279 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008280 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008281 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008282 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008283 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008284
8285 { // scope for mLock
8286 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008287 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008288 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008289 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008290 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008291 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008292 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008293 }
Eric Laurent81784c32012-11-19 14:55:58 -08008294
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008295 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008296 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008297 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008298 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8299 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008300
Glenn Kasten03003332013-08-06 15:40:54 -07008301 lStatus = track->initCheck();
8302 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008303 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008304 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008305 goto Exit;
8306 }
8307 mTracks.add(track);
8308
Eric Laurent05067782016-06-01 18:27:28 -07008309 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008310 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8311 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8312 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008313 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008314 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008315
8316 if (maxSharedAudioHistoryMs != 0) {
8317 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8318 }
Eric Laurent81784c32012-11-19 14:55:58 -08008319 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008320
Eric Laurent81784c32012-11-19 14:55:58 -08008321 lStatus = NO_ERROR;
8322
8323Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008324 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008325 return track;
8326}
8327
8328status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8329 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008330 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008331{
8332 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8333 sp<ThreadBase> strongMe = this;
8334 status_t status = NO_ERROR;
8335
8336 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008337 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008338 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008339 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008340 triggerSession,
8341 recordTrack->sessionId(),
8342 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008343 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008344 // Sync event can be cancelled by the trigger session if the track is not in a
8345 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008346 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008347 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008348 } else {
8349 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008350 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008351 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008352 }
8353 }
8354
8355 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008356 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008357 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008358 if (recordTrack->isInvalid()) {
8359 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008360 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8361 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008362 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008363 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8364 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008365 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8366 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008367 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008368 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008369 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008370 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008371 }
8372 return status;
8373 }
8374
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008375 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8376 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8377 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008378 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008379 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008380 status_t status = NO_ERROR;
8381 if (recordTrack->isExternalTrack()) {
8382 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008383 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008384 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008385 if (recordTrack->isInvalid()) {
8386 recordTrack->clearSyncStartEvent();
8387 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8388 recordTrack->mState = TrackBase::STARTING_2;
8389 // STARTING_2 forces destroy to call stopInput.
8390 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008391 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8392 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008393 }
8394 if (recordTrack->mState != TrackBase::STARTING_1) {
8395 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008396 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008397 // Someone else has changed state, let them take over,
8398 // leave mState in the new state.
8399 recordTrack->clearSyncStartEvent();
8400 return INVALID_OPERATION;
8401 }
8402 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008403 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008404 ALOGW("%s(%d): startInput failed, status %d",
8405 __func__, recordTrack->id(), status);
8406 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8407 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008408 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008409 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008410 return status;
8411 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008412 sendIoConfigEvent_l(
8413 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008414 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008415
8416 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8417
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008418 // Catch up with current buffer indices if thread is already running.
8419 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8420 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8421 // see previously buffered data before it called start(), but with greater risk of overrun.
8422
Andy Hung73c02e42015-03-29 01:13:58 -07008423 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008424 if (!recordTrack->isDirect()) {
8425 // clear any converter state as new data will be discontinuous
8426 recordTrack->mRecordBufferConverter->reset();
8427 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008428 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008429 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008430 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008431 return status;
8432 }
Eric Laurent81784c32012-11-19 14:55:58 -08008433}
8434
Eric Laurent81784c32012-11-19 14:55:58 -08008435void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8436{
8437 sp<SyncEvent> strongEvent = event.promote();
8438
8439 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008440 sp<RefBase> ptr = strongEvent->cookie().promote();
8441 if (ptr != 0) {
8442 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8443 recordTrack->handleSyncStartEvent(strongEvent);
8444 }
Eric Laurent81784c32012-11-19 14:55:58 -08008445 }
8446}
8447
Glenn Kastena8356f62013-07-25 14:37:52 -07008448bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008449 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008450 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008451 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008452 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008453 return false;
8454 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008455 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008456 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008457
Andy Hungabfab202019-03-07 19:45:54 -08008458 // NOTE: Waiting here is important to keep stop synchronous.
8459 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008460 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8461 mWaitWorkCV.broadcast(); // signal thread to stop
8462 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008463 }
Andy Hungce685402018-10-05 17:23:27 -07008464
8465 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008466 ALOGV("Record stopped OK");
8467 return true;
8468 }
Andy Hungce685402018-10-05 17:23:27 -07008469
8470 // don't handle anything - we've been invalidated or restarted and in a different state
8471 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8472 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008473 return false;
8474}
8475
Glenn Kasten0f11b512014-01-31 16:18:54 -08008476bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008477{
8478 return false;
8479}
8480
Glenn Kasten0f11b512014-01-31 16:18:54 -08008481status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008482{
8483#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8484 if (!isValidSyncEvent(event)) {
8485 return BAD_VALUE;
8486 }
8487
Glenn Kastend848eb42016-03-08 13:42:11 -08008488 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008489 status_t ret = NAME_NOT_FOUND;
8490
8491 Mutex::Autolock _l(mLock);
8492
8493 for (size_t i = 0; i < mTracks.size(); i++) {
8494 sp<RecordTrack> track = mTracks[i];
8495 if (eventSession == track->sessionId()) {
8496 (void) track->setSyncEvent(event);
8497 ret = NO_ERROR;
8498 }
8499 }
8500 return ret;
8501#else
8502 return BAD_VALUE;
8503#endif
8504}
8505
jiabin653cc0a2018-01-17 17:54:10 -08008506status_t AudioFlinger::RecordThread::getActiveMicrophones(
8507 std::vector<media::MicrophoneInfo>* activeMicrophones)
8508{
8509 ALOGV("RecordThread::getActiveMicrophones");
8510 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008511 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008512 return NO_INIT;
8513 }
jiabin9ff780e2018-03-19 18:19:52 -07008514 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8515 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008516}
8517
Paul McLean12340082019-03-19 09:35:05 -06008518status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8519 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008520{
Paul McLean12340082019-03-19 09:35:05 -06008521 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008522 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008523 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008524 return NO_INIT;
8525 }
Paul McLean12340082019-03-19 09:35:05 -06008526 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008527}
8528
Paul McLean12340082019-03-19 09:35:05 -06008529status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008530{
Paul McLean12340082019-03-19 09:35:05 -06008531 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008532 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008533 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008534 return NO_INIT;
8535 }
Paul McLean12340082019-03-19 09:35:05 -06008536 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008537}
8538
Eric Laurentec376dc2021-04-08 20:41:22 +02008539status_t AudioFlinger::RecordThread::shareAudioHistory(
8540 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8541 int64_t sharedAudioStartMs) {
8542 AutoMutex _l(mLock);
8543 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8544}
8545
8546status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8547 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8548 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008549
Eric Laurentec376dc2021-04-08 20:41:22 +02008550 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8551 return BAD_VALUE;
8552 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008553
8554 if (sharedAudioStartMs < 0
8555 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008556 return BAD_VALUE;
8557 }
8558
Eric Laurent2407ce32021-04-26 14:56:03 +02008559 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8560 // As we cannot detect more than one wraparound, only accept values up current write position
8561 // after one wraparound
8562 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8563 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008564 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008565 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8566 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008567 // Bring the start frame position within the input buffer to match the documented
8568 // "best effort" behavior of the API.
8569 if (sharedOffset < 0) {
8570 sharedAudioStartFrames = mRsmpInRear;
8571 } else if (sharedOffset > mRsmpInFrames) {
8572 sharedAudioStartFrames =
8573 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008574 }
8575
Eric Laurentec376dc2021-04-08 20:41:22 +02008576 mSharedAudioPackageName = sharedAudioPackageName;
8577 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008578 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008579 } else {
8580 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008581 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008582 }
8583 return NO_ERROR;
8584}
8585
Eric Laurent92d0a322021-07-16 15:32:33 +02008586void AudioFlinger::RecordThread::resetAudioHistory_l() {
8587 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8588 mSharedAudioStartFrames = -1;
8589 mSharedAudioPackageName = "";
8590}
8591
Kevin Rocard069c2712018-03-29 19:09:14 -07008592void AudioFlinger::RecordThread::updateMetadata_l()
8593{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008594 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8595 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008596 }
8597 StreamInHalInterface::SinkMetadata metadata;
8598 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008599 // Do not forward PatchRecord metadata to audio HAL
8600 if (track->isPatchTrack()) {
8601 continue;
8602 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008603 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008604 record_track_metadata_v7_t trackMetadata;
8605 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008606 .source = track->attributes().source,
8607 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008608 };
8609 trackMetadata.channel_mask = track->channelMask(),
8610 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8611
8612 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008613 }
8614 mInput->stream->updateSinkMetadata(metadata);
8615}
8616
Eric Laurent81784c32012-11-19 14:55:58 -08008617// destroyTrack_l() must be called with ThreadBase::mLock held
8618void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8619{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008620 track->terminate();
8621 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008622
Eric Laurent81784c32012-11-19 14:55:58 -08008623 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008624 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008625 removeTrack_l(track);
8626 }
8627}
8628
8629void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8630{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008631 String8 result;
8632 track->appendDump(result, false /* active */);
8633 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8634
Eric Laurent81784c32012-11-19 14:55:58 -08008635 mTracks.remove(track);
8636 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008637 if (track->isFastTrack()) {
8638 ALOG_ASSERT(!mFastTrackAvail);
8639 mFastTrackAvail = true;
8640 }
Eric Laurent81784c32012-11-19 14:55:58 -08008641}
8642
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008643void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008644{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008645 AudioStreamIn *input = mInput;
8646 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8647 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008648 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008649 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008650 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008651 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008652 }
Andy Hungbfa64962017-06-12 14:43:19 -07008653
8654 if (input != nullptr) {
8655 dprintf(fd, " Hal stream dump:\n");
8656 (void)input->stream->dump(fd);
8657 }
8658
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008659 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008660 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008661
Glenn Kasten2f90c512015-12-02 11:40:09 -08008662 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8663 // while we are dumping it. It may be inconsistent, but it won't mutate!
8664 // This is a large object so we place it on the heap.
8665 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008666 const std::unique_ptr<FastCaptureDumpState> copy =
8667 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008668 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008669}
8670
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008671void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008672{
Eric Laurent81784c32012-11-19 14:55:58 -08008673 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008674 size_t numtracks = mTracks.size();
8675 size_t numactive = mActiveTracks.size();
8676 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008677 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008678 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008679 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008680 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008681 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008682 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008683 for (size_t i = 0; i < numtracks ; ++i) {
8684 sp<RecordTrack> track = mTracks[i];
8685 if (track != 0) {
8686 bool active = mActiveTracks.indexOf(track) >= 0;
8687 if (active) {
8688 numactiveseen++;
8689 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008690 result.append(prefix);
8691 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008692 }
Eric Laurent81784c32012-11-19 14:55:58 -08008693 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008694 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008695 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008696 }
8697
Marco Nelissenb2208842014-02-07 14:00:50 -08008698 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008699 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008700 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008701 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008702 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008703 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008704 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008705 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008706 result.append(prefix);
8707 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008708 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008709 }
Eric Laurent81784c32012-11-19 14:55:58 -08008710
8711 }
8712 write(fd, result.string(), result.size());
8713}
8714
Eric Laurent5ada82e2019-08-29 17:53:54 -07008715void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008716{
8717 Mutex::Autolock _l(mLock);
8718 for (size_t i = 0; i < mTracks.size() ; i++) {
8719 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008720 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008721 track->setSilenced(silenced);
8722 }
8723 }
8724}
Andy Hung73c02e42015-03-29 01:13:58 -07008725
8726void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8727{
8728 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8729 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008730 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008731 const int32_t rear = recordThread->mRsmpInRear;
8732 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008733 if (mRecordTrack->startFrames() >= 0) {
8734 int32_t startFrames = mRecordTrack->startFrames();
8735 // Accept a recent wraparound of mRsmpInRear
8736 if (startFrames <= rear) {
8737 deltaFrames = rear - startFrames;
8738 } else {
8739 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008740 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008741 // start frame cannot be further in the past than start of resampling buffer
8742 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8743 deltaFrames = recordThread->mRsmpInFrames;
8744 }
8745 }
8746 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008747}
8748
8749void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8750 size_t *framesAvailable, bool *hasOverrun)
8751{
8752 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8753 RecordThread *recordThread = (RecordThread *) threadBase.get();
8754 const int32_t rear = recordThread->mRsmpInRear;
8755 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008756 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008757
8758 size_t framesIn;
8759 bool overrun = false;
8760 if (filled < 0) {
8761 // should not happen, but treat like a massive overrun and re-sync
8762 framesIn = 0;
8763 mRsmpInFront = rear;
8764 overrun = true;
8765 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8766 framesIn = (size_t) filled;
8767 } else {
8768 // client is not keeping up with server, but give it latest data
8769 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008770 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8771 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008772 overrun = true;
8773 }
8774 if (framesAvailable != NULL) {
8775 *framesAvailable = framesIn;
8776 }
8777 if (hasOverrun != NULL) {
8778 *hasOverrun = overrun;
8779 }
8780}
8781
Eric Laurent81784c32012-11-19 14:55:58 -08008782// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008783status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008784 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008785{
Andy Hung73c02e42015-03-29 01:13:58 -07008786 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008787 if (threadBase == 0) {
8788 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008789 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008790 return NOT_ENOUGH_DATA;
8791 }
8792 RecordThread *recordThread = (RecordThread *) threadBase.get();
8793 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008794 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008795 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008796 // FIXME should not be P2 (don't want to increase latency)
8797 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008798 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008799 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008800
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008801 front &= recordThread->mRsmpInFramesP2 - 1;
8802 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008803 if (part1 > (size_t) filled) {
8804 part1 = filled;
8805 }
8806 size_t ask = buffer->frameCount;
8807 ALOG_ASSERT(ask > 0);
8808 if (part1 > ask) {
8809 part1 = ask;
8810 }
8811 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008812 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008813 buffer->raw = NULL;
8814 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008815 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008816 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008817 }
8818
Andy Hung57446612015-04-19 23:56:46 -07008819 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008820 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008821 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008822 return NO_ERROR;
8823}
8824
8825// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008826void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8827 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008828{
Hongwei Wang95e37682019-04-12 11:13:36 -07008829 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008830 if (stepCount == 0) {
8831 return;
8832 }
Andy Hung73c02e42015-03-29 01:13:58 -07008833 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8834 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008835 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008836 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008837 buffer->frameCount = 0;
8838}
8839
Eric Laurentd8365c52017-07-16 15:27:05 -07008840void AudioFlinger::RecordThread::checkBtNrec()
8841{
8842 Mutex::Autolock _l(mLock);
8843 checkBtNrec_l();
8844}
8845
8846void AudioFlinger::RecordThread::checkBtNrec_l()
8847{
8848 // disable AEC and NS if the device is a BT SCO headset supporting those
8849 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008850 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008851 mAudioFlinger->btNrecIsOff();
8852 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8853 for (size_t i = 0; i < mEffectChains.size(); i++) {
8854 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8855 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8856 }
8857 }
8858}
8859
Andy Hung97a893e2015-03-29 01:03:07 -07008860
Eric Laurent10351942014-05-08 18:49:52 -07008861bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8862 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008863{
8864 bool reconfig = false;
8865
Eric Laurent10351942014-05-08 18:49:52 -07008866 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008867
Eric Laurent10351942014-05-08 18:49:52 -07008868 audio_format_t reqFormat = mFormat;
8869 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008870 // 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 -07008871 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8872
8873 AudioParameter param = AudioParameter(keyValuePair);
8874 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008875
8876 // scope for AutoPark extends to end of method
8877 AutoPark<FastCapture> park(mFastCapture);
8878
Eric Laurent10351942014-05-08 18:49:52 -07008879 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8880 // channel count change can be requested. Do we mandate the first client defines the
8881 // HAL sampling rate and channel count or do we allow changes on the fly?
8882 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8883 samplingRate = value;
8884 reconfig = true;
8885 }
8886 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008887 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008888 status = BAD_VALUE;
8889 } else {
8890 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008891 reconfig = true;
8892 }
Eric Laurent10351942014-05-08 18:49:52 -07008893 }
8894 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8895 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008896 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008897 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008898 status = BAD_VALUE;
8899 } else {
8900 channelMask = mask;
8901 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008902 }
Eric Laurent10351942014-05-08 18:49:52 -07008903 }
8904 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8905 // do not accept frame count changes if tracks are open as the track buffer
8906 // size depends on frame count and correct behavior would not be guaranteed
8907 // if frame count is changed after track creation
8908 if (mActiveTracks.size() > 0) {
8909 status = INVALID_OPERATION;
8910 } else {
8911 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008912 }
Eric Laurent10351942014-05-08 18:49:52 -07008913 }
8914 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008915 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008916 }
8917 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8918 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008919 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008920 }
Glenn Kastene198c362013-08-13 09:13:36 -07008921
Eric Laurent10351942014-05-08 18:49:52 -07008922 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008923 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008924 if (status == INVALID_OPERATION) {
8925 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008926 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008927 }
8928 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008929 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008930 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8931 if (mInput->stream->getAudioProperties(&config) == OK &&
8932 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8933 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008934 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008935 status = NO_ERROR;
8936 }
Eric Laurent81784c32012-11-19 14:55:58 -08008937 }
Eric Laurent10351942014-05-08 18:49:52 -07008938 if (status == NO_ERROR) {
8939 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008940 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008941 }
8942 }
Eric Laurent81784c32012-11-19 14:55:58 -08008943 }
Eric Laurent10351942014-05-08 18:49:52 -07008944
Eric Laurent81784c32012-11-19 14:55:58 -08008945 return reconfig;
8946}
8947
8948String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8949{
Eric Laurent81784c32012-11-19 14:55:58 -08008950 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008951 if (initCheck() == NO_ERROR) {
8952 String8 out_s8;
8953 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8954 return out_s8;
8955 }
Eric Laurent81784c32012-11-19 14:55:58 -08008956 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008957 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008958}
8959
Mikhail Naganov88536df2021-07-26 17:30:29 -07008960void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008961 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07008962 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08008963 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008964 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008965 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008966 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008967 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
8968 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08008969 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008970 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008971 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07008972 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008973 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008974 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008975 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08008976 break;
8977 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008978 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008979}
8980
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008981void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008982{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008983 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8984 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008985 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008986 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8987 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008988 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8989 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008990 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008991 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008992 ALOGI("HAL format %#x is not linear pcm", mFormat);
8993 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008994 result = mInput->stream->getFrameSize(&mFrameSize);
8995 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008996 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8997 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008998 result = mInput->stream->getBufferSize(&mBufferSize);
8999 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009000 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009001 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9002 "mBufferSize=%zu, mFrameCount=%zu",
9003 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009004
Eric Laurentec376dc2021-04-08 20:41:22 +02009005 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9006 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009007 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009008
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009009 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9010 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009011
9012 audio_input_flags_t flags = mInput->flags;
9013 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9014 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9015 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9016 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9017 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9018 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9019 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9020 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9021 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009022}
9023
Glenn Kasten5f972c02014-01-13 09:59:31 -08009024uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009025{
9026 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009027 uint32_t result;
9028 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9029 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009030 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009031 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009032}
9033
Glenn Kastend848eb42016-03-08 13:42:11 -08009034KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009035{
Glenn Kastend848eb42016-03-08 13:42:11 -08009036 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009037 Mutex::Autolock _l(mLock);
9038 for (size_t j = 0; j < mTracks.size(); ++j) {
9039 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009040 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009041 if (ids.indexOfKey(sessionId) < 0) {
9042 ids.add(sessionId, true);
9043 }
9044 }
9045 return ids;
9046}
9047
9048AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9049{
9050 Mutex::Autolock _l(mLock);
9051 AudioStreamIn *input = mInput;
9052 mInput = NULL;
9053 return input;
9054}
9055
9056// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009057sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009058{
9059 if (mInput == NULL) {
9060 return NULL;
9061 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009062 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009063}
9064
9065status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9066{
Eric Laurent81784c32012-11-19 14:55:58 -08009067 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009068 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009069 chain->setInBuffer(NULL);
9070 chain->setOutBuffer(NULL);
9071
9072 checkSuspendOnAddEffectChain_l(chain);
9073
Eric Laurent1b928682014-10-02 19:41:47 -07009074 // make sure enabled pre processing effects state is communicated to the HAL as we
9075 // just moved them to a new input stream.
9076 chain->syncHalEffectsState();
9077
Eric Laurent81784c32012-11-19 14:55:58 -08009078 mEffectChains.add(chain);
9079
9080 return NO_ERROR;
9081}
9082
9083size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9084{
9085 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009086
9087 for (size_t i = 0; i < mEffectChains.size(); i++) {
9088 if (chain == mEffectChains[i]) {
9089 mEffectChains.removeAt(i);
9090 break;
9091 }
Eric Laurent81784c32012-11-19 14:55:58 -08009092 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009093 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009094}
9095
Eric Laurent1c333e22014-05-20 10:48:17 -07009096status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9097 audio_patch_handle_t *handle)
9098{
9099 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009100
9101 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009102 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009103 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009104 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009105 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009106 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009107 }
9108
Eric Laurentd8365c52017-07-16 15:27:05 -07009109 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009110
9111 // store new source and send to effects
9112 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9113 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009114 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009115 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009116 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009117 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009118
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009119 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009120 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9121 status = hwDevice->createAudioPatch(patch->num_sources,
9122 patch->sources,
9123 patch->num_sinks,
9124 patch->sinks,
9125 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009126 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009127 char *address;
9128 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
9129 address = audio_device_address_to_parameter(
9130 patch->sources[0].ext.device.type,
9131 patch->sources[0].ext.device.address);
9132 } else {
9133 address = (char *)calloc(1, 1);
9134 }
9135 AudioParameter param = AudioParameter(String8(address));
9136 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07009137 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07009138 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07009139 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07009140 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009141 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07009142 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009143 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009144
jiabinc52b1ff2019-10-31 17:20:42 -07009145 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009146 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009147 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009148 }
Eric Laurent296fb132015-05-01 11:38:42 -07009149
Andy Hungc2b11cb2020-04-22 09:04:01 -07009150 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009151 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009152 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009153 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009154 // also dispatch to active AudioRecords
9155 for (const auto &track : mActiveTracks) {
9156 track->logEndInterval();
9157 track->logBeginInterval(pathSourcesAsString);
9158 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009159 return status;
9160}
9161
9162status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9163{
9164 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009165
jiabinc52b1ff2019-10-31 17:20:42 -07009166 mPatch = audio_patch{};
9167 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009168
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009169 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009170 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9171 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009172 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009173 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07009174 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009175 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07009176 }
9177 return status;
9178}
9179
jiabinc52b1ff2019-10-31 17:20:42 -07009180void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9181{
wendy lin56aa82b2020-12-02 15:19:55 +08009182 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009183 mOutDevices = outDevices;
9184 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9185 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009186 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009187 }
9188}
9189
Eric Laurentec376dc2021-04-08 20:41:22 +02009190int32_t AudioFlinger::RecordThread::getOldestFront_l()
9191{
9192 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009193 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009194 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009195 int32_t oldestFront = mRsmpInRear;
9196 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009197 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009198 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9199 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009200 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009201 if (filled > maxFilled) {
9202 oldestFront = front;
9203 maxFilled = filled;
9204 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009205 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009206 if (maxFilled > mRsmpInFrames) {
9207 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9208 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009209 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009210}
9211
9212void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9213{
9214 if (offset == 0) {
9215 return;
9216 }
9217 for (size_t i = 0; i < mTracks.size(); i++) {
9218 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9219 front = audio_utils::safe_sub_overflow(front, offset);
9220 mTracks[i]->mResamplerBufferProvider->setFront(front);
9221 }
9222}
9223
9224void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9225{
9226 // This is the formula for calculating the temporary buffer size.
9227 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9228 // 1 full output buffer, regardless of the alignment of the available input.
9229 // The value is somewhat arbitrary, and could probably be even larger.
9230 // A larger value should allow more old data to be read after a track calls start(),
9231 // without increasing latency.
9232 //
9233 // Note this is independent of the maximum downsampling ratio permitted for capture.
9234 size_t minRsmpInFrames = mFrameCount * 7;
9235
9236 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9237 // capture history available to another client using the same session ID:
9238 // dimension the resampler input buffer accordingly.
9239
9240 // Get oldest client read position: getOldestFront_l() must be called before altering
9241 // mRsmpInRear, or mRsmpInFrames
9242 int32_t previousFront = getOldestFront_l();
9243 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9244 int32_t previousRear = mRsmpInRear;
9245 mRsmpInRear = 0;
9246
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009247 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9248 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9249 "resizeInputBuffer_l() called with invalid max shared history %d",
9250 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009251 if (maxSharedAudioHistoryMs != 0) {
9252 // resizeInputBuffer_l should never be called with a non zero shared history if the
9253 // buffer was not already allocated
9254 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9255 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9256 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9257 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009258 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009259 return;
9260 }
9261 mRsmpInFrames = rsmpInFrames;
9262 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009263 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009264 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9265 // initialized
9266 if (mRsmpInFrames < minRsmpInFrames) {
9267 mRsmpInFrames = minRsmpInFrames;
9268 }
9269 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9270
9271 // TODO optimize audio capture buffer sizes ...
9272 // Here we calculate the size of the sliding buffer used as a source
9273 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9274 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9275 // be better to have it derived from the pipe depth in the long term.
9276 // The current value is higher than necessary. However it should not add to latency.
9277
9278 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9279 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9280
9281 void *rsmpInBuffer;
9282 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9283 // if posix_memalign fails, will segv here.
9284 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9285
9286 // Copy audio history if any from old buffer before freeing it
9287 if (previousRear != 0) {
9288 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9289 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9290
9291 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9292 previousFront &= previousRsmpInFramesP2 - 1;
9293 size_t part1 = previousRsmpInFramesP2 - previousFront;
9294 if (part1 > (size_t) unread) {
9295 part1 = unread;
9296 }
9297 if (part1 != 0) {
9298 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9299 part1 * mFrameSize);
9300 mRsmpInRear = part1;
9301 part1 = unread - part1;
9302 if (part1 != 0) {
9303 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9304 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9305 mRsmpInRear += part1;
9306 }
9307 }
9308 // Update front for all clients according to new rear
9309 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9310 } else {
9311 mRsmpInRear = 0;
9312 }
9313 free(mRsmpInBuffer);
9314 mRsmpInBuffer = rsmpInBuffer;
9315}
9316
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009317void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009318{
9319 Mutex::Autolock _l(mLock);
9320 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009321 if (record->getSource()) {
9322 mSource = record->getSource();
9323 }
Eric Laurent83b88082014-06-20 18:31:16 -07009324}
9325
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009326void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009327{
9328 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009329 if (mSource == record->getSource()) {
9330 mSource = mInput;
9331 }
Eric Laurent83b88082014-06-20 18:31:16 -07009332 destroyTrack_l(record);
9333}
9334
Mikhail Naganovdc769682018-05-04 15:34:08 -07009335void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009336{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009337 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009338 config->role = AUDIO_PORT_ROLE_SINK;
9339 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9340 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009341 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9342 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9343 config->flags.input = mInput->flags;
9344 }
Eric Laurent83b88082014-06-20 18:31:16 -07009345}
Eric Laurent1c333e22014-05-20 10:48:17 -07009346
Eric Laurent6acd1d42017-01-04 14:23:29 -08009347// ----------------------------------------------------------------------------
9348// Mmap
9349// ----------------------------------------------------------------------------
9350
9351AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9352 : mThread(thread)
9353{
Phil Burk9fabbf82017-08-03 12:02:00 -07009354 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009355}
9356
9357AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9358{
Phil Burk9fabbf82017-08-03 12:02:00 -07009359 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009360}
9361
9362status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9363 struct audio_mmap_buffer_info *info)
9364{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009365 return mThread->createMmapBuffer(minSizeFrames, info);
9366}
9367
9368status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9369{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009370 return mThread->getMmapPosition(position);
9371}
9372
jiabinb7d8c5a2020-08-26 17:24:52 -07009373status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9374 int64_t *timeNanos) {
9375 return mThread->getExternalPosition(position, timeNanos);
9376}
9377
Eric Laurenta54f1282017-07-01 19:39:32 -07009378status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009379 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009380
9381{
jiabind1f1cb62020-03-24 11:57:57 -07009382 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009383}
9384
9385status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9386{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009387 return mThread->stop(handle);
9388}
9389
Eric Laurent18b57012017-02-13 16:23:52 -08009390status_t AudioFlinger::MmapThreadHandle::standby()
9391{
Eric Laurent18b57012017-02-13 16:23:52 -08009392 return mThread->standby();
9393}
9394
Eric Laurent6acd1d42017-01-04 14:23:29 -08009395
9396AudioFlinger::MmapThread::MmapThread(
9397 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009398 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009399 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009400 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009401 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009402 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009403 mActiveTracks(&this->mLocalLog),
9404 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9405 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009406{
Eric Laurent18b57012017-02-13 16:23:52 -08009407 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009408 readHalParameters_l();
9409}
9410
9411AudioFlinger::MmapThread::~MmapThread()
9412{
9413}
9414
9415void AudioFlinger::MmapThread::onFirstRef()
9416{
9417 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9418}
9419
9420void AudioFlinger::MmapThread::disconnect()
9421{
Eric Laurent331679c2018-04-16 17:03:16 -07009422 ActiveTracks<MmapTrack> activeTracks;
9423 {
9424 Mutex::Autolock _l(mLock);
9425 for (const sp<MmapTrack> &t : mActiveTracks) {
9426 activeTracks.add(t);
9427 }
9428 }
9429 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009430 stop(t->portId());
9431 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009432 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009433 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009434 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009435 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009436 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009437 }
9438}
9439
9440
9441void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9442 audio_stream_type_t streamType __unused,
9443 audio_session_t sessionId,
9444 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009445 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009446 audio_port_handle_t portId)
9447{
9448 mAttr = *attr;
9449 mSessionId = sessionId;
9450 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009451 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009452 mPortId = portId;
9453}
9454
9455status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9456 struct audio_mmap_buffer_info *info)
9457{
9458 if (mHalStream == 0) {
9459 return NO_INIT;
9460 }
Eric Laurent18b57012017-02-13 16:23:52 -08009461 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009462 return mHalStream->createMmapBuffer(minSizeFrames, info);
9463}
9464
9465status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9466{
9467 if (mHalStream == 0) {
9468 return NO_INIT;
9469 }
9470 return mHalStream->getMmapPosition(position);
9471}
9472
Eric Laurent331679c2018-04-16 17:03:16 -07009473status_t AudioFlinger::MmapThread::exitStandby()
9474{
9475 status_t ret = mHalStream->start();
9476 if (ret != NO_ERROR) {
9477 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9478 return ret;
9479 }
Andy Hungcf10d742020-04-28 15:38:24 -07009480 if (mStandby) {
9481 mThreadMetrics.logBeginInterval();
9482 mStandby = false;
9483 }
Eric Laurent331679c2018-04-16 17:03:16 -07009484 return NO_ERROR;
9485}
9486
Eric Laurenta54f1282017-07-01 19:39:32 -07009487status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009488 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009489 audio_port_handle_t *handle)
9490{
Eric Laurenta54f1282017-07-01 19:39:32 -07009491 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009492 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009493 if (mHalStream == 0) {
9494 return NO_INIT;
9495 }
9496
9497 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009498
Eric Laurenta54f1282017-07-01 19:39:32 -07009499 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009500 // For the first track, reuse portId and session allocated when the stream was opened.
9501 ret = exitStandby();
9502 if (ret == NO_ERROR) {
9503 acquireWakeLock();
9504 }
9505 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009506 }
9507
9508 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9509
9510 audio_io_handle_t io = mId;
9511 if (isOutput()) {
9512 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9513 config.sample_rate = mSampleRate;
9514 config.channel_mask = mChannelMask;
9515 config.format = mFormat;
9516 audio_stream_type_t stream = streamType();
9517 audio_output_flags_t flags =
9518 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009519 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009520 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009521 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9522 mSessionId,
9523 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009524 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009525 &config,
9526 flags,
9527 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009528 &portId,
9529 &secondaryOutputs);
9530 ALOGD_IF(!secondaryOutputs.empty(),
9531 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009532 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009533 audio_config_base_t config;
9534 config.sample_rate = mSampleRate;
9535 config.channel_mask = mChannelMask;
9536 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009537 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009538 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009539 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009540 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009541 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009542 &config,
9543 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9544 &deviceId,
9545 &portId);
9546 }
9547 // APM should not chose a different input or output stream for the same set of attributes
9548 // and audo configuration
9549 if (ret != NO_ERROR || io != mId) {
9550 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9551 __FUNCTION__, ret, io, mId);
9552 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009553 }
9554
9555 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009556 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009557 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009558 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009559 }
9560
Eric Laurent331679c2018-04-16 17:03:16 -07009561 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009562 // abort if start is rejected by audio policy manager
9563 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009564 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009565 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009566 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009567 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009568 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009569 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009570 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009571 }
Eric Laurent331679c2018-04-16 17:03:16 -07009572 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009573 } else {
9574 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009575 }
9576 return PERMISSION_DENIED;
9577 }
9578
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009579 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009580 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009581 mChannelMask, mSessionId, isOutput(),
9582 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009583 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009584
Eric Laurent4eb58f12018-12-07 16:41:02 -08009585 if (isOutput()) {
9586 // force volume update when a new track is added
9587 mHalVolFloat = -1.0f;
9588 } else if (!track->isSilenced_l()) {
9589 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009590 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009591 t->invalidate();
9592 }
9593 }
9594
9595
Eric Laurent6acd1d42017-01-04 14:23:29 -08009596 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009597 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009598 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009599 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009600 chain->incTrackCnt();
9601 chain->incActiveTrackCnt();
9602 }
9603
Andy Hungc2b11cb2020-04-22 09:04:01 -07009604 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009605 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009606 broadcast_l();
9607
Eric Laurenta54f1282017-07-01 19:39:32 -07009608 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009609
9610 return NO_ERROR;
9611}
9612
9613status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9614{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009615 ALOGV("%s handle %d", __FUNCTION__, handle);
9616
9617 if (mHalStream == 0) {
9618 return NO_INIT;
9619 }
9620
Eric Laurenta54f1282017-07-01 19:39:32 -07009621 if (handle == mPortId) {
9622 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009623 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009624 return NO_ERROR;
9625 }
9626
Eric Laurent331679c2018-04-16 17:03:16 -07009627 Mutex::Autolock _l(mLock);
9628
Eric Laurent6acd1d42017-01-04 14:23:29 -08009629 sp<MmapTrack> track;
9630 for (const sp<MmapTrack> &t : mActiveTracks) {
9631 if (handle == t->portId()) {
9632 track = t;
9633 break;
9634 }
9635 }
9636 if (track == 0) {
9637 return BAD_VALUE;
9638 }
9639
9640 mActiveTracks.remove(track);
9641
Eric Laurent331679c2018-04-16 17:03:16 -07009642 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009643 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009644 AudioSystem::stopOutput(track->portId());
9645 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009646 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009647 AudioSystem::stopInput(track->portId());
9648 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009649 }
Eric Laurent331679c2018-04-16 17:03:16 -07009650 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009651
9652 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9653 if (chain != 0) {
9654 chain->decActiveTrackCnt();
9655 chain->decTrackCnt();
9656 }
9657
9658 broadcast_l();
9659
Eric Laurent6acd1d42017-01-04 14:23:29 -08009660 return NO_ERROR;
9661}
9662
Eric Laurent18b57012017-02-13 16:23:52 -08009663status_t AudioFlinger::MmapThread::standby()
9664{
9665 ALOGV("%s", __FUNCTION__);
9666
9667 if (mHalStream == 0) {
9668 return NO_INIT;
9669 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009670 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009671 return INVALID_OPERATION;
9672 }
9673 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009674 if (!mStandby) {
9675 mThreadMetrics.logEndInterval();
9676 mStandby = true;
9677 }
Eric Laurent18b57012017-02-13 16:23:52 -08009678 releaseWakeLock();
9679 return NO_ERROR;
9680}
9681
Eric Laurent6acd1d42017-01-04 14:23:29 -08009682
9683void AudioFlinger::MmapThread::readHalParameters_l()
9684{
9685 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9686 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9687 mFormat = mHALFormat;
9688 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9689 result = mHalStream->getFrameSize(&mFrameSize);
9690 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009691 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9692 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009693 result = mHalStream->getBufferSize(&mBufferSize);
9694 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9695 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009696
Andy Hungcf10d742020-04-28 15:38:24 -07009697 // TODO: make a readHalParameters call?
9698 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009699 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9700 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9701 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9702 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9703 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9704 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9705 /*
9706 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9707 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9708 (int32_t)mHapticChannelMask)
9709 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9710 (int32_t)mHapticChannelCount)
9711 */
9712 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9713 formatToString(mHALFormat).c_str())
9714 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9715 (int32_t)mFrameCount) // sic - added HAL
9716 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009717}
9718
9719bool AudioFlinger::MmapThread::threadLoop()
9720{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009721 checkSilentMode_l();
9722
9723 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9724
9725 while (!exitPending())
9726 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009727 Vector< sp<EffectChain> > effectChains;
9728
Andy Hung13850be2019-03-14 11:33:09 -07009729 { // under Thread lock
9730 Mutex::Autolock _l(mLock);
9731
Eric Laurent6acd1d42017-01-04 14:23:29 -08009732 if (mSignalPending) {
9733 // A signal was raised while we were unlocked
9734 mSignalPending = false;
9735 } else {
9736 if (mConfigEvents.isEmpty()) {
9737 // we're about to wait, flush the binder command buffer
9738 IPCThreadState::self()->flushCommands();
9739
9740 if (exitPending()) {
9741 break;
9742 }
9743
Eric Laurent6acd1d42017-01-04 14:23:29 -08009744 // wait until we have something to do...
9745 ALOGV("%s going to sleep", myName.string());
9746 mWaitWorkCV.wait(mLock);
9747 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009748
9749 checkSilentMode_l();
9750
9751 continue;
9752 }
9753 }
9754
9755 processConfigEvents_l();
9756
9757 processVolume_l();
9758
9759 checkInvalidTracks_l();
9760
9761 mActiveTracks.updatePowerState(this);
9762
Kevin Rocard069c2712018-03-29 19:09:14 -07009763 updateMetadata_l();
9764
Eric Laurent6acd1d42017-01-04 14:23:29 -08009765 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009766 } // release Thread lock
9767
Eric Laurent6acd1d42017-01-04 14:23:29 -08009768 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009769 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009770 }
Andy Hung13850be2019-03-14 11:33:09 -07009771
9772 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009773 unlockEffectChains(effectChains);
9774 // Effect chains will be actually deleted here if they were removed from
9775 // mEffectChains list during mixing or effects processing
9776 }
9777
9778 threadLoop_exit();
9779
9780 if (!mStandby) {
9781 threadLoop_standby();
9782 mStandby = true;
9783 }
9784
Eric Laurent6acd1d42017-01-04 14:23:29 -08009785 ALOGV("Thread %p type %d exiting", this, mType);
9786 return false;
9787}
9788
9789// checkForNewParameter_l() must be called with ThreadBase::mLock held
9790bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9791 status_t& status)
9792{
9793 AudioParameter param = AudioParameter(keyValuePair);
9794 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009795 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009796 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009797 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009798 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009799 if (sendToHal) {
9800 status = mHalStream->setParameters(keyValuePair);
9801 } else {
9802 status = NO_ERROR;
9803 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009804
9805 return false;
9806}
9807
9808String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9809{
9810 Mutex::Autolock _l(mLock);
9811 String8 out_s8;
9812 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9813 return out_s8;
9814 }
9815 return String8();
9816}
9817
Mikhail Naganov88536df2021-07-26 17:30:29 -07009818void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009819 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009820 sp<AudioIoDescriptor> desc;
9821 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009822 switch (event) {
9823 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009824 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009825 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009826 isInput = true;
9827 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009828 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009829 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009830 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009831 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
9832 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009833 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009834 case AUDIO_INPUT_CLOSED:
9835 case AUDIO_OUTPUT_CLOSED:
9836 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009837 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009838 break;
9839 }
9840 mAudioFlinger->ioConfigChanged(event, desc, pid);
9841}
9842
9843status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9844 audio_patch_handle_t *handle)
9845{
9846 status_t status = NO_ERROR;
9847
9848 // store new device and send to effects
9849 audio_devices_t type = AUDIO_DEVICE_NONE;
9850 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009851 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9852 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9853 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009854 if (isOutput()) {
9855 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009856 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9857 && !mAudioHwDev->supportsAudioPatches(),
9858 "Enumerated device type(%#x) must not be used "
9859 "as it does not support audio patches",
9860 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009861 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009862 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9863 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009864 }
9865 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009866 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009867 } else {
9868 type = patch->sources[0].ext.device.type;
9869 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009870 numDevices = mPatch.num_sources;
9871 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009872 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009873 }
9874
9875 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009876 if (isOutput()) {
9877 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9878 } else {
9879 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9880 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009881 }
9882
jiabinc52b1ff2019-10-31 17:20:42 -07009883 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009884 // store new source and send to effects
9885 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9886 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9887 for (size_t i = 0; i < mEffectChains.size(); i++) {
9888 mEffectChains[i]->setAudioSource_l(mAudioSource);
9889 }
9890 }
9891 }
9892
9893 if (mAudioHwDev->supportsAudioPatches()) {
9894 status = mHalDevice->createAudioPatch(patch->num_sources,
9895 patch->sources,
9896 patch->num_sinks,
9897 patch->sinks,
9898 handle);
9899 } else {
9900 char *address;
9901 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9902 //FIXME: we only support address on first sink with HAL version < 3.0
9903 address = audio_device_address_to_parameter(
9904 patch->sinks[0].ext.device.type,
9905 patch->sinks[0].ext.device.address);
9906 } else {
9907 address = (char *)calloc(1, 1);
9908 }
9909 AudioParameter param = AudioParameter(String8(address));
9910 free(address);
9911 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9912 if (!isOutput()) {
9913 param.addInt(String8(AudioParameter::keyInputSource),
9914 (int)patch->sinks[0].ext.mix.usecase.source);
9915 }
9916 status = mHalStream->setParameters(param.toString());
9917 *handle = AUDIO_PATCH_HANDLE_NONE;
9918 }
9919
jiabinc52b1ff2019-10-31 17:20:42 -07009920 if (numDevices == 0 || mDeviceId != deviceId) {
9921 if (isOutput()) {
9922 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9923 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009924 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009925 } else {
9926 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9927 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9928 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009929 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009930 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009931 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009932 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009933 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934 }
jiabinc52b1ff2019-10-31 17:20:42 -07009935 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009936 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937 }
9938 return status;
9939}
9940
9941status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9942{
9943 status_t status = NO_ERROR;
9944
jiabinc52b1ff2019-10-31 17:20:42 -07009945 mPatch = audio_patch{};
9946 mOutDeviceTypeAddrs.clear();
9947 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948
9949 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9950 supportsAudioPatches : false;
9951
9952 if (supportsAudioPatches) {
9953 status = mHalDevice->releaseAudioPatch(handle);
9954 } else {
9955 AudioParameter param;
9956 param.addInt(String8(AudioParameter::keyRouting), 0);
9957 status = mHalStream->setParameters(param.toString());
9958 }
9959 return status;
9960}
9961
Mikhail Naganovdc769682018-05-04 15:34:08 -07009962void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009964 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009965 if (isOutput()) {
9966 config->role = AUDIO_PORT_ROLE_SOURCE;
9967 config->ext.mix.hw_module = mAudioHwDev->handle();
9968 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9969 } else {
9970 config->role = AUDIO_PORT_ROLE_SINK;
9971 config->ext.mix.hw_module = mAudioHwDev->handle();
9972 config->ext.mix.usecase.source = mAudioSource;
9973 }
9974}
9975
9976status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9977{
9978 audio_session_t session = chain->sessionId();
9979
9980 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9981 // Attach all tracks with same session ID to this chain.
9982 // indicate all active tracks in the chain
9983 for (const sp<MmapTrack> &track : mActiveTracks) {
9984 if (session == track->sessionId()) {
9985 chain->incTrackCnt();
9986 chain->incActiveTrackCnt();
9987 }
9988 }
9989
9990 chain->setThread(this);
9991 chain->setInBuffer(nullptr);
9992 chain->setOutBuffer(nullptr);
9993 chain->syncHalEffectsState();
9994
9995 mEffectChains.add(chain);
9996 checkSuspendOnAddEffectChain_l(chain);
9997 return NO_ERROR;
9998}
9999
10000size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10001{
10002 audio_session_t session = chain->sessionId();
10003
10004 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10005
10006 for (size_t i = 0; i < mEffectChains.size(); i++) {
10007 if (chain == mEffectChains[i]) {
10008 mEffectChains.removeAt(i);
10009 // detach all active tracks from the chain
10010 // detach all tracks with same session ID from this chain
10011 for (const sp<MmapTrack> &track : mActiveTracks) {
10012 if (session == track->sessionId()) {
10013 chain->decActiveTrackCnt();
10014 chain->decTrackCnt();
10015 }
10016 }
10017 break;
10018 }
10019 }
10020 return mEffectChains.size();
10021}
10022
Eric Laurent6acd1d42017-01-04 14:23:29 -080010023void AudioFlinger::MmapThread::threadLoop_standby()
10024{
10025 mHalStream->standby();
10026}
10027
10028void AudioFlinger::MmapThread::threadLoop_exit()
10029{
Phil Burk7dce7282017-09-27 13:51:41 -070010030 // Do not call callback->onTearDown() because it is redundant for thread exit
10031 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010032}
10033
10034status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
10035{
10036 return BAD_VALUE;
10037}
10038
10039bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
10040{
10041 return false;
10042}
10043
10044status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10045 const effect_descriptor_t *desc, audio_session_t sessionId)
10046{
10047 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010048 if (audio_is_global_session(sessionId)) {
10049 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010050 desc->name, mThreadName);
10051 return BAD_VALUE;
10052 }
10053
10054 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10055 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10056 desc->name);
10057 return BAD_VALUE;
10058 }
10059 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010060 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10061 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010062 return BAD_VALUE;
10063 }
10064
10065 // Only allow effects without processing load or latency
10066 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10067 return BAD_VALUE;
10068 }
10069
jiabineb3bda02020-06-30 14:07:03 -070010070 if (EffectModule::isHapticGenerator(&desc->type)) {
10071 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10072 return BAD_VALUE;
10073 }
10074
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076}
10077
10078void AudioFlinger::MmapThread::checkInvalidTracks_l()
10079{
10080 for (const sp<MmapTrack> &track : mActiveTracks) {
10081 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010082 sp<MmapStreamCallback> callback = mCallback.promote();
10083 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010084 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -070010085 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -070010086 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -070010087 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10088 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
10089 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010091 }
10092 }
10093}
10094
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010095void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010096{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010097 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10098 mAttr.content_type, mAttr.usage, mAttr.source);
10099 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010100 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010101 dprintf(fd, " No active clients\n");
10102 }
10103}
10104
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010105void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010108 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010109 dprintf(fd, " %zu Tracks\n", numtracks);
10110 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010111 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010112 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010113 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010114 for (size_t i = 0; i < numtracks ; ++i) {
10115 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010116 result.append(prefix);
10117 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010118 }
10119 } else {
10120 dprintf(fd, "\n");
10121 }
10122 write(fd, result.string(), result.size());
10123}
10124
10125AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10126 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010127 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010128 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010130 mStreamVolume(1.0),
10131 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010132 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010133{
10134 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10135 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10136 mMasterVolume = audioFlinger->masterVolume_l();
10137 mMasterMute = audioFlinger->masterMute_l();
10138 if (mAudioHwDev) {
10139 if (mAudioHwDev->canSetMasterVolume()) {
10140 mMasterVolume = 1.0;
10141 }
10142
10143 if (mAudioHwDev->canSetMasterMute()) {
10144 mMasterMute = false;
10145 }
10146 }
10147}
10148
10149void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10150 audio_stream_type_t streamType,
10151 audio_session_t sessionId,
10152 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010153 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154 audio_port_handle_t portId)
10155{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010156 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157 mStreamType = streamType;
10158}
10159
10160AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10161{
10162 Mutex::Autolock _l(mLock);
10163 AudioStreamOut *output = mOutput;
10164 mOutput = NULL;
10165 return output;
10166}
10167
10168void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10169{
10170 Mutex::Autolock _l(mLock);
10171 // Don't apply master volume in SW if our HAL can do it for us.
10172 if (mAudioHwDev &&
10173 mAudioHwDev->canSetMasterVolume()) {
10174 mMasterVolume = 1.0;
10175 } else {
10176 mMasterVolume = value;
10177 }
10178}
10179
10180void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10181{
10182 Mutex::Autolock _l(mLock);
10183 // Don't apply master mute in SW if our HAL can do it for us.
10184 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10185 mMasterMute = false;
10186 } else {
10187 mMasterMute = muted;
10188 }
10189}
10190
10191void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10192{
10193 Mutex::Autolock _l(mLock);
10194 if (stream == mStreamType) {
10195 mStreamVolume = value;
10196 broadcast_l();
10197 }
10198}
10199
10200float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10201{
10202 Mutex::Autolock _l(mLock);
10203 if (stream == mStreamType) {
10204 return mStreamVolume;
10205 }
10206 return 0.0f;
10207}
10208
10209void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10210{
10211 Mutex::Autolock _l(mLock);
10212 if (stream == mStreamType) {
10213 mStreamMute= muted;
10214 broadcast_l();
10215 }
10216}
10217
10218void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10219{
10220 Mutex::Autolock _l(mLock);
10221 if (streamType == mStreamType) {
10222 for (const sp<MmapTrack> &track : mActiveTracks) {
10223 track->invalidate();
10224 }
10225 broadcast_l();
10226 }
10227}
10228
10229void AudioFlinger::MmapPlaybackThread::processVolume_l()
10230{
10231 float volume;
10232
10233 if (mMasterMute || mStreamMute) {
10234 volume = 0;
10235 } else {
10236 volume = mMasterVolume * mStreamVolume;
10237 }
10238
10239 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010240
10241 // Convert volumes from float to 8.24
10242 uint32_t vol = (uint32_t)(volume * (1 << 24));
10243
10244 // Delegate volume control to effect in track effect chain if needed
10245 // only one effect chain can be present on DirectOutputThread, so if
10246 // there is one, the track is connected to it
10247 if (!mEffectChains.isEmpty()) {
10248 mEffectChains[0]->setVolume_l(&vol, &vol);
10249 volume = (float)vol / (1 << 24);
10250 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010251 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010252 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10253 mHalVolFloat = volume; // HW volume control worked, so update value.
10254 mNoCallbackWarningCount = 0;
10255 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010256 sp<MmapStreamCallback> callback = mCallback.promote();
10257 if (callback != 0) {
10258 int channelCount;
10259 if (isOutput()) {
10260 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10261 } else {
10262 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10263 }
10264 Vector<float> values;
10265 for (int i = 0; i < channelCount; i++) {
10266 values.add(volume);
10267 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010268 mHalVolFloat = volume; // SW volume control worked, so update value.
10269 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010270 mLock.unlock();
10271 callback->onVolumeChanged(mChannelMask, values);
10272 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010273 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010274 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10275 ALOGW("Could not set MMAP stream volume: no volume callback!");
10276 mNoCallbackWarningCount++;
10277 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010280 for (const sp<MmapTrack> &track : mActiveTracks) {
10281 track->setMetadataHasChanged();
10282 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010283 }
10284}
10285
Kevin Rocard069c2712018-03-29 19:09:14 -070010286void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10287{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010288 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10289 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010290 }
10291 StreamOutHalInterface::SourceMetadata metadata;
10292 for (const sp<MmapTrack> &track : mActiveTracks) {
10293 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010294 playback_track_metadata_v7_t trackMetadata;
10295 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010296 .usage = track->attributes().usage,
10297 .content_type = track->attributes().content_type,
10298 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010299 };
10300 trackMetadata.channel_mask = track->channelMask(),
10301 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10302 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010303 }
10304 mOutput->stream->updateSourceMetadata(metadata);
10305}
10306
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10308{
10309 if (!mMasterMute) {
10310 char value[PROPERTY_VALUE_MAX];
10311 if (property_get("ro.audio.silent", value, "0") > 0) {
10312 char *endptr;
10313 unsigned long ul = strtoul(value, &endptr, 0);
10314 if (*endptr == '\0' && ul != 0) {
10315 ALOGD("Silence is golden");
10316 // The setprop command will not allow a property to be changed after
10317 // the first time it is set, so we don't have to worry about un-muting.
10318 setMasterMute_l(true);
10319 }
10320 }
10321 }
10322}
10323
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010324void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10325{
10326 MmapThread::toAudioPortConfig(config);
10327 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10328 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10329 config->flags.output = mOutput->flags;
10330 }
10331}
10332
jiabinb7d8c5a2020-08-26 17:24:52 -070010333status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10334 int64_t *timeNanos)
10335{
10336 if (mOutput == nullptr) {
10337 return NO_INIT;
10338 }
10339 struct timespec timestamp;
10340 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10341 if (status == NO_ERROR) {
10342 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10343 }
10344 return status;
10345}
10346
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010347void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010349 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350
Glenn Kastend3bb6452016-12-05 18:14:37 -080010351 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10352 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10354}
10355
10356AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10357 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010358 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010359 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360 mInput(input)
10361{
10362 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10363 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10364}
10365
Eric Laurent331679c2018-04-16 17:03:16 -070010366status_t AudioFlinger::MmapCaptureThread::exitStandby()
10367{
Phil Burkf054fc32018-12-06 09:45:59 -080010368 {
10369 // mInput might have been cleared by clearInput()
10370 Mutex::Autolock _l(mLock);
10371 if (mInput != nullptr && mInput->stream != nullptr) {
10372 mInput->stream->setGain(1.0f);
10373 }
10374 }
Eric Laurent331679c2018-04-16 17:03:16 -070010375 return MmapThread::exitStandby();
10376}
10377
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10379{
10380 Mutex::Autolock _l(mLock);
10381 AudioStreamIn *input = mInput;
10382 mInput = NULL;
10383 return input;
10384}
Kevin Rocard069c2712018-03-29 19:09:14 -070010385
Eric Laurent331679c2018-04-16 17:03:16 -070010386
10387void AudioFlinger::MmapCaptureThread::processVolume_l()
10388{
10389 bool changed = false;
10390 bool silenced = false;
10391
10392 sp<MmapStreamCallback> callback = mCallback.promote();
10393 if (callback == 0) {
10394 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10395 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10396 mNoCallbackWarningCount++;
10397 }
10398 }
10399
10400 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10401 // track is silenced and unmute otherwise
10402 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10403 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10404 changed = true;
10405 silenced = mActiveTracks[i]->isSilenced_l();
10406 }
10407 }
10408
10409 if (changed) {
10410 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10411 }
10412}
10413
Kevin Rocard069c2712018-03-29 19:09:14 -070010414void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10415{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010416 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10417 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010418 }
10419 StreamInHalInterface::SinkMetadata metadata;
10420 for (const sp<MmapTrack> &track : mActiveTracks) {
10421 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010422 record_track_metadata_v7_t trackMetadata;
10423 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010424 .source = track->attributes().source,
10425 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010426 };
10427 trackMetadata.channel_mask = track->channelMask(),
10428 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10429 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010430 }
10431 mInput->stream->updateSinkMetadata(metadata);
10432}
10433
Eric Laurent5ada82e2019-08-29 17:53:54 -070010434void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010435{
10436 Mutex::Autolock _l(mLock);
10437 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010438 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010439 mActiveTracks[i]->setSilenced_l(silenced);
10440 broadcast_l();
10441 }
10442 }
10443}
10444
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010445void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10446{
10447 MmapThread::toAudioPortConfig(config);
10448 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10449 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10450 config->flags.input = mInput->flags;
10451 }
10452}
10453
jiabinb7d8c5a2020-08-26 17:24:52 -070010454status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10455 uint64_t *position, int64_t *timeNanos)
10456{
10457 if (mInput == nullptr) {
10458 return NO_INIT;
10459 }
10460 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10461}
10462
Glenn Kasten63238ef2015-03-02 15:50:29 -080010463} // namespace android