blob: 67b84932119eecb3a73b5121763047d0ce0092c0 [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"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #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>
Vlad Popae8d99472022-06-30 16:02:48 +020034#include <binder/PersistableBundle.h>
jiabinc52b1ff2019-10-31 17:20:42 -070035#include <media/AudioContainers.h>
36#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070037#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070038#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080039#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080041#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080042#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080043
44#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070045#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010046#include <audio_utils/Balance.h>
Vlad Popab042ee62022-10-20 18:05:00 +020047#include <audio_utils/MelProcessor.h>
jiabinf6eb4c32020-02-25 14:06:25 -080048#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080049#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080050#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080052#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070053#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070054#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020056#include <system/audio_effects/effect_downmix.h>
57#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020058#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070059#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070062#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063#include <media/nbaio/AudioStreamOutSink.h>
64#include <media/nbaio/MonoPipe.h>
65#include <media/nbaio/MonoPipeReader.h>
66#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
68#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070070#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080073#include <powermanager/PowerManager.h>
74
Kevin Rocard7588ff42018-01-08 11:11:30 -080075#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070076#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080077
Eric Laurent81784c32012-11-19 14:55:58 -080078#include "AudioFlinger.h"
Andy Hung4b17e882023-07-07 13:47:37 -070079#include "Threads.h"
80
Andy Hungab7ef302018-05-15 19:35:29 -070081#include <mediautils/SchedulingPolicyService.h>
82#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083
Eric Laurent81784c32012-11-19 14:55:58 -080084#ifdef ADD_BATTERY_DATA
85#include <media/IMediaPlayerService.h>
86#include <media/IMediaDeathNotifier.h>
87#endif
88
Eric Laurent81784c32012-11-19 14:55:58 -080089#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070090#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091#include <cpustats/ThreadCpuUsage.h>
92#endif
93
Andy Hungd69d9f12023-05-23 17:36:46 -070094#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070095
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung0077d8c2023-05-24 11:53:47 -070097#include <afutils/TypedLogger.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080098
Eric Laurent81784c32012-11-19 14:55:58 -080099// ----------------------------------------------------------------------------
100
101// Note: the following macro is used for extremely verbose logging message. In
102// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
103// 0; but one side effect of this is to turn all LOGV's as well. Some messages
104// are so verbose that we want to suppress them even when we have ALOG_ASSERT
105// turned on. Do not uncomment the #def below unless you really know what you
106// are doing and want to see all of the extremely verbose messages.
107//#define VERY_VERY_VERBOSE_LOGGING
108#ifdef VERY_VERY_VERBOSE_LOGGING
109#define ALOGVV ALOGV
110#else
111#define ALOGVV(a...) do { } while(0)
112#endif
113
Andy Hung6770c6f2015-04-07 13:43:36 -0700114// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700115#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700116
Andy Hung6770c6f2015-04-07 13:43:36 -0700117template <typename T>
118static inline T min(const T& a, const T& b)
119{
120 return a < b ? a : b;
121}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700122
Eric Laurent81784c32012-11-19 14:55:58 -0800123namespace android {
124
Andy Hung4b17e882023-07-07 13:47:37 -0700125using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700126using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000127using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700128
Eric Laurent81784c32012-11-19 14:55:58 -0800129// retry counts for buffer fill timeout
130// 50 * ~20msecs = 1 second
131static const int8_t kMaxTrackRetries = 50;
132static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700133
Eric Laurent81784c32012-11-19 14:55:58 -0800134// allow less retry attempts on direct output thread.
135// direct outputs can be a scarce resource in audio hardware and should
136// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700137// Notes:
138// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
139// in case the data write is bursty for the AudioTrack. The application
140// should endeavor to write at least once every kMaxTrackRetriesDirectMs
141// to prevent an underrun situation. If the data is bursty, then
142// the application can also throttle the data sent to be even.
143// 2) For compressed audio data, any data present in the AudioTrack buffer
144// will be sent and reset the retry count. This delivers data as
145// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
146// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
147// of data to be available, then any remaining data is delivered.
148// This is required to ensure the last bit of data is delivered before underrun.
149//
150// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
151// or the size of the HAL period for proportional / linear PCM tracks.
152static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800153
154// don't warn about blocked writes or record buffer overflows more often than this
155static const nsecs_t kWarningThrottleNs = seconds(5);
156
157// RecordThread loop sleep time upon application overrun or audio HAL read error
158static const int kRecordThreadSleepUs = 5000;
159
Eric Laurent10351942014-05-08 18:49:52 -0700160// maximum time to wait in sendConfigEvent_l() for a status to be received
161static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800162
163// minimum sleep time for the mixer thread loop when tracks are active but in underrun
164static const uint32_t kMinThreadSleepTimeUs = 5000;
165// maximum divider applied to the active sleep time in the mixer thread loop
166static const uint32_t kMaxThreadSleepTimeShift = 2;
167
Andy Hung09a50072014-02-27 14:30:47 -0800168// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700169// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800170static const uint32_t kMinNormalSinkBufferSizeMs = 20;
171// maximum normal sink buffer size
172static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800173
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700174// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
175// FIXME This should be based on experimentally observed scheduling jitter
176static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
177
Eric Laurent972a1732013-09-04 09:42:59 -0700178// Offloaded output thread standby delay: allows track transition without going to standby
179static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
180
Eric Laurent51716182016-02-29 18:00:56 -0800181// Direct output thread minimum sleep time in idle or active(underrun) state
182static const nsecs_t kDirectMinSleepTimeUs = 10000;
183
Brian Lindahl65e90012022-07-27 18:01:07 +0200184// Minimum amount of time between checking to see if the timestamp is advancing
185// for underrun detection. If we check too frequently, we may not detect a
186// timestamp update and will falsely detect underrun.
187static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
188
Glenn Kasten1b291842016-07-18 14:55:21 -0700189// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
190// balance between power consumption and latency, and allows threads to be scheduled reliably
191// by the CFS scheduler.
192// FIXME Express other hardcoded references to 20ms with references to this constant and move
193// it appropriately.
194#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800195
Eric Laurent81784c32012-11-19 14:55:58 -0800196// Whether to use fast mixer
197static const enum {
198 FastMixer_Never, // never initialize or use: for debugging only
199 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
200 // normal mixer multiplier is 1
201 FastMixer_Static, // initialize if needed, then use all the time if initialized,
202 // multiplier is calculated based on min & max normal mixer buffer size
203 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 // FIXME for FastMixer_Dynamic:
206 // Supporting this option will require fixing HALs that can't handle large writes.
207 // For example, one HAL implementation returns an error from a large write,
208 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
209 // We could either fix the HAL implementations, or provide a wrapper that breaks
210 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
211} kUseFastMixer = FastMixer_Static;
212
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700213// Whether to use fast capture
214static const enum {
215 FastCapture_Never, // never initialize or use: for debugging only
216 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
217 FastCapture_Static, // initialize if needed, then use all the time if initialized
218} kUseFastCapture = FastCapture_Static;
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220// Priorities for requestPriority
221static const int kPriorityAudioApp = 2;
222static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700223static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800224
Glenn Kastenea38ee72016-04-18 11:08:01 -0700225// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
226// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
227// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700228
229// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800230static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800231
Glenn Kasten03490092014-05-27 12:30:54 -0700232// The minimum and maximum allowed values
233static const int kFastTrackMultiplierMin = 1;
234static const int kFastTrackMultiplierMax = 2;
235
236// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
237static int sFastTrackMultiplier = kFastTrackMultiplier;
238
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700239// See Thread::readOnlyHeap().
240// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
241// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
242// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700243static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700244
Eric Laurent81784c32012-11-19 14:55:58 -0800245// ----------------------------------------------------------------------------
246
Andy Hungb68f5eb2019-12-03 16:49:17 -0800247// TODO: move all toString helpers to audio.h
248// under #ifdef __cplusplus #endif
249static std::string patchSinksToString(const struct audio_patch *patch)
250{
251 std::stringstream ss;
252 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700253 if (i > 0) {
254 ss << "|";
255 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800256 ss << "(" << toString(patch->sinks[i].ext.device.type)
257 << ", " << patch->sinks[i].ext.device.address << ")";
258 }
259 return ss.str();
260}
261
262static std::string patchSourcesToString(const struct audio_patch *patch)
263{
264 std::stringstream ss;
265 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700266 if (i > 0) {
267 ss << "|";
268 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800269 ss << "(" << toString(patch->sources[i].ext.device.type)
270 << ", " << patch->sources[i].ext.device.address << ")";
271 }
272 return ss.str();
273}
274
Andy Hung4bd53e72022-11-17 17:21:45 -0800275static std::string toString(audio_latency_mode_t mode) {
276 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000277 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
278 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800279}
280
281// Could be made a template, but other toString overloads for std::vector are confused.
282static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
283 std::string s("{ ");
284 for (const auto& e : elements) {
285 s.append(toString(e));
286 s.append(" ");
287 }
288 s.append("}");
289 return s;
290}
291
Glenn Kasten03490092014-05-27 12:30:54 -0700292static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
293
294static void sFastTrackMultiplierInit()
295{
296 char value[PROPERTY_VALUE_MAX];
297 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
298 char *endptr;
299 unsigned long ul = strtoul(value, &endptr, 0);
300 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
301 sFastTrackMultiplier = (int) ul;
302 }
303 }
304}
305
306// ----------------------------------------------------------------------------
307
Eric Laurent81784c32012-11-19 14:55:58 -0800308#ifdef ADD_BATTERY_DATA
309// To collect the amplifier usage
310static void addBatteryData(uint32_t params) {
311 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
312 if (service == NULL) {
313 // it already logged
314 return;
315 }
316
317 service->addBatteryData(params);
318}
319#endif
320
Andy Hung3f0c9022016-01-15 17:49:46 -0800321// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
322struct {
323 // call when you acquire a partial wakelock
324 void acquire(const sp<IBinder> &wakeLockToken) {
325 pthread_mutex_lock(&mLock);
326 if (wakeLockToken.get() == nullptr) {
327 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
328 } else {
329 if (mCount == 0) {
330 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
331 }
332 ++mCount;
333 }
334 pthread_mutex_unlock(&mLock);
335 }
336
337 // call when you release a partial wakelock.
338 void release(const sp<IBinder> &wakeLockToken) {
339 if (wakeLockToken.get() == nullptr) {
340 return;
341 }
342 pthread_mutex_lock(&mLock);
343 if (--mCount < 0) {
344 ALOGE("negative wakelock count");
345 mCount = 0;
346 }
347 pthread_mutex_unlock(&mLock);
348 }
349
350 // retrieves the boottime timebase offset from monotonic.
351 int64_t getBoottimeOffset() {
352 pthread_mutex_lock(&mLock);
353 int64_t boottimeOffset = mBoottimeOffset;
354 pthread_mutex_unlock(&mLock);
355 return boottimeOffset;
356 }
357
358 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
359 // and the selected timebase.
360 // Currently only TIMEBASE_BOOTTIME is allowed.
361 //
362 // This only needs to be called upon acquiring the first partial wakelock
363 // after all other partial wakelocks are released.
364 //
365 // We do an empirical measurement of the offset rather than parsing
366 // /proc/timer_list since the latter is not a formal kernel ABI.
367 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
368 int clockbase;
369 switch (timebase) {
370 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
371 clockbase = SYSTEM_TIME_BOOTTIME;
372 break;
373 default:
374 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
375 break;
376 }
377 // try three times to get the clock offset, choose the one
378 // with the minimum gap in measurements.
379 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700380 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800381 for (int i = 0; i < tries; ++i) {
382 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
383 const nsecs_t tbase = systemTime(clockbase);
384 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
385 const nsecs_t gap = tmono2 - tmono;
386 if (i == 0 || gap < bestGap) {
387 bestGap = gap;
388 measured = tbase - ((tmono + tmono2) >> 1);
389 }
390 }
391
392 // to avoid micro-adjusting, we don't change the timebase
393 // unless it is significantly different.
394 //
395 // Assumption: It probably takes more than toleranceNs to
396 // suspend and resume the device.
397 static int64_t toleranceNs = 10000; // 10 us
398 if (llabs(*offset - measured) > toleranceNs) {
399 ALOGV("Adjusting timebase offset old: %lld new: %lld",
400 (long long)*offset, (long long)measured);
401 *offset = measured;
402 }
403 }
404
405 pthread_mutex_t mLock;
406 int32_t mCount;
407 int64_t mBoottimeOffset;
408} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800409
410// ----------------------------------------------------------------------------
411// CPU Stats
412// ----------------------------------------------------------------------------
413
414class CpuStats {
415public:
416 CpuStats();
417 void sample(const String8 &title);
418#ifdef DEBUG_CPU_USAGE
419private:
420 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700421 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800422
Andy Hung16698b82018-08-01 10:48:38 -0700423 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800424
425 int mCpuNum; // thread's current CPU number
426 int mCpukHz; // frequency of thread's current CPU in kHz
427#endif
428};
429
430CpuStats::CpuStats()
431#ifdef DEBUG_CPU_USAGE
432 : mCpuNum(-1), mCpukHz(-1)
433#endif
434{
435}
436
Glenn Kasten0f11b512014-01-31 16:18:54 -0800437void CpuStats::sample(const String8 &title
438#ifndef DEBUG_CPU_USAGE
439 __unused
440#endif
441 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800442#ifdef DEBUG_CPU_USAGE
443 // get current thread's delta CPU time in wall clock ns
444 double wcNs;
445 bool valid = mCpuUsage.sampleAndEnable(wcNs);
446
447 // record sample for wall clock statistics
448 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800450 }
451
452 // get the current CPU number
453 int cpuNum = sched_getcpu();
454
455 // get the current CPU frequency in kHz
456 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
457
458 // check if either CPU number or frequency changed
459 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
460 mCpuNum = cpuNum;
461 mCpukHz = cpukHz;
462 // ignore sample for purposes of cycles
463 valid = false;
464 }
465
466 // if no change in CPU number or frequency, then record sample for cycle statistics
467 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700468 const double cycles = wcNs * cpukHz * 0.000001;
469 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800470 }
471
Eric Tan5b13ff82018-07-27 11:20:17 -0700472 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800473 // mCpuUsage.elapsed() is expensive, so don't call it every loop
474 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700475 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800476 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700477 const double perLoop = elapsed / (double) n;
478 const double perLoop100 = perLoop * 0.01;
479 const double perLoop1k = perLoop * 0.001;
480 const double mean = mWcStats.getMean();
481 const double stddev = mWcStats.getStdDev();
482 const double minimum = mWcStats.getMin();
483 const double maximum = mWcStats.getMax();
484 const double meanCycles = mHzStats.getMean();
485 const double stddevCycles = mHzStats.getStdDev();
486 const double minCycles = mHzStats.getMin();
487 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800488 mCpuUsage.resetElapsed();
489 mWcStats.reset();
490 mHzStats.reset();
491 ALOGD("CPU usage for %s over past %.1f secs\n"
492 " (%u mixer loops at %.1f mean ms per loop):\n"
493 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
494 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
495 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
496 title.string(),
497 elapsed * .000000001, n, perLoop * .000001,
498 mean * .001,
499 stddev * .001,
500 minimum * .001,
501 maximum * .001,
502 mean / perLoop100,
503 stddev / perLoop100,
504 minimum / perLoop100,
505 maximum / perLoop100,
506 meanCycles / perLoop1k,
507 stddevCycles / perLoop1k,
508 minCycles / perLoop1k,
509 maxCycles / perLoop1k);
510
511 }
512 }
513#endif
514};
515
516// ----------------------------------------------------------------------------
517// ThreadBase
518// ----------------------------------------------------------------------------
519
Glenn Kasten97b7b752014-09-28 13:04:24 -0700520// static
Andy Hung4b17e882023-07-07 13:47:37 -0700521const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700522{
523 switch (type) {
524 case MIXER:
525 return "MIXER";
526 case DIRECT:
527 return "DIRECT";
528 case DUPLICATING:
529 return "DUPLICATING";
530 case RECORD:
531 return "RECORD";
532 case OFFLOAD:
533 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700534 case MMAP_PLAYBACK:
535 return "MMAP_PLAYBACK";
536 case MMAP_CAPTURE:
537 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200538 case SPATIALIZER:
539 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000540 case BIT_PERFECT:
541 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700542 default:
543 return "unknown";
544 }
545}
546
Andy Hung4b17e882023-07-07 13:47:37 -0700547ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700548 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800549 : Thread(false /*canCallJava*/),
550 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700551 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700552 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
553 isOut),
554 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700555 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800556 // are set by PlaybackThread::readOutputParameters_l() or
557 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700558 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700559 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700560 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800561 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700562 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800563 mSystemReady(systemReady),
564 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800565{
Andy Hungcf10d742020-04-28 15:38:24 -0700566 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700567 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800568}
569
Andy Hung4b17e882023-07-07 13:47:37 -0700570ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800571{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700572 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700573 mConfigEvents.clear();
574
Eric Laurent81784c32012-11-19 14:55:58 -0800575 // do not lock the mutex in destructor
576 releaseWakeLock_l();
577 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800578 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800579 binder->unlinkToDeath(mDeathRecipient);
580 }
Andy Hungd0979812019-02-21 15:51:44 -0800581
582 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800583}
584
Andy Hung4b17e882023-07-07 13:47:37 -0700585status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700586{
587 status_t status = initCheck();
588 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800589 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700590 } else {
591 ALOGE("No working audio driver found.");
592 }
593 return status;
594}
595
Andy Hung4b17e882023-07-07 13:47:37 -0700596void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800597{
598 ALOGV("ThreadBase::exit");
599 // do any cleanup required for exit to succeed
600 preExit();
601 {
602 // This lock prevents the following race in thread (uniprocessor for illustration):
603 // if (!exitPending()) {
604 // // context switch from here to exit()
605 // // exit() calls requestExit(), what exitPending() observes
606 // // exit() calls signal(), which is dropped since no waiters
607 // // context switch back from exit() to here
608 // mWaitWorkCV.wait(...);
609 // // now thread is hung
610 // }
611 AutoMutex lock(mLock);
612 requestExit();
613 mWaitWorkCV.broadcast();
614 }
615 // When Thread::requestExitAndWait is made virtual and this method is renamed to
616 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
617 requestExitAndWait();
618}
619
Andy Hung4b17e882023-07-07 13:47:37 -0700620status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800621{
Eric Laurent81784c32012-11-19 14:55:58 -0800622 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
623 Mutex::Autolock _l(mLock);
624
Eric Laurent10351942014-05-08 18:49:52 -0700625 return sendSetParameterConfigEvent_l(keyValuePairs);
626}
627
628// sendConfigEvent_l() must be called with ThreadBase::mLock held
629// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung4b17e882023-07-07 13:47:37 -0700630status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700631NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700632{
633 status_t status = NO_ERROR;
634
Eric Laurent72e3f392015-05-20 14:43:50 -0700635 if (event->mRequiresSystemReady && !mSystemReady) {
636 event->mWaitStatus = false;
637 mPendingConfigEvents.add(event);
638 return status;
639 }
Eric Laurent10351942014-05-08 18:49:52 -0700640 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700641 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800642 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700643 mLock.unlock();
644 {
645 Mutex::Autolock _l(event->mLock);
646 while (event->mWaitStatus) {
647 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
648 event->mStatus = TIMED_OUT;
649 event->mWaitStatus = false;
650 }
651 }
652 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800653 }
Eric Laurent10351942014-05-08 18:49:52 -0700654 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800655 return status;
656}
657
Andy Hung4b17e882023-07-07 13:47:37 -0700658void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700659 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800660{
661 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700662 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800663}
664
665// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -0700666void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700667 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800668{
Andy Hungd0979812019-02-21 15:51:44 -0800669 // The audio statistics history is exponentially weighted to forget events
670 // about five or more seconds in the past. In order to have
671 // crisper statistics for mediametrics, we reset the statistics on
672 // an IoConfigEvent, to reflect different properties for a new device.
673 mIoJitterMs.reset();
674 mLatencyMs.reset();
675 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000676 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100677 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800678
Eric Laurent09f1ed22019-04-24 17:45:17 -0700679 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700680 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800681}
682
Andy Hung4b17e882023-07-07 13:47:37 -0700683void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700684{
685 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800686 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700687}
688
Eric Laurent81784c32012-11-19 14:55:58 -0800689// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -0700690void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800691 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800692{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800693 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700694 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800695}
696
Eric Laurent10351942014-05-08 18:49:52 -0700697// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -0700698status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800699{
Andy Hung2ddee192015-12-18 17:34:44 -0800700 sp<ConfigEvent> configEvent;
701 AudioParameter param(keyValuePair);
702 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700703 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800704 setMasterMono_l(value != 0);
705 if (param.size() == 1) {
706 return NO_ERROR; // should be a solo parameter - we don't pass down
707 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700708 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800709 configEvent = new SetParameterConfigEvent(param.toString());
710 } else {
711 configEvent = new SetParameterConfigEvent(keyValuePair);
712 }
Eric Laurent10351942014-05-08 18:49:52 -0700713 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700714}
715
Andy Hung4b17e882023-07-07 13:47:37 -0700716status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700717 const struct audio_patch *patch,
718 audio_patch_handle_t *handle)
719{
720 Mutex::Autolock _l(mLock);
721 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
722 status_t status = sendConfigEvent_l(configEvent);
723 if (status == NO_ERROR) {
724 CreateAudioPatchConfigEventData *data =
725 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
726 *handle = data->mHandle;
727 }
728 return status;
729}
730
Andy Hung4b17e882023-07-07 13:47:37 -0700731status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700732 const audio_patch_handle_t handle)
733{
734 Mutex::Autolock _l(mLock);
735 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
736 return sendConfigEvent_l(configEvent);
737}
738
Andy Hung4b17e882023-07-07 13:47:37 -0700739status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700740 const DeviceDescriptorBaseVector& outDevices)
741{
742 if (type() != RECORD) {
743 // The update out device operation is only for record thread.
744 return INVALID_OPERATION;
745 }
746 Mutex::Autolock _l(mLock);
747 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
748 return sendConfigEvent_l(configEvent);
749}
750
Andy Hung4b17e882023-07-07 13:47:37 -0700751void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200752{
753 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
754 sp<ConfigEvent> configEvent =
755 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
756 sendConfigEvent_l(configEvent);
757}
Eric Laurent1c333e22014-05-20 10:48:17 -0700758
Andy Hung4b17e882023-07-07 13:47:37 -0700759void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200760{
761 Mutex::Autolock _l(mLock);
762 sendCheckOutputStageEffectsEvent_l();
763}
764
Andy Hung4b17e882023-07-07 13:47:37 -0700765void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200766{
767 sp<ConfigEvent> configEvent =
768 (ConfigEvent *)new CheckOutputStageEffectsEvent();
769 sendConfigEvent_l(configEvent);
770}
771
Andy Hung4b17e882023-07-07 13:47:37 -0700772void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200773{
774 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
775 sendConfigEvent_l(configEvent);
776}
777
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700778// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700779void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700780{
Eric Laurent10351942014-05-08 18:49:52 -0700781 bool configChanged = false;
782
Eric Laurent81784c32012-11-19 14:55:58 -0800783 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700784 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700785 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800786 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700787 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700788 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700789 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
790 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800791 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700792 true /*asynchronous*/);
793 if (err != 0) {
794 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700795 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700796 }
797 } break;
798 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700799 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700800 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700801 } break;
802 case CFG_EVENT_SET_PARAMETER: {
803 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
804 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
805 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700806 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
807 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700808 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700809 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700810 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700811 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 CreateAudioPatchConfigEventData *data =
813 (CreateAudioPatchConfigEventData *)event->mData.get();
814 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700815 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200816 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700817 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
818 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
819 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700820 } break;
821 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700822 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700823 ReleaseAudioPatchConfigEventData *data =
824 (ReleaseAudioPatchConfigEventData *)event->mData.get();
825 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700826 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200827 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700828 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
829 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
830 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
831 } break;
832 case CFG_EVENT_UPDATE_OUT_DEVICE: {
833 UpdateOutDevicesConfigEventData *data =
834 (UpdateOutDevicesConfigEventData *)event->mData.get();
835 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700836 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200837 case CFG_EVENT_RESIZE_BUFFER: {
838 ResizeBufferConfigEventData *data =
839 (ResizeBufferConfigEventData *)event->mData.get();
840 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
841 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200842
843 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
844 setCheckOutputStageEffects();
845 } break;
846
Eric Laurent68a40a82022-05-03 18:15:04 +0200847 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
848 onHalLatencyModesChanged_l();
849 } break;
850
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700851 default:
Eric Laurent10351942014-05-08 18:49:52 -0700852 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700853 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800854 }
Eric Laurent10351942014-05-08 18:49:52 -0700855 {
856 Mutex::Autolock _l(event->mLock);
857 if (event->mWaitStatus) {
858 event->mWaitStatus = false;
859 event->mCond.signal();
860 }
861 }
862 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
863 }
864
865 if (configChanged) {
866 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800867 }
Eric Laurent81784c32012-11-19 14:55:58 -0800868}
869
Marco Nelissenb2208842014-02-07 14:00:50 -0800870String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
871 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700872 const audio_channel_representation_t representation =
873 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700874
875 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800876 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700877 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
878 if (output) {
879 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
880 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700882 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700883 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
884 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
887 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
888 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
889 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
892 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
893 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
894 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700895 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
896 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
897 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
898 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
899 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
900 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
901 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700902 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700903 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
904 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700905 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
906 } else {
907 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
908 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
909 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
910 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
911 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
912 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
913 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
914 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
915 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
916 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
917 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
918 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700919 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
920 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
921 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700922 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700923 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
924 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700925 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
926 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
927 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
928 }
929 const int len = s.length();
930 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700931 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700932 s.unlockBuffer(len - 2); // remove trailing ", "
933 }
934 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800935 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700936 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
937 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
938 return s;
939 default:
940 s.appendFormat("unknown mask, representation:%d bits:%#x",
941 representation, audio_channel_mask_get_bits(mask));
942 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800943 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800944}
945
Andy Hung4b17e882023-07-07 13:47:37 -0700946void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -0700947NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800948{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800949 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
950 this, mThreadName, getTid(), type(), threadTypeToString(type()));
951
Eric Laurent81784c32012-11-19 14:55:58 -0800952 bool locked = AudioFlinger::dumpTryLock(mLock);
953 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800954 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800955 }
956
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700957 dumpBase_l(fd, args);
958 dumpInternals_l(fd, args);
959 dumpTracks_l(fd, args);
960 dumpEffectChains_l(fd, args);
961
962 if (locked) {
963 mLock.unlock();
964 }
965
966 dprintf(fd, " Local log:\n");
967 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700968
969 // --all does the statistics
970 bool dumpAll = false;
971 for (const auto &arg : args) {
972 if (arg == String16("--all")) {
973 dumpAll = true;
974 }
975 }
976 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700977 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700978 if (!sched.empty()) {
979 (void)write(fd, sched.c_str(), sched.size());
980 }
981 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700982}
983
Andy Hung4b17e882023-07-07 13:47:37 -0700984void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700985{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700986 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700987 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700988 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700989 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700990 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700991 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700992 dprintf(fd, " Channel count: %u\n", mChannelCount);
993 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800994 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700995 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700996 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700997 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800998 size_t numConfig = mConfigEvents.size();
999 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001000 const size_t SIZE = 256;
1001 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001002 for (size_t i = 0; i < numConfig; i++) {
1003 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001004 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001005 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001006 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001007 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001008 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001009 }
Andy Hung293558a2017-03-21 12:19:20 -07001010 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001011 dprintf(fd, " Output devices: %s (%s)\n",
1012 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1013 dprintf(fd, " Input device: %#x (%s)\n",
1014 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001015 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001016
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001017 // Dump timestamp statistics for the Thread types that support it.
1018 if (mType == RECORD
1019 || mType == MIXER
1020 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001021 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001022 || mType == OFFLOAD
1023 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001024 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001025 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001026 }
1027
Andy Hung446f4df2019-02-21 12:26:41 -08001028 if (mLastIoBeginNs > 0) { // MMAP may not set this
1029 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1030 isOutput() ? "write" : "read",
1031 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1032 }
1033
1034 if (mProcessTimeMs.getN() > 0) {
1035 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1036 }
1037
1038 if (mIoJitterMs.getN() > 0) {
1039 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1040 isOutput() ? "write" : "read",
1041 mIoJitterMs.toString().c_str());
1042 }
1043
Andy Hunge6c37112019-02-26 17:38:10 -08001044 if (mLatencyMs.getN() > 0) {
1045 dprintf(fd, " Threadloop %s latency stats: %s\n",
1046 isOutput() ? "write" : "read",
1047 mLatencyMs.toString().c_str());
1048 }
Robert Wu06db0a32021-08-10 19:05:34 +00001049
1050 if (mMonopipePipeDepthStats.getN() > 0) {
1051 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1052 isOutput() ? "write" : "read",
1053 mMonopipePipeDepthStats.toString().c_str());
1054 }
Eric Laurent81784c32012-11-19 14:55:58 -08001055}
1056
Andy Hung4b17e882023-07-07 13:47:37 -07001057void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001058{
1059 const size_t SIZE = 256;
1060 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001061
Marco Nelissenb2208842014-02-07 14:00:50 -08001062 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001063 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001064 write(fd, buffer, strlen(buffer));
1065
Marco Nelissenb2208842014-02-07 14:00:50 -08001066 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001067 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001068 if (chain != 0) {
1069 chain->dump(fd, args);
1070 }
1071 }
1072}
1073
Andy Hung4b17e882023-07-07 13:47:37 -07001074void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001075{
1076 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001077 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001078}
1079
Andy Hung4b17e882023-07-07 13:47:37 -07001080String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001081{
1082 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001083 case MIXER:
1084 return String16("AudioMix");
1085 case DIRECT:
1086 return String16("AudioDirectOut");
1087 case DUPLICATING:
1088 return String16("AudioDup");
1089 case RECORD:
1090 return String16("AudioIn");
1091 case OFFLOAD:
1092 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001093 case MMAP_PLAYBACK:
1094 return String16("MmapPlayback");
1095 case MMAP_CAPTURE:
1096 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001097 case SPATIALIZER:
1098 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001099 default:
1100 ALOG_ASSERT(false);
1101 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001102 }
1103}
1104
Andy Hung4b17e882023-07-07 13:47:37 -07001105void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001106{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001107 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001108 if (mPowerManager != 0) {
1109 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001110 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001111 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1112 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001113 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001114 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001115 {} /* workSource */,
1116 {} /* historyTag */);
1117 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001118 mWakeLockToken = binder;
1119 }
Chris Ye6597d732020-02-28 22:38:25 -08001120 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001121 }
Wei Jia3f273d12015-11-24 09:06:49 -08001122
Andy Hung3f0c9022016-01-15 17:49:46 -08001123 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001124 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1125 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001126}
1127
Andy Hung4b17e882023-07-07 13:47:37 -07001128void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001129{
1130 Mutex::Autolock _l(mLock);
1131 releaseWakeLock_l();
1132}
1133
Andy Hung4b17e882023-07-07 13:47:37 -07001134void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001135{
Andy Hung3f0c9022016-01-15 17:49:46 -08001136 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001137 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001138 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001139 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001140 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001141 }
1142 mWakeLockToken.clear();
1143 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001144}
1145
Andy Hung4b17e882023-07-07 13:47:37 -07001146void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001147 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001148 // use checkService() to avoid blocking if power service is not up yet
1149 sp<IBinder> binder =
1150 defaultServiceManager()->checkService(String16("power"));
1151 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001152 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001153 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001154 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001155 binder->linkToDeath(mDeathRecipient);
1156 }
1157 }
1158}
1159
Andy Hung4b17e882023-07-07 13:47:37 -07001160void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001161 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001162
1163#if !LOG_NDEBUG
1164 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001165 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001166 s << uid << " ";
1167 }
1168 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1169#endif
1170
Andy Hung438e7572015-12-14 15:51:17 -08001171 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1172 if (mSystemReady) {
1173 ALOGE("no wake lock to update, but system ready!");
1174 } else {
1175 ALOGW("no wake lock to update, system not ready yet");
1176 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001177 return;
1178 }
1179 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001180 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001181 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1182 mWakeLockToken, uidsAsInt);
1183 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001184 }
1185}
1186
Andy Hung4b17e882023-07-07 13:47:37 -07001187void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001188{
1189 Mutex::Autolock _l(mLock);
1190 releaseWakeLock_l();
1191 mPowerManager.clear();
1192}
1193
Andy Hung4b17e882023-07-07 13:47:37 -07001194void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001195 const DeviceDescriptorBaseVector& outDevices __unused)
1196{
1197 ALOGE("%s should only be called in RecordThread", __func__);
1198}
1199
Andy Hung4b17e882023-07-07 13:47:37 -07001200void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001201{
1202 ALOGE("%s should only be called in RecordThread", __func__);
1203}
1204
Andy Hung4b17e882023-07-07 13:47:37 -07001205void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001206{
1207 sp<ThreadBase> thread = mThread.promote();
1208 if (thread != 0) {
1209 thread->clearPowerManager();
1210 }
1211 ALOGW("power manager service died !!!");
1212}
1213
Andy Hung4b17e882023-07-07 13:47:37 -07001214void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001215 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001216{
Andy Hung116bc262023-06-20 18:56:17 -07001217 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001218 if (chain != 0) {
1219 if (type != NULL) {
1220 chain->setEffectSuspended_l(type, suspend);
1221 } else {
1222 chain->setEffectSuspendedAll_l(suspend);
1223 }
1224 }
1225
1226 updateSuspendedSessions_l(type, suspend, sessionId);
1227}
1228
Andy Hung4b17e882023-07-07 13:47:37 -07001229void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001230{
1231 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1232 if (index < 0) {
1233 return;
1234 }
1235
1236 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1237 mSuspendedSessions.valueAt(index);
1238
1239 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001240 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001241 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001242 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001243 chain->setEffectSuspendedAll_l(true);
1244 } else {
1245 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1246 desc->mType.timeLow);
1247 chain->setEffectSuspended_l(&desc->mType, true);
1248 }
1249 }
1250 }
1251}
1252
Andy Hung4b17e882023-07-07 13:47:37 -07001253void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001254 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001255 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001256{
1257 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1258
1259 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1260
1261 if (suspend) {
1262 if (index >= 0) {
1263 sessionEffects = mSuspendedSessions.valueAt(index);
1264 } else {
1265 mSuspendedSessions.add(sessionId, sessionEffects);
1266 }
1267 } else {
1268 if (index < 0) {
1269 return;
1270 }
1271 sessionEffects = mSuspendedSessions.valueAt(index);
1272 }
1273
1274
Andy Hung116bc262023-06-20 18:56:17 -07001275 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001276 if (type != NULL) {
1277 key = type->timeLow;
1278 }
1279 index = sessionEffects.indexOfKey(key);
1280
1281 sp<SuspendedSessionDesc> desc;
1282 if (suspend) {
1283 if (index >= 0) {
1284 desc = sessionEffects.valueAt(index);
1285 } else {
1286 desc = new SuspendedSessionDesc();
1287 if (type != NULL) {
1288 desc->mType = *type;
1289 }
1290 sessionEffects.add(key, desc);
1291 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1292 }
1293 desc->mRefCount++;
1294 } else {
1295 if (index < 0) {
1296 return;
1297 }
1298 desc = sessionEffects.valueAt(index);
1299 if (--desc->mRefCount == 0) {
1300 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1301 sessionEffects.removeItemsAt(index);
1302 if (sessionEffects.isEmpty()) {
1303 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1304 sessionId);
1305 mSuspendedSessions.removeItem(sessionId);
1306 }
1307 }
1308 }
1309 if (!sessionEffects.isEmpty()) {
1310 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1311 }
1312}
1313
Andy Hung4b17e882023-07-07 13:47:37 -07001314void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001315 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001316 bool threadLocked)
1317NO_THREAD_SAFETY_ANALYSIS // manual locking
1318{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001319 if (!threadLocked) {
1320 mLock.lock();
1321 }
Eric Laurent81784c32012-11-19 14:55:58 -08001322
Eric Laurent81784c32012-11-19 14:55:58 -08001323 if (mType != RECORD) {
1324 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1325 // another session. This gives the priority to well behaved effect control panels
1326 // and applications not using global effects.
1327 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1328 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001329 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001330 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1331 }
1332 }
1333
Eric Laurent6b446ce2019-12-13 10:56:31 -08001334 if (!threadLocked) {
1335 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001336 }
1337}
1338
Eric Laurent4c415062016-06-17 16:14:16 -07001339// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001340status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001341 const effect_descriptor_t *desc, audio_session_t sessionId)
1342{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001343 // No global output effect sessions on record threads
1344 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1345 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001346 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1347 desc->name, mThreadName);
1348 return BAD_VALUE;
1349 }
1350 // only pre processing effects on record thread
1351 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1352 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1353 desc->name, mThreadName);
1354 return BAD_VALUE;
1355 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001356
1357 // always allow effects without processing load or latency
1358 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1359 return NO_ERROR;
1360 }
1361
Eric Laurent4c415062016-06-17 16:14:16 -07001362 audio_input_flags_t flags = mInput->flags;
1363 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1364 if (flags & AUDIO_INPUT_FLAG_RAW) {
1365 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1366 desc->name, mThreadName);
1367 return BAD_VALUE;
1368 }
1369 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1370 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1371 desc->name, mThreadName);
1372 return BAD_VALUE;
1373 }
1374 }
jiabineb3bda02020-06-30 14:07:03 -07001375
Andy Hung116bc262023-06-20 18:56:17 -07001376 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001377 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1378 return BAD_VALUE;
1379 }
Eric Laurent4c415062016-06-17 16:14:16 -07001380 return NO_ERROR;
1381}
1382
1383// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001384status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001385 const effect_descriptor_t *desc, audio_session_t sessionId)
1386{
1387 // no preprocessing on playback threads
1388 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001389 ALOGW("%s: pre processing effect %s created on playback"
1390 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001391 return BAD_VALUE;
1392 }
1393
Eric Laurent3e4de772017-07-16 16:55:08 -07001394 // always allow effects without processing load or latency
1395 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1396 return NO_ERROR;
1397 }
1398
Andy Hung116bc262023-06-20 18:56:17 -07001399 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001400 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1401 __func__);
1402 return BAD_VALUE;
1403 }
1404
Eric Laurentf690c462021-09-17 14:47:03 +02001405 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1406 && mType != SPATIALIZER) {
1407 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1408 __func__, mType);
1409 return BAD_VALUE;
1410 }
1411
Eric Laurent4c415062016-06-17 16:14:16 -07001412 switch (mType) {
1413 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001414 audio_output_flags_t flags = mOutput->flags;
1415 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1416 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1417 // global effects are applied only to non fast tracks if they are SW
1418 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1419 break;
1420 }
1421 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1422 // only post processing on output stage session
1423 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001424 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1425 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001426 return BAD_VALUE;
1427 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001428 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1429 // only post processing on output stage session
1430 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001431 ALOGW("%s: non post processing effect %s not allowed on device session",
1432 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001433 return BAD_VALUE;
1434 }
Eric Laurent4c415062016-06-17 16:14:16 -07001435 } else {
1436 // no restriction on effects applied on non fast tracks
1437 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1438 break;
1439 }
1440 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001443 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001444 return BAD_VALUE;
1445 }
1446 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001447 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1448 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001449 return BAD_VALUE;
1450 }
1451 }
1452 } break;
1453 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001454 // nothing actionable on offload threads, if the effect:
1455 // - is offloadable: the effect can be created
1456 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1457 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001458 break;
1459 case DIRECT:
1460 // Reject any effect on Direct output threads for now, since the format of
1461 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001462 ALOGW("%s: effect %s on DIRECT output thread %s",
1463 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001464 return BAD_VALUE;
1465 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001466 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001467 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1468 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001469 return BAD_VALUE;
1470 }
1471 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001472 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1473 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001474 return BAD_VALUE;
1475 }
1476 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001477 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1478 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001479 return BAD_VALUE;
1480 }
1481 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001482 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001483 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1484 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1485 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1486 // are supported and added after the spatializer.
1487 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1488 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1489 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001490 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001491 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1492 // only post processing , downmixer or spatializer effects on output stage session
1493 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1494 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1495 break;
1496 }
1497 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1498 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1499 __func__, desc->name);
1500 return BAD_VALUE;
1501 }
1502 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1503 // only post processing on output stage session
1504 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1505 ALOGW("%s: non post processing effect %s not allowed on device session",
1506 __func__, desc->name);
1507 return BAD_VALUE;
1508 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001509 }
1510 break;
jiabinc658e452022-10-21 20:52:21 +00001511 case BIT_PERFECT:
1512 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1513 // Allow HW accelerated effects of tunnel type
1514 break;
1515 }
1516 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1517 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1518 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1519 // 3) there is any bit-perfect track with the given session id.
1520 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1521 sessionId == AUDIO_SESSION_DEVICE) {
1522 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1523 __func__, desc->name, mThreadName);
1524 return BAD_VALUE;
1525 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1526 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1527 __func__, desc->name, sessionId);
1528 return BAD_VALUE;
1529 }
1530 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001531 default:
1532 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1533 }
1534
1535 return NO_ERROR;
1536}
1537
Eric Laurent81784c32012-11-19 14:55:58 -08001538// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001539sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001540 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001541 const sp<IEffectClient>& effectClient,
1542 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001543 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001544 effect_descriptor_t *desc,
1545 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001546 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001547 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001548 bool probe,
1549 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001550{
Andy Hung116bc262023-06-20 18:56:17 -07001551 sp<IAfEffectModule> effect;
1552 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001553 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001554 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001555 bool chainCreated = false;
1556 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001557 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001558
1559 lStatus = initCheck();
1560 if (lStatus != NO_ERROR) {
1561 ALOGW("createEffect_l() Audio driver not initialized.");
1562 goto Exit;
1563 }
1564
Eric Laurent81784c32012-11-19 14:55:58 -08001565 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1566
1567 { // scope for mLock
1568 Mutex::Autolock _l(mLock);
1569
Eric Laurent4c415062016-06-17 16:14:16 -07001570 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001571 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001572 goto Exit;
1573 }
1574
Eric Laurent81784c32012-11-19 14:55:58 -08001575 // check for existing effect chain with the requested audio session
1576 chain = getEffectChain_l(sessionId);
1577 if (chain == 0) {
1578 // create a new chain for this session
1579 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001580 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001581 addEffectChain_l(chain);
1582 chain->setStrategy(getStrategyForSession_l(sessionId));
1583 chainCreated = true;
1584 } else {
1585 effect = chain->getEffectFromDesc_l(desc);
1586 }
1587
1588 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1589
1590 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001591 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001592 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001593 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001594 if (lStatus != NO_ERROR) {
1595 goto Exit;
1596 }
1597 effectCreated = true;
1598
jiabinc52b1ff2019-10-31 17:20:42 -07001599 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001600 effect->setDevices(outDeviceTypeAddrs());
1601 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001602 effect->setMode(mAudioFlinger->getMode());
1603 effect->setAudioSource(mAudioSource);
1604 }
jiabin1319f5a2021-03-30 22:21:24 +00001605 if (effect->isHapticGenerator()) {
1606 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1607 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001608 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1609 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1610 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001611 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001612 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001613 }
1614 }
Eric Laurent81784c32012-11-19 14:55:58 -08001615 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001616 handle = IAfEffectHandle::create(
1617 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001618 lStatus = handle->initCheck();
1619 if (lStatus == OK) {
1620 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001621 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001622 }
Eric Laurent81784c32012-11-19 14:55:58 -08001623 if (enabled != NULL) {
1624 *enabled = (int)effect->isEnabled();
1625 }
1626 }
1627
1628Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001629 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001630 Mutex::Autolock _l(mLock);
1631 if (effectCreated) {
1632 chain->removeEffect_l(effect);
1633 }
Eric Laurent81784c32012-11-19 14:55:58 -08001634 if (chainCreated) {
1635 removeEffectChain_l(chain);
1636 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001637 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001638 }
1639
Glenn Kasten9156ef32013-08-06 15:39:08 -07001640 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001641 return handle;
1642}
1643
Andy Hung4b17e882023-07-07 13:47:37 -07001644void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001645 bool unpinIfLast)
1646{
1647 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001648 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001649 {
1650 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07001651 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001652 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001653 return;
1654 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001655 effect = effectBase->asEffectModule();
1656 if (effect == nullptr) {
1657 return;
1658 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001659 // restore suspended effects if the disconnected handle was enabled and the last one.
1660 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1661 if (remove) {
1662 removeEffect_l(effect, true);
1663 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001664 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001665 }
1666 if (remove) {
1667 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001668 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001669 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001670 }
1671 }
1672}
1673
Andy Hung4b17e882023-07-07 13:47:37 -07001674void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001675 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001676 Mutex::Autolock _l(mLock);
1677 broadcast_l();
1678 }
1679 if (!effect->isOffloadable()) {
1680 if (mType == ThreadBase::OFFLOAD) {
1681 PlaybackThread *t = (PlaybackThread *)this;
1682 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1683 }
1684 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1685 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1686 }
1687 }
1688}
1689
Andy Hung4b17e882023-07-07 13:47:37 -07001690void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001691 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001692 Mutex::Autolock _l(mLock);
1693 broadcast_l();
1694 }
1695}
1696
Andy Hung4b17e882023-07-07 13:47:37 -07001697sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001698 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001699{
1700 Mutex::Autolock _l(mLock);
1701 return getEffect_l(sessionId, effectId);
1702}
1703
Andy Hung4b17e882023-07-07 13:47:37 -07001704sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001705 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001706{
Andy Hung116bc262023-06-20 18:56:17 -07001707 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001708 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1709}
1710
Andy Hung4b17e882023-07-07 13:47:37 -07001711std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001712{
Andy Hung116bc262023-06-20 18:56:17 -07001713 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001714 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1715}
1716
Eric Laurent81784c32012-11-19 14:55:58 -08001717// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1718// PlaybackThread::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07001719status_t ThreadBase::addEffect_l(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001720{
1721 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001722 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001723 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001724 bool chainCreated = false;
1725
Eric Laurent5baf2af2013-09-12 17:37:00 -07001726 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001727 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001728 this, effect->desc().name, effect->desc().flags);
1729
Eric Laurent81784c32012-11-19 14:55:58 -08001730 if (chain == 0) {
1731 // create a new chain for this session
1732 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001733 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001734 addEffectChain_l(chain);
1735 chain->setStrategy(getStrategyForSession_l(sessionId));
1736 chainCreated = true;
1737 }
1738 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1739
1740 if (chain->getEffectFromId_l(effect->id()) != 0) {
1741 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1742 this, effect->desc().name, chain.get());
1743 return BAD_VALUE;
1744 }
1745
Eric Laurent5baf2af2013-09-12 17:37:00 -07001746 effect->setOffloaded(mType == OFFLOAD, mId);
1747
Eric Laurent81784c32012-11-19 14:55:58 -08001748 status_t status = chain->addEffect_l(effect);
1749 if (status != NO_ERROR) {
1750 if (chainCreated) {
1751 removeEffectChain_l(chain);
1752 }
1753 return status;
1754 }
1755
jiabin8f278ee2019-11-11 12:16:27 -08001756 effect->setDevices(outDeviceTypeAddrs());
1757 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001758 effect->setMode(mAudioFlinger->getMode());
1759 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001760
Eric Laurent81784c32012-11-19 14:55:58 -08001761 return NO_ERROR;
1762}
1763
Andy Hung4b17e882023-07-07 13:47:37 -07001764void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001765
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001766 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001767 effect_descriptor_t desc = effect->desc();
1768 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1769 detachAuxEffect_l(effect->id());
1770 }
1771
Andy Hung116bc262023-06-20 18:56:17 -07001772 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001773 if (chain != 0) {
1774 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001775 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001776 removeEffectChain_l(chain);
1777 }
1778 } else {
1779 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1780 }
1781}
1782
Andy Hung4b17e882023-07-07 13:47:37 -07001783void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001784 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001785NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
1787 effectChains = mEffectChains;
1788 for (size_t i = 0; i < mEffectChains.size(); i++) {
1789 mEffectChains[i]->lock();
1790 }
1791}
1792
Andy Hung4b17e882023-07-07 13:47:37 -07001793void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001794 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001795NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001796{
1797 for (size_t i = 0; i < effectChains.size(); i++) {
1798 effectChains[i]->unlock();
1799 }
1800}
1801
Andy Hung4b17e882023-07-07 13:47:37 -07001802sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001803{
1804 Mutex::Autolock _l(mLock);
1805 return getEffectChain_l(sessionId);
1806}
1807
Andy Hung4b17e882023-07-07 13:47:37 -07001808sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001809 const
Eric Laurent81784c32012-11-19 14:55:58 -08001810{
1811 size_t size = mEffectChains.size();
1812 for (size_t i = 0; i < size; i++) {
1813 if (mEffectChains[i]->sessionId() == sessionId) {
1814 return mEffectChains[i];
1815 }
1816 }
1817 return 0;
1818}
1819
Andy Hung4b17e882023-07-07 13:47:37 -07001820void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001821{
1822 Mutex::Autolock _l(mLock);
1823 size_t size = mEffectChains.size();
1824 for (size_t i = 0; i < size; i++) {
1825 mEffectChains[i]->setMode_l(mode);
1826 }
1827}
1828
Andy Hung4b17e882023-07-07 13:47:37 -07001829void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001830{
1831 config->type = AUDIO_PORT_TYPE_MIX;
1832 config->ext.mix.handle = mId;
1833 config->sample_rate = mSampleRate;
1834 config->format = mFormat;
1835 config->channel_mask = mChannelMask;
1836 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1837 AUDIO_PORT_CONFIG_FORMAT;
1838}
1839
Andy Hung4b17e882023-07-07 13:47:37 -07001840void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001841{
1842 Mutex::Autolock _l(mLock);
1843 if (mSystemReady) {
1844 return;
1845 }
1846 mSystemReady = true;
1847
1848 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1849 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1850 }
1851 mPendingConfigEvents.clear();
1852}
1853
Andy Hungdae27702016-10-31 14:01:16 -07001854template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001855ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001856 ssize_t index = mActiveTracks.indexOf(track);
1857 if (index >= 0) {
1858 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1859 return index;
1860 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001861 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001862 mActiveTracksGeneration++;
1863 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001864 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001865 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001866 return mActiveTracks.add(track);
1867}
1868
1869template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001870ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001871 ssize_t index = mActiveTracks.remove(track);
1872 if (index < 0) {
1873 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1874 return index;
1875 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001876 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001877 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001878 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001879 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001880 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001881#ifdef TEE_SINK
1882 track->dumpTee(-1 /* fd */, "_REMOVE");
1883#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001884 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001885 return index;
1886}
1887
1888template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001889void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001890 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001891 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001892 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001893 }
1894 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001895 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001896 mActiveTracks.clear();
1897 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001898}
1899
1900template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001901void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001902 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001903 // Updates ActiveTracks client uids to the thread wakelock.
1904 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1905 thread->updateWakeLockUids_l(getWakeLockUids());
1906 mLastActiveTracksGeneration = mActiveTracksGeneration;
1907 }
Andy Hungdae27702016-10-31 14:01:16 -07001908}
Eric Laurent83b88082014-06-20 18:31:16 -07001909
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001910template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001911bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001912 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001913 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001914
1915 for (const sp<T> &track : mActiveTracks) {
1916 // Do not short-circuit as all hasChanged states must be reset
1917 // as all the metadata are going to be sent
1918 hasChanged |= track->readAndClearHasChanged();
1919 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001920 return hasChanged;
1921}
1922
1923template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001924void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001925 const char *funcName, const sp<T> &track) const {
1926 if (mLocalLog != nullptr) {
1927 String8 result;
1928 track->appendDump(result, false /* active */);
1929 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1930 }
1931}
1932
Andy Hung4b17e882023-07-07 13:47:37 -07001933void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08001934{
1935 // Thread could be blocked waiting for async
1936 // so signal it to handle state changes immediately
1937 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1938 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1939 mSignalPending = true;
1940 mWaitWorkCV.broadcast();
1941}
1942
Andy Hungd0979812019-02-21 15:51:44 -08001943// Call only from threadLoop() or when it is idle.
1944// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07001945void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08001946{
1947 // Do not log if we have no stats.
1948 // We choose the timestamp verifier because it is the most likely item to be present.
1949 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1950 if (nstats == 0) {
1951 return;
1952 }
1953
1954 // Don't log more frequently than once per 12 hours.
1955 // We use BOOTTIME to include suspend time.
1956 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1957 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1958 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1959 return;
1960 }
1961
1962 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1963 mLastRecordedTimeNs = timeNs;
1964
Ray Essickf27e9872019-12-07 06:28:46 -08001965 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001966
1967#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1968
1969 // thread configuration
1970 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1971 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1972 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1973 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1974 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1975 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1976 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001977 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1978 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001979
1980 // thread statistics
1981 if (mIoJitterMs.getN() > 0) {
1982 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1983 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1984 }
1985 if (mProcessTimeMs.getN() > 0) {
1986 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1987 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1988 }
1989 const auto tsjitter = mTimestampVerifier.getJitterMs();
1990 if (tsjitter.getN() > 0) {
1991 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1992 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1993 }
1994 if (mLatencyMs.getN() > 0) {
1995 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1996 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1997 }
Robert Wu06db0a32021-08-10 19:05:34 +00001998 if (mMonopipePipeDepthStats.getN() > 0) {
1999 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2000 mMonopipePipeDepthStats.getMean());
2001 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2002 mMonopipePipeDepthStats.getStdDev());
2003 }
Andy Hungd0979812019-02-21 15:51:44 -08002004
2005 item->selfrecord();
2006}
2007
Andy Hung4b17e882023-07-07 13:47:37 -07002008product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002009{
2010 if (!mAudioFlinger->isAudioPolicyReady()) {
2011 return PRODUCT_STRATEGY_NONE;
2012 }
2013 return AudioSystem::getStrategyForStream(stream);
2014}
2015
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002016// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002017void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002018 const sp<audio_utils::MelProcessor>& /*processor*/)
2019{
2020 // Do nothing
2021 ALOGW("%s: ThreadBase does not support CSD", __func__);
2022}
2023
2024// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002025void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002026{
2027 // Do nothing
2028 ALOGW("%s: ThreadBase does not support CSD", __func__);
2029}
2030
Eric Laurent81784c32012-11-19 14:55:58 -08002031// ----------------------------------------------------------------------------
2032// Playback
2033// ----------------------------------------------------------------------------
2034
Andy Hung4b17e882023-07-07 13:47:37 -07002035PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent81784c32012-11-19 14:55:58 -08002036 AudioStreamOut* output,
2037 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002038 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002039 bool systemReady,
2040 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002041 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002042 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002043 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002044 mMixerBuffer(NULL),
2045 mMixerBufferSize(0),
2046 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2047 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002048 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002049 mEffectBuffer(NULL),
2050 mEffectBufferSize(0),
2051 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2052 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002053 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002054 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002055 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002056 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002057 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002058 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002059 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002060 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002061 mMixerStatus(MIXER_IDLE),
2062 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002063 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002064 mBytesRemaining(0),
2065 mCurrentWriteLength(0),
2066 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002067 mWriteAckSequence(0),
2068 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002069 mScreenState(AudioFlinger::mScreenState),
2070 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002071 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002072 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002073 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002074 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002075 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002076{
Glenn Kastend7dca052015-03-05 16:05:54 -08002077 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2078 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002079
2080 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2081 // it would be safer to explicitly pass initial masterVolume/masterMute as
2082 // parameter.
2083 //
2084 // If the HAL we are using has support for master volume or master mute,
2085 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2086 // and the mute set to false).
2087 mMasterVolume = audioFlinger->masterVolume_l();
2088 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002089 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002090 if (mOutput->audioHwDev->canSetMasterVolume()) {
2091 mMasterVolume = 1.0;
2092 }
2093
2094 if (mOutput->audioHwDev->canSetMasterMute()) {
2095 mMasterMute = false;
2096 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002097 mIsMsdDevice = strcmp(
2098 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002099 }
2100
Eric Laurentf1f22e72021-07-13 14:04:14 +02002101 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2102 mMixerChannelMask = mixerConfig->channel_mask;
2103 }
2104
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002105 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002106
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002107 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002108 && mMixerChannelMask != mChannelMask) {
2109 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2110 mChannelMask, mMixerChannelMask);
2111 }
2112
Andy Hungc8fddf32018-08-08 18:32:37 -07002113 // TODO: We may also match on address as well as device type for
2114 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002115 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002116 // TODO: This property should be ensure that only contains one single device type.
2117 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2118 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002119 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2120 : AUDIO_DEVICE_NONE));
2121 }
2122
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002123 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2124 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002125 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002126 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2127 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002128 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002129 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2130 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002131 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2132 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002133}
2134
Andy Hung4b17e882023-07-07 13:47:37 -07002135PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002136{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002137 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002138 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002139 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002140 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002141 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002142}
2143
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002144// Thread virtuals
2145
Andy Hung4b17e882023-07-07 13:47:37 -07002146void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002147{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002148 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002149 ALOGE("The stream is not open yet"); // This should not happen.
2150 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002151 // Callbacks take strong or weak pointers as a parameter.
2152 // Since PlaybackThread passes itself as a callback handler, it can only
2153 // be done outside of the constructor. Creating weak and especially strong
2154 // pointers to a refcounted object in its own constructor is strongly
2155 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2156 // Even if a function takes a weak pointer, it is possible that it will
2157 // need to convert it to a strong pointer down the line.
2158 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2159 mOutput->stream->setCallback(this) == OK) {
2160 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002161 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002162 }
2163
jiabinf6eb4c32020-02-25 14:06:25 -08002164 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002165 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002166 }
2167 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002168 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002169 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002170}
2171
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002172// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002173void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002174{
2175 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002176 status_t result = mOutput->stream->exit();
2177 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002178}
2179
Andy Hung4b17e882023-07-07 13:47:37 -07002180void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002181{
Eric Laurent81784c32012-11-19 14:55:58 -08002182 String8 result;
2183
Marco Nelissenb2208842014-02-07 14:00:50 -08002184 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002185 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2186 const stream_type_t *st = &mStreamTypes[i];
2187 if (i > 0) {
2188 result.appendFormat(", ");
2189 }
2190 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2191 if (st->mute) {
2192 result.append("M");
2193 }
2194 }
2195 result.append("\n");
2196 write(fd, result.string(), result.length());
2197 result.clear();
2198
Eric Laurent81784c32012-11-19 14:55:58 -08002199 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2200 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002201 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002202 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002203
2204 size_t numtracks = mTracks.size();
2205 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002206 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002207 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002208 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002209 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002210 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002211 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002212 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002213 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002214 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002215 if (track != 0) {
2216 bool active = mActiveTracks.indexOf(track) >= 0;
2217 if (active) {
2218 numactiveseen++;
2219 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002220 result.append(prefix);
2221 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002222 }
2223 }
2224 } else {
2225 result.append("\n");
2226 }
2227 if (numactiveseen != numactive) {
2228 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002229 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002230 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002231 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002232 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002233 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002234 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002235 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002236 result.append(prefix);
2237 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002238 }
2239 }
2240 }
2241
2242 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Andy Hung4b17e882023-07-07 13:47:37 -07002245void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002246{
Andy Hung04cb8f72020-03-20 13:44:33 -07002247 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002248 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002249 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2250 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002251 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2252 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2253 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2254 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002255 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002256 dprintf(fd, " Total writes: %d\n", mNumWrites);
2257 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2258 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2259 dprintf(fd, " Suspend count: %d\n", mSuspended);
2260 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2261 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2262 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2263 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002264 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002265 AudioStreamOut *output = mOutput;
2266 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002267 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002268 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002269 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2270 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2271 if (mPipeSink.get() != nullptr) {
2272 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2273 }
2274 if (output != nullptr) {
2275 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002276 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002277 }
Eric Laurent81784c32012-11-19 14:55:58 -08002278}
2279
Eric Laurent81784c32012-11-19 14:55:58 -08002280// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002281sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002282 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002283 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002284 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002285 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002286 audio_format_t format,
2287 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002288 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002289 size_t *pNotificationFrameCount,
2290 uint32_t notificationsPerBuffer,
2291 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002292 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002293 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002294 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002295 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002296 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002297 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002298 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002299 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002300 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002301 bool isSpatialized,
2302 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002303{
Glenn Kasten74935e42013-12-19 08:56:45 -08002304 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002305 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002306 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002307 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002308 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002309 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002310 uint32_t sampleRate;
2311
2312 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2313 lStatus = BAD_VALUE;
2314 goto Exit;
2315 }
Eric Laurent21da6472017-11-09 16:29:26 -08002316
2317 if (*pSampleRate == 0) {
2318 *pSampleRate = mSampleRate;
2319 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002320 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002321
2322 // special case for FAST flag considered OK if fast mixer is present
2323 if (hasFastMixer()) {
2324 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2325 }
2326
2327 // Check if requested flags are compatible with output stream flags
2328 if ((*flags & outputFlags) != *flags) {
2329 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2330 *flags, outputFlags);
2331 *flags = (audio_output_flags_t)(*flags & outputFlags);
2332 }
Eric Laurent81784c32012-11-19 14:55:58 -08002333
jiabinc658e452022-10-21 20:52:21 +00002334 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002335 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002336 if (chain.get() != nullptr) {
2337 // Bit-perfect is required according to the configuration and preferred mixer
2338 // attributes, but it is not in the output flag from the client's request. Explicitly
2339 // adding bit-perfect flag to check the compatibility
2340 audio_output_flags_t flagsToCheck =
2341 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2342 chain->checkOutputFlagCompatibility(&flagsToCheck);
2343 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2344 ALOGE("%s cannot create track as there is data-processing effect attached to "
2345 "given session id(%d)", __func__, sessionId);
2346 lStatus = BAD_VALUE;
2347 goto Exit;
2348 }
2349 *flags = flagsToCheck;
2350 }
2351 }
2352
Eric Laurent81784c32012-11-19 14:55:58 -08002353 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002354 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002355 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002356 // PCM data
2357 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002358 // TODO: extract as a data library function that checks that a computationally
2359 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002360 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002361 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2362 (channelMask == AUDIO_CHANNEL_OUT_MONO
2363 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002364 // hardware sample rate
2365 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002366 // normal mixer has an associated fast mixer
2367 hasFastMixer() &&
2368 // there are sufficient fast track slots available
2369 (mFastTrackAvailMask != 0)
2370 // FIXME test that MixerThread for this fast track has a capable output HAL
2371 // FIXME add a permission test also?
2372 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002373 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2374 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002375 // read the fast track multiplier property the first time it is needed
2376 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2377 if (ok != 0) {
2378 ALOGE("%s pthread_once failed: %d", __func__, ok);
2379 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002380 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002381 }
Eric Laurent4c415062016-06-17 16:14:16 -07002382
2383 // check compatibility with audio effects.
2384 { // scope for mLock
2385 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002386 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002387 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002388 AUDIO_SESSION_OUTPUT_STAGE,
2389 AUDIO_SESSION_OUTPUT_MIX,
2390 sessionId,
2391 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002392 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002393 if (chain.get() != nullptr) {
2394 audio_output_flags_t old = *flags;
2395 chain->checkOutputFlagCompatibility(flags);
2396 if (old != *flags) {
2397 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2398 (int)session, (int)old, (int)*flags);
2399 }
Eric Laurent4c415062016-06-17 16:14:16 -07002400 }
2401 }
2402 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002403 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002404 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2405 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002406 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002407 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002408 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002409 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002410 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002411 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002412 audio_is_linear_pcm(format), channelMask, sampleRate,
2413 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002414 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002415 }
2416 }
Eric Laurent21da6472017-11-09 16:29:26 -08002417
2418 if (!audio_has_proportional_frames(format)) {
2419 if (sharedBuffer != 0) {
2420 // Same comment as below about ignoring frameCount parameter for set()
2421 frameCount = sharedBuffer->size();
2422 } else if (frameCount == 0) {
2423 frameCount = mNormalFrameCount;
2424 }
2425 if (notificationFrameCount != frameCount) {
2426 notificationFrameCount = frameCount;
2427 }
2428 } else if (sharedBuffer != 0) {
2429 // FIXME: Ensure client side memory buffers need
2430 // not have additional alignment beyond sample
2431 // (e.g. 16 bit stereo accessed as 32 bit frame).
2432 size_t alignment = audio_bytes_per_sample(format);
2433 if (alignment & 1) {
2434 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2435 alignment = 1;
2436 }
2437 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2438 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2439 if (channelCount > 1) {
2440 // More than 2 channels does not require stronger alignment than stereo
2441 alignment <<= 1;
2442 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002443 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002444 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002445 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002446 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002447 goto Exit;
2448 }
Eric Laurent21da6472017-11-09 16:29:26 -08002449
2450 // When initializing a shared buffer AudioTrack via constructors,
2451 // there's no frameCount parameter.
2452 // But when initializing a shared buffer AudioTrack via set(),
2453 // there _is_ a frameCount parameter. We silently ignore it.
2454 frameCount = sharedBuffer->size() / frameSize;
2455 } else {
2456 size_t minFrameCount = 0;
2457 // For fast tracks we try to respect the application's request for notifications per buffer.
2458 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2459 if (notificationsPerBuffer > 0) {
2460 // Avoid possible arithmetic overflow during multiplication.
2461 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2462 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2463 notificationsPerBuffer, mFrameCount);
2464 } else {
2465 minFrameCount = mFrameCount * notificationsPerBuffer;
2466 }
2467 }
2468 } else {
2469 // For normal PCM streaming tracks, update minimum frame count.
2470 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2471 // cover audio hardware latency.
2472 // This is probably too conservative, but legacy application code may depend on it.
2473 // If you change this calculation, also review the start threshold which is related.
2474 uint32_t latencyMs = latency_l();
2475 if (latencyMs == 0) {
2476 ALOGE("Error when retrieving output stream latency");
2477 lStatus = UNKNOWN_ERROR;
2478 goto Exit;
2479 }
2480
2481 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2482 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2483
Eric Laurent81784c32012-11-19 14:55:58 -08002484 }
Eric Laurent21da6472017-11-09 16:29:26 -08002485 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002486 frameCount = minFrameCount;
2487 }
Eric Laurent81784c32012-11-19 14:55:58 -08002488 }
Eric Laurent21da6472017-11-09 16:29:26 -08002489
2490 // Make sure that application is notified with sufficient margin before underrun.
2491 // The client can divide the AudioTrack buffer into sub-buffers,
2492 // and expresses its desire to server as the notification frame count.
2493 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2494 size_t maxNotificationFrames;
2495 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2496 // notify every HAL buffer, regardless of the size of the track buffer
2497 maxNotificationFrames = mFrameCount;
2498 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002499 // Triple buffer the notification period for a triple buffered mixer period;
2500 // otherwise, double buffering for the notification period is fine.
2501 //
2502 // TODO: This should be moved to AudioTrack to modify the notification period
2503 // on AudioTrack::setBufferSizeInFrames() changes.
2504 const int nBuffering =
2505 (uint64_t{frameCount} * mSampleRate)
2506 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2507
Eric Laurent21da6472017-11-09 16:29:26 -08002508 maxNotificationFrames = frameCount / nBuffering;
2509 // If client requested a fast track but this was denied, then use the smaller maximum.
2510 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2511 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2512 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2513 maxNotificationFrames = maxNotificationFramesFastDenied;
2514 }
2515 }
2516 }
2517 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2518 if (notificationFrameCount == 0) {
2519 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2520 maxNotificationFrames, frameCount);
2521 } else {
2522 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2523 notificationFrameCount, maxNotificationFrames, frameCount);
2524 }
2525 notificationFrameCount = maxNotificationFrames;
2526 }
2527 }
2528
Glenn Kasten74935e42013-12-19 08:56:45 -08002529 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002530 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002531
Glenn Kastenc3df8382014-03-13 15:05:25 -07002532 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002533 case BIT_PERFECT:
2534 if (isBitPerfect) {
2535 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2536 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2537 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2538 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2539 mChannelMask);
2540 lStatus = BAD_VALUE;
2541 goto Exit;
2542 }
2543 }
2544 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002545
2546 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002547 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002548 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002549 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2550 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002551 sampleRate, format, channelMask, mOutput, mFormat);
2552 lStatus = BAD_VALUE;
2553 goto Exit;
2554 }
2555 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002556 break;
2557
2558 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002559 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002560 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2561 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002562 sampleRate, format, channelMask, mOutput, mFormat);
2563 lStatus = BAD_VALUE;
2564 goto Exit;
2565 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002566 break;
2567
2568 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002569 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002570 ALOGE("createTrack_l() Bad parameter: format %#x \""
2571 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572 format, mOutput, mFormat);
2573 lStatus = BAD_VALUE;
2574 goto Exit;
2575 }
Andy Hungcd044842014-08-07 11:04:34 -07002576 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002577 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2578 lStatus = BAD_VALUE;
2579 goto Exit;
2580 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002581 break;
2582
Eric Laurent81784c32012-11-19 14:55:58 -08002583 }
2584
2585 lStatus = initCheck();
2586 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002587 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002588 goto Exit;
2589 }
2590
2591 { // scope for mLock
2592 Mutex::Autolock _l(mLock);
2593
2594 // all tracks in same audio session must share the same routing strategy otherwise
2595 // conflicts will happen when tracks are moved from one output to another by audio policy
2596 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002597 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002598 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002599 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002600 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002601 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002602 if (sessionId == t->sessionId() && strategy != actual) {
2603 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2604 strategy, actual);
2605 lStatus = BAD_VALUE;
2606 goto Exit;
2607 }
2608 }
2609 }
2610
yucliuc9c49cd2020-07-13 16:25:21 -07002611 // Set DIRECT flag if current thread is DirectOutputThread. This can
2612 // happen when the playback is rerouted to direct output thread by
2613 // dynamic audio policy.
2614 // Do NOT report the flag changes back to client, since the client
2615 // doesn't explicitly request a direct flag.
2616 audio_output_flags_t trackFlags = *flags;
2617 if (mType == DIRECT) {
2618 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2619 }
2620
Andy Hung11e74242023-06-26 19:20:57 -07002621 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002622 channelMask, frameCount,
2623 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002624 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002625 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002626 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002627
Glenn Kasten03003332013-08-06 15:40:54 -07002628 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2629 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002630 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002631 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002632 goto Exit;
2633 }
2634 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002635 {
2636 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2637 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002638 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002639 }
2640 }
Eric Laurent81784c32012-11-19 14:55:58 -08002641
Andy Hung116bc262023-06-20 18:56:17 -07002642 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002643 if (chain != 0) {
2644 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2645 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002646 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002647 chain->incTrackCnt();
2648 }
2649
Eric Laurent05067782016-06-01 18:27:28 -07002650 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002651 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2652 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2653 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002654 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002655 }
2656 }
2657
2658 lStatus = NO_ERROR;
2659
2660Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002661 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002662 return track;
2663}
2664
Andy Hung1bc088a2018-02-09 15:57:31 -08002665template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002666ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002667{
Andy Hungc0691382018-09-12 18:01:57 -07002668 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002669 const ssize_t index = mTracks.remove(track);
2670 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002671 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002672 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002673 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002674 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002675 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002676 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002677 }
2678 return index;
2679}
2680
Andy Hung4b17e882023-07-07 13:47:37 -07002681uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002682{
2683 return latency;
2684}
2685
Andy Hung4b17e882023-07-07 13:47:37 -07002686uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002687{
2688 Mutex::Autolock _l(mLock);
2689 return latency_l();
2690}
Andy Hung4b17e882023-07-07 13:47:37 -07002691uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002692{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002693 uint32_t latency;
2694 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2695 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002696 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002697 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002698}
2699
Andy Hung4b17e882023-07-07 13:47:37 -07002700void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002701{
2702 Mutex::Autolock _l(mLock);
2703 // Don't apply master volume in SW if our HAL can do it for us.
2704 if (mOutput && mOutput->audioHwDev &&
2705 mOutput->audioHwDev->canSetMasterVolume()) {
2706 mMasterVolume = 1.0;
2707 } else {
2708 mMasterVolume = value;
2709 }
2710}
2711
Andy Hung4b17e882023-07-07 13:47:37 -07002712void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002713{
2714 mMasterBalance.store(balance);
2715}
2716
Andy Hung4b17e882023-07-07 13:47:37 -07002717void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002718{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002719 if (isDuplicating()) {
2720 return;
2721 }
Eric Laurent81784c32012-11-19 14:55:58 -08002722 Mutex::Autolock _l(mLock);
2723 // Don't apply master mute in SW if our HAL can do it for us.
2724 if (mOutput && mOutput->audioHwDev &&
2725 mOutput->audioHwDev->canSetMasterMute()) {
2726 mMasterMute = false;
2727 } else {
2728 mMasterMute = muted;
2729 }
2730}
2731
Andy Hung4b17e882023-07-07 13:47:37 -07002732void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002733{
2734 Mutex::Autolock _l(mLock);
2735 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002736 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002737}
2738
Andy Hung4b17e882023-07-07 13:47:37 -07002739void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002740{
2741 Mutex::Autolock _l(mLock);
2742 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002743 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002744}
2745
Andy Hung4b17e882023-07-07 13:47:37 -07002746float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002747{
2748 Mutex::Autolock _l(mLock);
2749 return mStreamTypes[stream].volume;
2750}
2751
Andy Hung4b17e882023-07-07 13:47:37 -07002752void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002753{
2754 mOutput->stream->setVolume(left, right);
2755}
2756
Eric Laurent81784c32012-11-19 14:55:58 -08002757// addTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07002758status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung920f6572022-10-06 12:09:49 -07002759NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002760{
2761 status_t status = ALREADY_EXISTS;
2762
Eric Laurent81784c32012-11-19 14:55:58 -08002763 if (mActiveTracks.indexOf(track) < 0) {
2764 // the track is newly added, make sure it fills up all its
2765 // buffers before playing. This is to ensure the client will
2766 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002767 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002768 IAfTrackBase::track_state state = track->state();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002770 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002771 mLock.lock();
2772 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002773 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002774 if (status == NO_ERROR) {
2775 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002776 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002777 mLock.lock();
2778 }
2779 return INVALID_OPERATION;
2780 }
2781 // abort if start is rejected by audio policy manager
2782 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002783 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2784 // current playback thread is reopened, which may happen when clients set preferred
2785 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2786 // immediately.
2787 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788 }
2789#ifdef ADD_BATTERY_DATA
2790 // to track the speaker usage
2791 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2792#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002793 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794 }
2795
Eric Laurent51716182016-02-29 18:00:56 -08002796 // set retry count for buffer fill
2797 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002798 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002799 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002800 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002801 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002802 }
Andy Hung11e74242023-06-26 19:20:57 -07002803 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002804 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002805 track->retryCount() = kMaxTrackStartupRetries;
2806 track->fillingStatus() =
2807 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002808 }
2809
Andy Hung116bc262023-06-20 18:56:17 -07002810 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002811 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2812 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2813 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002814 // Unlock due to VibratorService will lock for this call and will
2815 // call Tracks.mute/unmute which also require thread's lock.
2816 mLock.unlock();
Simon Bowden62823412022-10-17 14:52:26 +00002817 const os::HapticScale intensity = AudioFlinger::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002818 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002819 std::optional<media::AudioVibratorInfo> vibratorInfo;
2820 {
2821 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2822 // used to play this track.
2823 Mutex::Autolock _l(mAudioFlinger->mLock);
2824 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2825 }
jiabin57303cc2018-12-18 15:45:57 -08002826 mLock.lock();
Simon Bowden62823412022-10-17 14:52:26 +00002827 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002828 if (vibratorInfo) {
2829 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2830 }
2831
jiabin57303cc2018-12-18 15:45:57 -08002832 // Haptic playback should be enabled by vibrator service.
2833 if (track->getHapticPlaybackEnabled()) {
2834 // Disable haptic playback of all active track to ensure only
2835 // one track playing haptic if current track should play haptic.
2836 for (const auto &t : mActiveTracks) {
2837 t->setHapticPlaybackEnabled(false);
2838 }
jiabin245cdd92018-12-07 17:55:15 -08002839 }
jiabine70bc7f2020-06-30 22:07:55 -07002840
2841 // Set haptic intensity for effect
2842 if (chain != nullptr) {
2843 chain->setHapticIntensity_l(track->id(), intensity);
2844 }
jiabin245cdd92018-12-07 17:55:15 -08002845 }
2846
Andy Hung11e74242023-06-26 19:20:57 -07002847 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002848 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002849 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002850 if (chain != 0) {
2851 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2852 track->sessionId());
2853 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002854 }
2855
Andy Hungc2b11cb2020-04-22 09:04:01 -07002856 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002857 status = NO_ERROR;
2858 }
2859
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002860 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002861 return status;
2862}
2863
Andy Hung4b17e882023-07-07 13:47:37 -07002864bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002865{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002867 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002869 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002871 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002872 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002873 if (track->isPausePending()) {
2874 track->pauseAck();
2875 }
Andy Hung11e74242023-06-26 19:20:57 -07002876 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002877 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878
2879 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002880}
2881
Andy Hung4b17e882023-07-07 13:47:37 -07002882void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002883{
2884 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002885
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002886 String8 result;
2887 track->appendDump(result, false /* active */);
2888 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002889
Eric Laurent81784c32012-11-19 14:55:58 -08002890 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002891 {
2892 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2893 mAudioTrackCallbacks.erase(track);
2894 }
Eric Laurent81784c32012-11-19 14:55:58 -08002895 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002896 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002897 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002898 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2899 mFastTrackAvailMask |= 1 << index;
2900 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07002901 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002902 }
Andy Hung116bc262023-06-20 18:56:17 -07002903 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002904 if (chain != 0) {
2905 chain->decTrackCnt();
2906 }
2907}
2908
Andy Hung4b17e882023-07-07 13:47:37 -07002909String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002910{
Eric Laurent81784c32012-11-19 14:55:58 -08002911 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002912 String8 out_s8;
2913 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2914 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002915 }
Andy Hung920f6572022-10-06 12:09:49 -07002916 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002917}
2918
Andy Hung4b17e882023-07-07 13:47:37 -07002919status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002920 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002921 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002922 return NO_INIT;
2923 }
2924 return mOutput->stream->selectPresentation(presentationId, programId);
2925}
2926
Andy Hung4b17e882023-07-07 13:47:37 -07002927void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002928 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002929 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002930 sp<AudioIoDescriptor> desc;
2931 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002932 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002933 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002934 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002935 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002936 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2937 mSampleRate, mFormat, mChannelMask,
2938 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2939 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002940 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002941 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002942 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002943 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002944 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002945 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002946 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002947 break;
2948 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002949 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002950}
2951
Andy Hung4b17e882023-07-07 13:47:37 -07002952void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002953{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002954 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955}
2956
Andy Hung4b17e882023-07-07 13:47:37 -07002957void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002959 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960}
2961
Andy Hung4b17e882023-07-07 13:47:37 -07002962void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002963{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002964 mCallbackThread->setAsyncError();
2965}
2966
Andy Hung4b17e882023-07-07 13:47:37 -07002967void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08002968 const std::basic_string<uint8_t>& metadataBs)
2969{
Andy Hung4b17e882023-07-07 13:47:37 -07002970 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08002971 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07002972 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08002973 if (playbackThread == nullptr) {
2974 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2975 return;
2976 }
2977
jiabinf6eb4c32020-02-25 14:06:25 -08002978 audio_utils::metadata::Data metadata =
2979 audio_utils::metadata::dataFromByteString(metadataBs);
2980 if (metadata.empty()) {
2981 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2982 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2983 (int)metadataBs.size());
2984 return;
2985 }
2986
2987 audio_utils::metadata::ByteString metaDataStr =
2988 audio_utils::metadata::byteStringFromData(metadata);
2989 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2990 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002991 for (const auto& callbackPair : mAudioTrackCallbacks) {
2992 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002993 }
2994 }).detach();
2995}
2996
Andy Hung4b17e882023-07-07 13:47:37 -07002997void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998{
2999 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003000 // reject out of sequence requests
3001 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3002 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003003 mWaitWorkCV.signal();
3004 }
3005}
3006
Andy Hung4b17e882023-07-07 13:47:37 -07003007void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003008{
3009 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003010 // reject out of sequence requests
3011 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003012 // Register discontinuity when HW drain is completed because that can cause
3013 // the timestamp frame position to reset to 0 for direct and offload threads.
3014 // (Out of sequence requests are ignored, since the discontinuity would be handled
3015 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003016 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003017 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003018 mWaitWorkCV.signal();
3019 }
3020}
3021
Andy Hung4b17e882023-07-07 13:47:37 -07003022void PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003023{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003024 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003025 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3026 mSampleRate = audioConfig.sample_rate;
3027 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003028 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003029 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003030 }
Andy Hung4b17e882023-07-07 13:47:37 -07003031 if (hasMixer() && !AudioFlinger::isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003032 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3033 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003034 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003035
3036 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3037 mMixerChannelMask = mChannelMask;
3038 }
3039
Andy Hunge5412692014-05-16 11:25:07 -07003040 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003041 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003042
Eric Laurentf1f22e72021-07-13 14:04:14 +02003043 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3044
Phil Burkca5e6142015-07-14 09:42:29 -07003045 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003046 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003047 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003048 // Get format from the shim, which will be different than the HAL format
3049 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003050 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003051 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003052 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003053 }
Andy Hung4b17e882023-07-07 13:47:37 -07003054 if (hasMixer() && !AudioFlinger::isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003055 LOG_FATAL("HAL format %#x not supported for mixed output",
3056 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003057 }
Phil Burk062e67a2015-02-11 13:40:50 -08003058 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003059 result = mOutput->stream->getBufferSize(&mBufferSize);
3060 LOG_ALWAYS_FATAL_IF(result != OK,
3061 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003062 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003063 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003064 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003065 mFrameCount);
3066 }
3067
Eric Laurentd1f69b02014-12-15 14:33:13 -08003068 mHwSupportsPause = false;
3069 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003070 bool supportsPause = false, supportsResume = false;
3071 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3072 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003073 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003074 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003075 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003076 } else if (supportsResume) {
3077 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003078 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003079 }
3080 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003081 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3082 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3083 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003084
Andy Hungfbfc3952015-01-15 13:33:51 -08003085 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3086 // For best precision, we use float instead of the associated output
3087 // device format (typically PCM 16 bit).
3088
3089 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3090 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3091 mBufferSize = mFrameSize * mFrameCount;
3092
3093 // TODO: We currently use the associated output device channel mask and sample rate.
3094 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3095 // (if a valid mask) to avoid premature downmix.
3096 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3097 // instead of the output device sample rate to avoid loss of high frequency information.
3098 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3099 }
3100
Andy Hung09a50072014-02-27 14:30:47 -08003101 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003102 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003103 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003104 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3105 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003106 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3107 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003108
Eric Laurent81784c32012-11-19 14:55:58 -08003109 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3110 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3111 maxNormalFrameCount = maxNormalFrameCount & ~15;
3112 if (maxNormalFrameCount < minNormalFrameCount) {
3113 maxNormalFrameCount = minNormalFrameCount;
3114 }
3115 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3116 if (multiplier <= 1.0) {
3117 multiplier = 1.0;
3118 } else if (multiplier <= 2.0) {
3119 if (2 * mFrameCount <= maxNormalFrameCount) {
3120 multiplier = 2.0;
3121 } else {
3122 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3123 }
3124 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003125 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003126 }
3127 }
3128 mNormalFrameCount = multiplier * mFrameCount;
3129 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003130 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003131 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3132 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003133 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003134 mNormalFrameCount);
3135
Andy Hung08fb1742015-05-31 23:22:10 -07003136 // Check if we want to throttle the processing to no more than 2x normal rate
3137 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003138 mThreadThrottleTimeMs = 0;
3139 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003140 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3141
Andy Hung010a1a12014-03-13 13:57:33 -07003142 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3143 // Originally this was int16_t[] array, need to remove legacy implications.
3144 free(mSinkBuffer);
3145 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003146
Andy Hung5b10a202014-03-13 13:59:29 -07003147 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3148 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3149 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003150 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003151
Andy Hung69aed5f2014-02-25 17:24:40 -08003152 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3153 // drives the output.
3154 free(mMixerBuffer);
3155 mMixerBuffer = NULL;
3156 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003157 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003158 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003159 * audio_bytes_per_sample(mMixerBufferFormat);
3160 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3161 }
Andy Hung98ef9782014-03-04 14:46:50 -08003162 free(mEffectBuffer);
3163 mEffectBuffer = NULL;
3164 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003165 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003166 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003167 * audio_bytes_per_sample(mEffectBufferFormat);
3168 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3169 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003170
Eric Laurentb62d0362021-10-26 17:40:18 +02003171 if (mType == SPATIALIZER) {
3172 free(mPostSpatializerBuffer);
3173 mPostSpatializerBuffer = nullptr;
3174 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3175 * audio_bytes_per_sample(mEffectBufferFormat);
3176 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3177 }
3178
Mikhail Naganov55773032020-10-01 15:08:13 -07003179 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3180 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003181 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3182 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003183 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003184
Eric Laurent81784c32012-11-19 14:55:58 -08003185 // force reconfiguration of effect chains and engines to take new buffer size and audio
3186 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003187 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003188 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3189 // matter.
3190 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003191 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003192 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003193 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3194 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003195 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003196
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003197 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003198 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003199 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3200 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3201 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3202 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3203 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3204 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3205 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3206 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3207 (int32_t)mHapticChannelMask)
3208 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3209 (int32_t)mHapticChannelCount)
3210 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3211 formatToString(mHALFormat).c_str())
3212 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3213 (int32_t)mFrameCount) // sic - added HAL
3214 ;
3215 uint32_t latencyMs;
3216 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3217 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3218 }
3219 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003220}
3221
Andy Hung4b17e882023-07-07 13:47:37 -07003222ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003223{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003224 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003225 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003226 }
3227 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003228 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07003229 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003230 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003231 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003232 }
Kevin Rocard12381092018-04-11 09:19:59 -07003233 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003234 MetadataUpdate change;
3235 change.playbackMetadataUpdate = metadata.tracks;
3236 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003237}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003238
Andy Hung4b17e882023-07-07 13:47:37 -07003239void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003240 const StreamOutHalInterface::SourceMetadata& metadata)
3241{
3242 mOutput->stream->updateSourceMetadata(metadata);
3243};
3244
Andy Hung4b17e882023-07-07 13:47:37 -07003245status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003246 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003247{
3248 if (halFrames == NULL || dspFrames == NULL) {
3249 return BAD_VALUE;
3250 }
3251 Mutex::Autolock _l(mLock);
3252 if (initCheck() != NO_ERROR) {
3253 return INVALID_OPERATION;
3254 }
Andy Hung818e7a32016-02-16 18:08:07 -08003255 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003256 *halFrames = framesWritten;
3257
3258 if (isSuspended()) {
3259 // return an estimation of rendered frames when the output is suspended
3260 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003261 *dspFrames = (uint32_t)
3262 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003263 return NO_ERROR;
3264 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003265 status_t status;
3266 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003267 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003268 *dspFrames = (size_t)frames;
3269 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003270 }
3271}
3272
Andy Hung4b17e882023-07-07 13:47:37 -07003273product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003274{
3275 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3276 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3277 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003278 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003279 }
3280 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003281 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003282 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003283 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003284 }
3285 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003286 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003287}
3288
3289
Andy Hung4b17e882023-07-07 13:47:37 -07003290AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003291{
3292 Mutex::Autolock _l(mLock);
3293 return mOutput;
3294}
3295
Andy Hung4b17e882023-07-07 13:47:37 -07003296AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003297{
3298 Mutex::Autolock _l(mLock);
3299 AudioStreamOut *output = mOutput;
3300 mOutput = NULL;
3301 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3302 // must push a NULL and wait for ack
3303 mOutputSink.clear();
3304 mPipeSink.clear();
3305 mNormalSink.clear();
3306 return output;
3307}
3308
3309// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003310sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003311{
3312 if (mOutput == NULL) {
3313 return NULL;
3314 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003315 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003316}
3317
Andy Hung4b17e882023-07-07 13:47:37 -07003318uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003319{
3320 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3321}
3322
Andy Hung4b17e882023-07-07 13:47:37 -07003323status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003324{
3325 if (!isValidSyncEvent(event)) {
3326 return BAD_VALUE;
3327 }
3328
3329 Mutex::Autolock _l(mLock);
3330
3331 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003332 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003333 if (event->triggerSession() == track->sessionId()) {
3334 (void) track->setSyncEvent(event);
3335 return NO_ERROR;
3336 }
3337 }
3338
3339 return NAME_NOT_FOUND;
3340}
3341
Andy Hung4b17e882023-07-07 13:47:37 -07003342bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003343{
3344 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3345}
3346
Andy Hung4b17e882023-07-07 13:47:37 -07003347void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003348 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003349{
Andy Hungfe726a62018-09-27 15:17:25 -07003350 // Miscellaneous track cleanup when removed from the active list,
3351 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003352#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003353 for (const auto& track : tracksToRemove) {
3354 if (track->isExternalTrack()) {
3355 // to track the speaker usage
3356 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003357 }
3358 }
Andy Hungfe726a62018-09-27 15:17:25 -07003359#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003360}
3361
Andy Hung4b17e882023-07-07 13:47:37 -07003362void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003363{
3364 if (!mMasterMute) {
3365 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003366 if (mOutDeviceTypeAddrs.empty()) {
3367 ALOGD("ro.audio.silent is ignored since no output device is set");
3368 return;
3369 }
jiabinc52b1ff2019-10-31 17:20:42 -07003370 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003371 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3372 return;
3373 }
Eric Laurent81784c32012-11-19 14:55:58 -08003374 if (property_get("ro.audio.silent", value, "0") > 0) {
3375 char *endptr;
3376 unsigned long ul = strtoul(value, &endptr, 0);
3377 if (*endptr == '\0' && ul != 0) {
3378 ALOGD("Silence is golden");
3379 // The setprop command will not allow a property to be changed after
3380 // the first time it is set, so we don't have to worry about un-muting.
3381 setMasterMute_l(true);
3382 }
3383 }
3384 }
3385}
3386
3387// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003388ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003389{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003390 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003391 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003392 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003393 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003394
3395 // If an NBAIO sink is present, use it to write the normal mixer's submix
3396 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003397
Andy Hung010a1a12014-03-13 13:57:33 -07003398 const size_t count = mBytesRemaining / mFrameSize;
3399
Simon Wilson2d590962012-11-29 15:18:50 -08003400 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003401 // update the setpoint when AudioFlinger::mScreenState changes
3402 uint32_t screenState = AudioFlinger::mScreenState;
3403 if (screenState != mScreenState) {
3404 mScreenState = screenState;
3405 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3406 if (pipe != NULL) {
3407 pipe->setAvgFrames((mScreenState & 1) ?
3408 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3409 }
3410 }
Andy Hung010a1a12014-03-13 13:57:33 -07003411 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003412 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003413
Eric Laurent81784c32012-11-19 14:55:58 -08003414 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003415 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003416
Andy Hung8946a282018-04-19 20:04:56 -07003417#ifdef TEE_SINK
3418 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3419#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003420 } else {
3421 bytesWritten = framesWritten;
3422 }
3423 // otherwise use the HAL / AudioStreamOut directly
3424 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003425 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003426
Eric Laurentbfb1b832013-01-07 09:53:42 -08003427 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003428 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3429 mWriteAckSequence += 2;
3430 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003431 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003432 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003433 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003434 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003435 // FIXME We should have an implementation of timestamps for direct output threads.
3436 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003437 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003438 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003439
Eric Laurentbfb1b832013-01-07 09:53:42 -08003440 if (mUseAsyncWrite &&
3441 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3442 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003443 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003444 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003445 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003446 }
Eric Laurent81784c32012-11-19 14:55:58 -08003447 }
3448
Eric Laurent81784c32012-11-19 14:55:58 -08003449 mNumWrites++;
3450 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003451 if (mStandby) {
3452 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003453 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003454 mStandby = false;
3455 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003456 return bytesWritten;
3457}
3458
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003459// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003460void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003461 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003462{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003463 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003464 if (outputSink != nullptr) {
3465 outputSink->startMelComputation(processor);
3466 }
Vlad Popab042ee62022-10-20 18:05:00 +02003467}
3468
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003469// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07003470void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003471{
3472 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003473 if (outputSink != nullptr) {
3474 outputSink->stopMelComputation();
3475 }
Vlad Popab042ee62022-10-20 18:05:00 +02003476}
3477
Andy Hung4b17e882023-07-07 13:47:37 -07003478void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003479{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003480 bool supportsDrain = false;
3481 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003482 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3483 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003484 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3485 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003486 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003487 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003488 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003489 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003490 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003491 }
3492}
3493
Andy Hung4b17e882023-07-07 13:47:37 -07003494void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003495{
Eric Laurent275e8e92014-11-30 15:14:47 -08003496 {
3497 Mutex::Autolock _l(mLock);
3498 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003499 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003500 track->invalidate();
3501 }
Andy Hungdae27702016-10-31 14:01:16 -07003502 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3503 // After we exit there are no more track changes sent to BatteryNotifier
3504 // because that requires an active threadLoop.
3505 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3506 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003507 }
Eric Laurent81784c32012-11-19 14:55:58 -08003508}
3509
3510/*
3511The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003512 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003513 - mActiveSleepTimeUs from activeSleepTimeUs()
3514 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003515 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3516 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003517 - maxPeriod from frame count and sample rate (MIXER only)
3518
3519The parameters that affect these derived values are:
3520 - frame count
3521 - frame size
3522 - sample rate
3523 - device type: A2DP or not
3524 - device latency
3525 - format: PCM or not
3526 - active sleep time
3527 - idle sleep time
3528*/
3529
Andy Hung4b17e882023-07-07 13:47:37 -07003530void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003531{
Andy Hung25c2dac2014-02-27 14:56:00 -08003532 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003533 mActiveSleepTimeUs = activeSleepTimeUs();
3534 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003535
Eric Laurent52568142022-10-28 11:23:28 +02003536 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
Carter Hsu0ca47c22023-06-02 18:01:45 +08003537
Eric Laurent42537be2016-01-08 17:16:42 -08003538 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3539 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003540 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003541 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3542 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3543 }
3544 }
Eric Laurent81784c32012-11-19 14:55:58 -08003545}
3546
Andy Hung4b17e882023-07-07 13:47:37 -07003547bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003548{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003549 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003550 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003551 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003552 size_t size = mTracks.size();
3553 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003554 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003555 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003556 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003557 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003558 }
3559 }
Eric Laurent13084622016-05-17 10:51:49 -07003560 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003561}
3562
Andy Hung4b17e882023-07-07 13:47:37 -07003563void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003564{
3565 Mutex::Autolock _l(mLock);
3566 invalidateTracks_l(streamType);
3567}
3568
Andy Hung4b17e882023-07-07 13:47:37 -07003569void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003570 Mutex::Autolock _l(mLock);
3571 invalidateTracks_l(portIds);
3572}
3573
Andy Hung4b17e882023-07-07 13:47:37 -07003574bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003575 bool trackMatch = false;
3576 const size_t size = mTracks.size();
3577 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003578 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003579 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3580 t->invalidate();
3581 portIds.erase(t->portId());
3582 trackMatch = true;
3583 }
3584 if (portIds.empty()) {
3585 break;
3586 }
3587 }
3588 return trackMatch;
3589}
3590
jiabinf042b9b2021-05-07 23:46:28 +00003591// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003592IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003593 audio_port_handle_t trackPortId) {
3594 for (size_t i = 0; i < mTracks.size(); i++) {
3595 if (mTracks[i]->portId() == trackPortId) {
3596 return mTracks[i].get();
3597 }
3598 }
3599 return nullptr;
3600}
3601
Andy Hung4b17e882023-07-07 13:47:37 -07003602status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003603{
Glenn Kastend848eb42016-03-08 13:42:11 -08003604 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003605 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003606 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003607
Andy Hungd3639922022-04-28 18:00:49 -07003608 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003609 if (!audio_is_global_session(session)) {
3610 // player sessions on a spatializer output will use a dedicated input buffer and
3611 // will either output multi channel to mEffectBuffer if the track is spatilaized
3612 // or stereo to mPostSpatializerBuffer if not spatialized.
3613 uint32_t channelMask;
3614 bool isSessionSpatialized =
3615 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3616 if (isSessionSpatialized) {
3617 channelMask = mMixerChannelMask;
3618 } else {
3619 channelMask = mChannelMask;
3620 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003621 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003622 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003623 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003624 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003625 &halInBuffer);
3626 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003627
3628 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3629 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3630 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3631 &halOutBuffer);
3632 if (result != OK) return result;
3633
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003634 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003635
Mikhail Naganov022b9952017-01-04 16:36:51 -08003636 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3637 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003638 } else {
3639 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3640 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3641 // mPostSpatializerBuffer as output buffer
3642 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3643 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3644 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3645 if (result != OK) return result;
3646 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3647 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3648 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003649
Eric Laurentb62d0362021-10-26 17:40:18 +02003650 if (session == AUDIO_SESSION_DEVICE) {
3651 halInBuffer = halOutBuffer;
3652 }
3653 }
3654 } else {
3655 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3656 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3657 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3658 &halInBuffer);
3659 if (result != OK) return result;
3660 halOutBuffer = halInBuffer;
3661 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3662 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003663 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003664 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003665 // Only one effect chain can be present in direct output thread and it uses
3666 // the sink buffer as input
3667 if (mType != DIRECT) {
3668 size_t numSamples = mNormalFrameCount
3669 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3670 + mHapticChannelCount);
Andy Hung920f6572022-10-06 12:09:49 -07003671 const status_t allocateStatus = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003672 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003673 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003674 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003675
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003676 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003677 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3678 buffer, session);
3679 }
3680 }
3681 }
3682
3683 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003684 // Attach all tracks with same session ID to this chain.
3685 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003686 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003687 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003688 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3689 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003690 track->setMainBuffer(buffer);
3691 chain->incTrackCnt();
3692 }
3693 }
3694
3695 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003696 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003697 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003698 ALOGV("addEffectChain_l() activating track %p on session %d",
3699 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003700 chain->incActiveTrackCnt();
3701 }
3702 }
3703 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003704
Eric Laurentaaa44472014-09-12 17:41:50 -07003705 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003706 chain->setInBuffer(halInBuffer);
3707 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003708 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3709 // chains list in order to be processed last as it contains output device effects.
3710 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3711 // processing effects specific to an output stream before effects applied to all streams
3712 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003713 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3714 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003715 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003716 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003717 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003718 // Effect chain for other sessions are inserted at beginning of effect
3719 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003720 // sessions is not important.
3721 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003722 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3723 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003724 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003725 size_t size = mEffectChains.size();
3726 size_t i = 0;
3727 for (i = 0; i < size; i++) {
3728 if (mEffectChains[i]->sessionId() < session) {
3729 break;
3730 }
3731 }
3732 mEffectChains.insertAt(chain, i);
3733 checkSuspendOnAddEffectChain_l(chain);
3734
3735 return NO_ERROR;
3736}
3737
Andy Hung4b17e882023-07-07 13:47:37 -07003738size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003739{
Glenn Kastend848eb42016-03-08 13:42:11 -08003740 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003741
3742 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3743
3744 for (size_t i = 0; i < mEffectChains.size(); i++) {
3745 if (chain == mEffectChains[i]) {
3746 mEffectChains.removeAt(i);
3747 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003748 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003749 if (session == track->sessionId()) {
3750 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3751 chain.get(), session);
3752 chain->decActiveTrackCnt();
3753 }
3754 }
3755
3756 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003757 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003758 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003759 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003760 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003761 chain->decTrackCnt();
3762 }
3763 }
3764 break;
3765 }
3766 }
3767 return mEffectChains.size();
3768}
3769
Andy Hung4b17e882023-07-07 13:47:37 -07003770status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003771 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003772{
3773 Mutex::Autolock _l(mLock);
3774 return attachAuxEffect_l(track, EffectId);
3775}
3776
Andy Hung4b17e882023-07-07 13:47:37 -07003777status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003778 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003779{
3780 status_t status = NO_ERROR;
3781
3782 if (EffectId == 0) {
3783 track->setAuxBuffer(0, NULL);
3784 } else {
3785 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003786 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003787 if (effect != 0) {
3788 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3789 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3790 } else {
3791 status = INVALID_OPERATION;
3792 }
3793 } else {
3794 status = BAD_VALUE;
3795 }
3796 }
3797 return status;
3798}
3799
Andy Hung4b17e882023-07-07 13:47:37 -07003800void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003801{
3802 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003803 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003804 if (track->auxEffectId() == effectId) {
3805 attachAuxEffect_l(track, 0);
3806 }
3807 }
3808}
3809
Andy Hung4b17e882023-07-07 13:47:37 -07003810bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003811NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003812{
Andy Hung78d8d952023-05-30 18:10:23 -07003813 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003814
Andy Hung11e74242023-06-26 19:20:57 -07003815 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003816
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003817 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003818 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003819
3820 // MIXER
3821 nsecs_t lastWarning = 0;
3822
3823 // DUPLICATING
3824 // FIXME could this be made local to while loop?
3825 writeFrames = 0;
3826
3827 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003828 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003829
Andy Hungd3639922022-04-28 18:00:49 -07003830 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003831 sleepTimeShift = 0;
3832 }
3833
3834 CpuStats cpuStats;
3835 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3836
3837 acquireWakeLock();
3838
Glenn Kasteneef598c2017-04-03 14:41:13 -07003839 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3840 // thread associated with this PlaybackThread.
3841 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3842 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003843 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3844 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003845 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003846 const char *logString = NULL;
3847
rago1bb90822017-05-02 18:31:48 -07003848 // Estimated time for next buffer to be written to hal. This is used only on
3849 // suspended mode (for now) to help schedule the wait time until next iteration.
3850 nsecs_t timeLoopNextNs = 0;
3851
Eric Laurent664539d2013-09-23 18:24:31 -07003852 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003853
Andy Hung2dbffc22018-08-08 18:50:41 -07003854 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003855
Eric Laurentb3f315a2021-07-13 15:09:05 +02003856 sendCheckOutputStageEffectsEvent();
3857
Andy Hung446f4df2019-02-21 12:26:41 -08003858 // loopCount is used for statistics and diagnostics.
3859 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003860 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003861 // Log merge requests are performed during AudioFlinger binder transactions, but
3862 // that does not cover audio playback. It's requested here for that reason.
3863 mAudioFlinger->requestLogMerge();
3864
Eric Laurent81784c32012-11-19 14:55:58 -08003865 cpuStats.sample(myName);
3866
Andy Hung116bc262023-06-20 18:56:17 -07003867 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003868 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003869 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07003870 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003871
Andy Hung2dbffc22018-08-08 18:50:41 -07003872 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3873 //
jiabinc52b1ff2019-10-31 17:20:42 -07003874 // Note: we access outDeviceTypes() outside of mLock.
3875 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003876 // Here, we try for the AF lock, but do not block on it as the latency
3877 // is more informational.
3878 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
Andy Hung4b17e882023-07-07 13:47:37 -07003879 std::vector<AudioFlinger::PatchPanel::SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003880 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003881 status_t status = INVALID_OPERATION;
3882 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3883 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3884 && swPatches.size() > 0) {
3885 status = swPatches[0].getLatencyMs_l(&latencyMs);
3886 downstreamPatchHandle = swPatches[0].getPatchHandle();
3887 }
3888 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003889 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003890 lastDownstreamPatchHandle = downstreamPatchHandle;
3891 }
3892 if (status == OK) {
3893 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003894 // latency of 5 seconds).
3895 const double minLatency = 0., maxLatency = 5000.;
3896 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003897 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003898 } else {
3899 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003900 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003901 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003902 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003903 }
3904 mAudioFlinger->mLock.unlock();
3905 }
3906 } else {
3907 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3908 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003909 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003910 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3911 }
3912 }
3913
Eric Laurentb3f315a2021-07-13 15:09:05 +02003914 if (mCheckOutputStageEffects.exchange(false)) {
3915 checkOutputStageEffects();
3916 }
3917
Vlad Popa7e81cea2023-01-19 16:34:16 +01003918 MetadataUpdate metadataUpdate;
Eric Laurent81784c32012-11-19 14:55:58 -08003919 { // scope for mLock
3920
3921 Mutex::Autolock _l(mLock);
3922
Eric Laurent021cf962014-05-13 10:18:14 -07003923 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003924 if (mCheckOutputStageEffects.load()) {
3925 continue;
3926 }
Eric Laurent10351942014-05-08 18:49:52 -07003927
Glenn Kasteneef598c2017-04-03 14:41:13 -07003928 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003929 if (logString != NULL) {
3930 mNBLogWriter->logTimestamp();
3931 mNBLogWriter->log(logString);
3932 logString = NULL;
3933 }
3934
Dean Wheatley12473e92021-03-18 23:00:55 +11003935 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003936
Eric Laurent81784c32012-11-19 14:55:58 -08003937 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003938 if (mSignalPending) {
3939 // A signal was raised while we were unlocked
3940 mSignalPending = false;
3941 } else if (waitingAsyncCallback_l()) {
3942 if (exitPending()) {
3943 break;
3944 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003945 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003946 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003947 releaseWakeLock_l();
3948 released = true;
3949 }
Andy Hung10cbff12017-02-21 17:30:14 -08003950
3951 const int64_t waitNs = computeWaitTimeNs_l();
3952 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3953 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3954 if (status == TIMED_OUT) {
3955 mSignalPending = true; // if timeout recheck everything
3956 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003957 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003958 if (released) {
3959 acquireWakeLock_l();
3960 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003961 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3962 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003963
3964 continue;
3965 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003966 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003967 isSuspended()) {
3968 // put audio hardware into standby after short delay
3969 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003970
3971 threadLoop_standby();
3972
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003973 // This is where we go into standby
3974 if (!mStandby) {
3975 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003976 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003977 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02003978 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003979 }
Andy Hungd0979812019-02-21 15:51:44 -08003980 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003981 }
3982
Eric Tan39ec8d62018-07-24 09:49:29 -07003983 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003984 // we're about to wait, flush the binder command buffer
3985 IPCThreadState::self()->flushCommands();
3986
3987 clearOutputTracks();
3988
3989 if (exitPending()) {
3990 break;
3991 }
3992
3993 releaseWakeLock_l();
3994 // wait until we have something to do...
3995 ALOGV("%s going to sleep", myName.string());
3996 mWaitWorkCV.wait(mLock);
3997 ALOGV("%s waking up", myName.string());
3998 acquireWakeLock_l();
3999
4000 mMixerStatus = MIXER_IDLE;
4001 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4002 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004003 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004004 checkSilentMode_l();
4005
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004006 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4007 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004008 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004009 sleepTimeShift = 0;
4010 }
4011
4012 continue;
4013 }
4014 }
Eric Laurent81784c32012-11-19 14:55:58 -08004015 // mMixerStatusIgnoringFastTracks is also updated internally
4016 mMixerStatus = prepareTracks_l(&tracksToRemove);
4017
Andy Hungdae27702016-10-31 14:01:16 -07004018 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004019
Vlad Popa7e81cea2023-01-19 16:34:16 +01004020 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004021
Eric Laurent81784c32012-11-19 14:55:58 -08004022 // prevent any changes in effect chain list and in each effect chain
4023 // during mixing and effect process as the audio buffers could be deleted
4024 // or modified if an effect is created or deleted
4025 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004026
4027 // Determine which session to pick up haptic data.
4028 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004029 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004030 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004031 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004032 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004033 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004034 if (effectChain != nullptr
4035 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004036 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004037 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004038 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004039 break;
4040 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004041 if (activeHapticSessionId == AUDIO_SESSION_NONE
4042 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004043 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004044 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004045 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004046 }
4047 }
4048 }
4049
Andy Hungc1646382019-04-30 16:12:10 -07004050 // Acquire a local copy of active tracks with lock (release w/o lock).
4051 //
4052 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4053 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4054 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4055 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004056
4057 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004058
Jiabin Huangfb476842022-12-06 03:18:10 +00004059 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004060 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004061 }
4062
Eric Laurent19952e12023-04-20 10:08:29 +02004063 // signal actual start of output stream when the render position reported by the kernel
4064 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004065 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4066 && (mKernelPositionOnStandby
4067 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004068 mHalStarted = true;
4069 mWaitHalStartCV.broadcast();
4070 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004071 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004072
Eric Laurentbfb1b832013-01-07 09:53:42 -08004073 if (mBytesRemaining == 0) {
4074 mCurrentWriteLength = 0;
4075 if (mMixerStatus == MIXER_TRACKS_READY) {
4076 // threadLoop_mix() sets mCurrentWriteLength
4077 threadLoop_mix();
4078 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4079 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004080 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004081 // must be written to HAL
4082 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004083 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004084 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004085
4086 // Tally underrun frames as we are inserting 0s here.
4087 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004088 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004089 && !track->isStopped()
4090 && !track->isPaused()
4091 && !track->isTerminated()) {
4092 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4093 __func__, track->id(), track->getTrackStateAsString(),
4094 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004095 track->audioTrackServerProxy()->tallyUnderrunFrames(
4096 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004097 }
4098 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099 }
4100 }
Andy Hung98ef9782014-03-04 14:46:50 -08004101 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004102 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004103 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004104 // or mSinkBuffer (if there are no effects and there is no data already copied to
4105 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004106 //
4107 // This is done pre-effects computation; if effects change to
4108 // support higher precision, this needs to move.
4109 //
4110 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004111 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004112 uint32_t mixerChannelCount = mEffectBufferValid ?
4113 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004114 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004115 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4116 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4117
David Li88ee0902022-06-22 10:01:21 +08004118 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4119 // do these processes after effects are applied.
4120 if (!mEffectBufferValid) {
4121 // mono blend occurs for mixer threads only (not direct or offloaded)
4122 // and is handled here if we're going directly to the sink.
4123 if (requireMonoBlend()) {
4124 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4125 mNormalFrameCount, true /*limit*/);
4126 }
Andy Hung2ddee192015-12-18 17:34:44 -08004127
David Li88ee0902022-06-22 10:01:21 +08004128 if (!hasFastMixer()) {
4129 // Balance must take effect after mono conversion.
4130 // We do it here if there is no FastMixer.
4131 // mBalance detects zero balance within the class for speed
4132 // (not needed here).
4133 mBalance.setBalance(mMasterBalance.load());
4134 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4135 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004136 }
4137
Andy Hung98ef9782014-03-04 14:46:50 -08004138 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004139 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004140
4141 // If we're going directly to the sink and there are haptic channels,
4142 // we should adjust channels as the sample data is partially interleaved
4143 // in this case.
4144 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4145 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4146 mChannelCount + mHapticChannelCount,
4147 audio_bytes_per_sample(format),
4148 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4149 }
Andy Hung98ef9782014-03-04 14:46:50 -08004150 }
4151
Eric Laurentbfb1b832013-01-07 09:53:42 -08004152 mBytesRemaining = mCurrentWriteLength;
4153 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004154 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4155 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4156 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4157 mBytesWritten += mBytesRemaining;
4158 mFramesWritten += framesRemaining;
4159 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004160 mBytesRemaining = 0;
4161 }
Eric Laurent81784c32012-11-19 14:55:58 -08004162
Eric Laurentbfb1b832013-01-07 09:53:42 -08004163 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004164 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 for (size_t i = 0; i < effectChains.size(); i ++) {
4166 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004167 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004168 if (activeHapticSessionId != AUDIO_SESSION_NONE
4169 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004170 // Haptic data is active in this case, copy it directly from
4171 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004172 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4173 audio_channel_count_from_out_mask(mMixerChannelMask) :
4174 mChannelCount;
4175 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4176 hapticSessionChannelCount = mChannelCount;
4177 }
4178
jiabin47affe52019-04-04 18:02:07 -07004179 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004180 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004181 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004182 memcpy_by_audio_format(
4183 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004184 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004185 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004186 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004187 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004188 }
Eric Laurent81784c32012-11-19 14:55:58 -08004189 }
4190 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004191 // Process effect chains for offloaded thread even if no audio
4192 // was read from audio track: process only updates effect state
4193 // and thus does have to be synchronized with audio writes but may have
4194 // to be called while waiting for async write callback
4195 if (mType == OFFLOAD) {
4196 for (size_t i = 0; i < effectChains.size(); i ++) {
4197 effectChains[i]->process_l();
4198 }
4199 }
Eric Laurent81784c32012-11-19 14:55:58 -08004200
Andy Hung98ef9782014-03-04 14:46:50 -08004201 // Only if the Effects buffer is enabled and there is data in the
4202 // Effects buffer (buffer valid), we need to
4203 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004204 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004205 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004206 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004207 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004208 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004209 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004210 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004211 }
4212
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004213 if (!hasFastMixer()) {
4214 // Balance must take effect after mono conversion.
4215 // We do it here if there is no FastMixer.
4216 // mBalance detects zero balance within the class for speed (not needed here).
4217 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004218 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004219 }
4220
Eric Laurentb62d0362021-10-26 17:40:18 +02004221 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4222 // mPostSpatializerBuffer if the haptics track is spatialized.
4223 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4224 // For other thread types, the haptics channels are already in mEffectBuffer.
4225 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4226 const size_t srcBufferSize = mNormalFrameCount *
4227 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4228 mEffectBufferFormat);
4229 const size_t dstBufferSize = mNormalFrameCount
4230 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4231
4232 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4233 mEffectBufferFormat,
4234 (uint8_t*)mEffectBuffer + srcBufferSize,
4235 mEffectBufferFormat,
4236 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004237 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004238 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4239 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4240 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4241 // Clamp PCM float values more than this distance from 0 to insulate
4242 // a HAL which doesn't handle NaN correctly.
4243 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4244 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4245 static_cast<const float*>(effectBuffer),
4246 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4247 } else {
4248 memcpy_by_audio_format(mSinkBuffer, mFormat,
4249 effectBuffer, mEffectBufferFormat, framesToCopy);
4250 }
jiabin245cdd92018-12-07 17:55:15 -08004251 // The sample data is partially interleaved when haptic channels exist,
4252 // we need to adjust channels here.
4253 if (mHapticChannelCount > 0) {
4254 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4255 mChannelCount + mHapticChannelCount,
4256 audio_bytes_per_sample(mFormat),
4257 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4258 }
Andy Hung98ef9782014-03-04 14:46:50 -08004259 }
4260
Eric Laurent81784c32012-11-19 14:55:58 -08004261 // enable changes in effect chain
4262 unlockEffectChains(effectChains);
4263
Vlad Popafce10862023-02-03 10:37:07 +01004264 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
4265 mAudioFlinger->mMelReporter->updateMetadataForCsd(id(),
4266 metadataUpdate.playbackMetadataUpdate);
4267 }
4268
Eric Laurentbfb1b832013-01-07 09:53:42 -08004269 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004270 // mSleepTimeUs == 0 means we must write to audio hardware
4271 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004272 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004273 // writePeriodNs is updated >= 0 when ret > 0.
4274 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004275 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004276 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004277 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004278 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004279 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004280 if (ret < 0) {
4281 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004282 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004283 mBytesWritten += ret;
4284 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004285 const int64_t frames = ret / mFrameSize;
4286 mFramesWritten += frames;
4287
4288 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4289 // process information relating to write time.
4290 if (audio_has_proportional_frames(mFormat)) {
4291 // we are in a continuous mixing cycle
4292 if (mMixerStatus == MIXER_TRACKS_READY &&
4293 loopCount == lastLoopCountWritten + 1) {
4294
4295 const double jitterMs =
4296 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4297 {frames, writePeriodNs},
4298 {0, 0} /* lastTimestamp */, mSampleRate);
4299 const double processMs =
4300 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4301
4302 Mutex::Autolock _l(mLock);
4303 mIoJitterMs.add(jitterMs);
4304 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004305
4306 if (mPipeSink.get() != nullptr) {
4307 // Using the Monopipe availableToWrite, we estimate the current
4308 // buffer size.
4309 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4310 const ssize_t
4311 availableToWrite = mPipeSink->availableToWrite();
4312 const size_t pipeFrames = monoPipe->maxFrames();
4313 const size_t
4314 remainingFrames = pipeFrames - max(availableToWrite, 0);
4315 mMonopipePipeDepthStats.add(remainingFrames);
4316 }
Andy Hung446f4df2019-02-21 12:26:41 -08004317 }
4318
4319 // write blocked detection
4320 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004321 if ((mType == MIXER || mType == SPATIALIZER)
4322 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004323 mNumDelayedWrites++;
4324 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4325 ATRACE_NAME("underrun");
4326 ALOGW("write blocked for %lld msecs, "
4327 "%d delayed writes, thread %d",
4328 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4329 mNumDelayedWrites, mId);
4330 lastWarning = lastIoEndNs;
4331 }
4332 }
4333 }
4334 // update timing info.
4335 mLastIoBeginNs = lastIoBeginNs;
4336 mLastIoEndNs = lastIoEndNs;
4337 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004338 }
4339 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4340 (mMixerStatus == MIXER_DRAIN_ALL)) {
4341 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004342 }
Andy Hungd3639922022-04-28 18:00:49 -07004343 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004344
4345 if (mThreadThrottle
4346 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004347 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004348 // Limit MixerThread data processing to no more than twice the
4349 // expected processing rate.
4350 //
4351 // This helps prevent underruns with NuPlayer and other applications
4352 // which may set up buffers that are close to the minimum size, or use
4353 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4354 //
4355 // The throttle smooths out sudden large data drains from the device,
4356 // e.g. when it comes out of standby, which often causes problems with
4357 // (1) mixer threads without a fast mixer (which has its own warm-up)
4358 // (2) minimum buffer sized tracks (even if the track is full,
4359 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004360 //
4361 // Total time spent in last processing cycle equals time spent in
4362 // 1. threadLoop_write, as well as time spent in
4363 // 2. threadLoop_mix (significant for heavy mixing, especially
4364 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004365
Andy Hung446f4df2019-02-21 12:26:41 -08004366 // it's OK if deltaMs is an overestimate.
4367
4368 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004369
Ivan Lozanoea04d392017-11-07 14:37:07 -08004370 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004371 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004372 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004373
Andy Hung08fb1742015-05-31 23:22:10 -07004374 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004375 // notify of throttle start on verbose log
4376 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4377 "mixer(%p) throttle begin:"
4378 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004379 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004380 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004381 // Throttle must be attributed to the previous mixer loop's write time
4382 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004383 // This also ensures proper timing statistics.
4384 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004385 } else {
4386 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4387 if (diff > 0) {
4388 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004389 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004390 ALOGD_IF(!isSingleDeviceType(
4391 outDeviceTypes(), audio_is_a2dp_out_device) &&
4392 !isSingleDeviceType(
4393 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004394 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004395 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4396 }
Andy Hung08fb1742015-05-31 23:22:10 -07004397 }
4398 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004399 }
Eric Laurent81784c32012-11-19 14:55:58 -08004400
Eric Laurentbfb1b832013-01-07 09:53:42 -08004401 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004402 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004403 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004404 // suspended requires accurate metering of sleep time.
4405 if (isSuspended()) {
4406 // advance by expected sleepTime
4407 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4408 const nsecs_t nowNs = systemTime();
4409
4410 // compute expected next time vs current time.
4411 // (negative deltas are treated as delays).
4412 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4413 if (deltaNs < -kMaxNextBufferDelayNs) {
4414 // Delays longer than the max allowed trigger a reset.
4415 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4416 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4417 timeLoopNextNs = nowNs + deltaNs;
4418 } else if (deltaNs < 0) {
4419 // Delays within the max delay allowed: zero the delta/sleepTime
4420 // to help the system catch up in the next iteration(s)
4421 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4422 deltaNs = 0;
4423 }
4424 // update sleep time (which is >= 0)
4425 mSleepTimeUs = deltaNs / 1000;
4426 }
Eric Laurente93cc032016-05-05 10:15:10 -07004427 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4428 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004429 }
Glenn Kastene7754022014-10-31 12:11:26 -07004430 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004431 }
Eric Laurent81784c32012-11-19 14:55:58 -08004432 }
4433
4434 // Finally let go of removed track(s), without the lock held
4435 // since we can't guarantee the destructors won't acquire that
4436 // same lock. This will also mutate and push a new fast mixer state.
4437 threadLoop_removeTracks(tracksToRemove);
4438 tracksToRemove.clear();
4439
4440 // FIXME I don't understand the need for this here;
4441 // it was in the original code but maybe the
4442 // assignment in saveOutputTracks() makes this unnecessary?
4443 clearOutputTracks();
4444
4445 // Effect chains will be actually deleted here if they were removed from
4446 // mEffectChains list during mixing or effects processing
4447 effectChains.clear();
4448
4449 // FIXME Note that the above .clear() is no longer necessary since effectChains
4450 // is now local to this block, but will keep it for now (at least until merge done).
4451 }
4452
Eric Laurentbfb1b832013-01-07 09:53:42 -08004453 threadLoop_exit();
4454
Eric Laurentcf817a22014-08-04 20:36:31 -07004455 if (!mStandby) {
4456 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004457 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004458 }
4459
4460 releaseWakeLock();
4461
4462 ALOGV("Thread %p type %d exiting", this, mType);
4463 return false;
4464}
4465
Andy Hung4b17e882023-07-07 13:47:37 -07004466void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004467{
Dean Wheatley12473e92021-03-18 23:00:55 +11004468 if (mStandby) {
4469 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4470 return;
4471 } else if (mHwPaused) {
4472 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4473 return;
4474 }
4475
4476 // Gather the framesReleased counters for all active tracks,
4477 // and associate with the sink frames written out. We need
4478 // this to convert the sink timestamp to the track timestamp.
4479 bool kernelLocationUpdate = false;
4480 ExtendedTimestamp timestamp; // use private copy to fetch
4481
4482 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4483 // HAL may be draining some small duration buffered data for fade out.
4484 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4485 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4486 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4487 mSampleRate);
4488
4489 if (isTimestampCorrectionEnabled()) {
4490 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4491 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4492 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4493 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4494 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4495 = correctedTimestamp.mFrames;
4496 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4497 = correctedTimestamp.mTimeNs;
4498 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4499 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4500 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4501
4502 // Note: Downstream latency only added if timestamp correction enabled.
4503 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4504 const int64_t newPosition =
4505 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4506 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4507 // prevent retrograde
4508 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4509 newPosition,
4510 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4511 - mSuspendedFrames));
4512 }
4513 }
4514
4515 // We always fetch the timestamp here because often the downstream
4516 // sink will block while writing.
4517
4518 // We keep track of the last valid kernel position in case we are in underrun
4519 // and the normal mixer period is the same as the fast mixer period, or there
4520 // is some error from the HAL.
4521 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4522 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4523 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4524 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4525 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4526
4527 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4528 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4529 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4530 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4531 }
4532
4533 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4534 kernelLocationUpdate = true;
4535 } else {
4536 ALOGVV("getTimestamp error - no valid kernel position");
4537 }
4538
4539 // copy over kernel info
4540 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4541 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4542 + mSuspendedFrames; // add frames discarded when suspended
4543 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4544 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4545 } else {
4546 mTimestampVerifier.error();
4547 }
4548
4549 // mFramesWritten for non-offloaded tracks are contiguous
4550 // even after standby() is called. This is useful for the track frame
4551 // to sink frame mapping.
4552 bool serverLocationUpdate = false;
4553 if (mFramesWritten != mLastFramesWritten) {
4554 serverLocationUpdate = true;
4555 mLastFramesWritten = mFramesWritten;
4556 }
4557 // Only update timestamps if there is a meaningful change.
4558 // Either the kernel timestamp must be valid or we have written something.
4559 if (kernelLocationUpdate || serverLocationUpdate) {
4560 if (serverLocationUpdate) {
4561 // use the time before we called the HAL write - it is a bit more accurate
4562 // to when the server last read data than the current time here.
4563 //
4564 // If we haven't written anything, mLastIoBeginNs will be -1
4565 // and we use systemTime().
4566 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4567 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4568 ? systemTime() : mLastIoBeginNs;
4569 }
4570
Andy Hung11e74242023-06-26 19:20:57 -07004571 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004572 if (!t->isFastTrack()) {
4573 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004574 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004575 mFramesWritten,
4576 mSampleRate,
4577 mTimestamp);
4578 }
4579 }
4580 }
4581
4582 if (audio_has_proportional_frames(mFormat)) {
4583 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4584 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4585 mLatencyMs.add(latencyMs);
4586 }
4587 }
4588#if 0
4589 // logFormat example
4590 if (z % 100 == 0) {
4591 timespec ts;
4592 clock_gettime(CLOCK_MONOTONIC, &ts);
4593 LOGT("This is an integer %d, this is a float %f, this is my "
4594 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4595 LOGT("A deceptive null-terminated string %\0");
4596 }
4597 ++z;
4598#endif
4599}
4600
Eric Laurentbfb1b832013-01-07 09:53:42 -08004601// removeTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07004602void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung920f6572022-10-06 12:09:49 -07004603NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004604{
Andy Hungfe726a62018-09-27 15:17:25 -07004605 for (const auto& track : tracksToRemove) {
4606 mActiveTracks.remove(track);
4607 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004608 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004609 if (chain != 0) {
4610 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4611 __func__, track->id(), chain.get(), track->sessionId());
4612 chain->decActiveTrackCnt();
4613 }
4614 // If an external client track, inform APM we're no longer active, and remove if needed.
4615 // We do this under lock so that the state is consistent if the Track is destroyed.
4616 if (track->isExternalTrack()) {
4617 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004618 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004619 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004620 }
4621 }
Andy Hungfe726a62018-09-27 15:17:25 -07004622 if (track->isTerminated()) {
4623 // remove from our tracks vector
4624 removeTrack_l(track);
4625 }
jiabineb3bda02020-06-30 14:07:03 -07004626 if (mHapticChannelCount > 0 &&
4627 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4628 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004629 mLock.unlock();
4630 // Unlock due to VibratorService will lock for this call and will
4631 // call Tracks.mute/unmute which also require thread's lock.
4632 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4633 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004634
4635 // When the track is stop, set the haptic intensity as MUTE
4636 // for the HapticGenerator effect.
4637 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004638 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004639 }
jiabin245cdd92018-12-07 17:55:15 -08004640 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004641 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004642}
Eric Laurent81784c32012-11-19 14:55:58 -08004643
Andy Hung4b17e882023-07-07 13:47:37 -07004644status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004645{
4646 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004647 ExtendedTimestamp ets;
4648 status_t status = mNormalSink->getTimestamp(ets);
4649 if (status == NO_ERROR) {
4650 status = ets.getBestTimestamp(&timestamp);
4651 }
4652 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004653 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004654 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004655 collectTimestamps_l();
4656 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4657 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004658 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004659 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4660 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4661 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4662 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4663 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004664 }
4665 return INVALID_OPERATION;
4666}
Eric Laurent1c333e22014-05-20 10:48:17 -07004667
Eric Laurenteab90452019-06-24 15:17:46 -07004668// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4669// still applied by the mixer.
4670// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4671// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4672// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004673status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004674{
4675 status_t result = NO_ERROR;
4676 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4677 if (*volume != mLeftVolFloat) {
4678 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004679 // HAL can return INVALID_OPERATION if operation is not supported.
4680 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004681 "Error when setting output stream volume: %d", result);
4682 if (result == NO_ERROR) {
4683 mLeftVolFloat = *volume;
4684 }
4685 }
4686 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4687 // remove stream volume contribution from software volume.
4688 if (mLeftVolFloat == *volume) {
4689 *volume = 1.0f;
4690 }
4691 }
4692 return result;
4693}
4694
Andy Hung4b17e882023-07-07 13:47:37 -07004695status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004696 audio_patch_handle_t *handle)
4697{
Andy Hungf60abce2016-08-26 11:37:54 -07004698 status_t status;
4699 if (property_get_bool("af.patch_park", false /* default_value */)) {
4700 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4701 // or if HAL does not properly lock against access.
4702 AutoPark<FastMixer> park(mFastMixer);
4703 status = PlaybackThread::createAudioPatch_l(patch, handle);
4704 } else {
4705 status = PlaybackThread::createAudioPatch_l(patch, handle);
4706 }
Eric Laurentb0463942022-12-20 16:31:10 +01004707
4708 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004709 return status;
4710}
4711
Andy Hung4b17e882023-07-07 13:47:37 -07004712status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004713 audio_patch_handle_t *handle)
4714{
4715 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004716
4717 // store new device and send to effects
4718 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004719 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004720 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004721 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4722 && !mOutput->audioHwDev->supportsAudioPatches(),
4723 "Enumerated device type(%#x) must not be used "
4724 "as it does not support audio patches",
4725 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004726 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004727 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4728 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004729 }
4730
François Gaffie0c280aa2018-07-25 10:02:15 +02004731 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004732#ifdef ADD_BATTERY_DATA
4733 // when changing the audio output device, call addBatteryData to notify
4734 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004735 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004736 uint32_t params = 0;
4737 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004738 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004739 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004740 }
4741
Eric Laurent054d9d32015-04-24 08:48:48 -07004742 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004743 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004744 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4745 }
4746
4747 if (params != 0) {
4748 addBatteryData(params);
4749 }
4750 }
4751#endif
4752
4753 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004754 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004755 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004756
jiabinc52b1ff2019-10-31 17:20:42 -07004757 // mPatch.num_sinks is not set when the thread is created so that
4758 // the first patch creation triggers an ioConfigChanged callback
4759 bool configChanged = (mPatch.num_sinks == 0) ||
4760 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004761 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004762 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004763 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004764
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004765 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004766 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4767 status = hwDevice->createAudioPatch(patch->num_sources,
4768 patch->sources,
4769 patch->num_sinks,
4770 patch->sinks,
4771 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004772 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004773 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004774 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004775 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004776 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004777
4778 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004779 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004780 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004781 // also dispatch to active AudioTracks for MediaMetrics
4782 for (const auto &track : mActiveTracks) {
4783 track->logEndInterval();
4784 track->logBeginInterval(patchSinksAsString);
4785 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004786
Eric Laurente8726fe2015-06-26 09:39:24 -07004787 if (configChanged) {
4788 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4789 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004790 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004791 mActiveTracks.setHasChanged();
4792
Eric Laurent1c333e22014-05-20 10:48:17 -07004793 return status;
4794}
4795
Andy Hung4b17e882023-07-07 13:47:37 -07004796status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004797{
Andy Hungf60abce2016-08-26 11:37:54 -07004798 status_t status;
4799 if (property_get_bool("af.patch_park", false /* default_value */)) {
4800 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4801 // or if HAL does not properly lock against access.
4802 AutoPark<FastMixer> park(mFastMixer);
4803 status = PlaybackThread::releaseAudioPatch_l(handle);
4804 } else {
4805 status = PlaybackThread::releaseAudioPatch_l(handle);
4806 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004807 return status;
4808}
4809
Andy Hung4b17e882023-07-07 13:47:37 -07004810status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004811{
4812 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004813
jiabinc52b1ff2019-10-31 17:20:42 -07004814 mPatch = audio_patch{};
4815 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004816
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004817 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004818 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4819 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004820 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004821 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004822 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004823 // Force meteadata update after a route change
4824 mActiveTracks.setHasChanged();
4825
Eric Laurent1c333e22014-05-20 10:48:17 -07004826 return status;
4827}
4828
Andy Hung4b17e882023-07-07 13:47:37 -07004829void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004830{
4831 Mutex::Autolock _l(mLock);
4832 mTracks.add(track);
4833}
4834
Andy Hung4b17e882023-07-07 13:47:37 -07004835void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004836{
4837 Mutex::Autolock _l(mLock);
4838 destroyTrack_l(track);
4839}
4840
Andy Hung4b17e882023-07-07 13:47:37 -07004841void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004842{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004843 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004844 config->role = AUDIO_PORT_ROLE_SOURCE;
4845 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4846 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004847 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4848 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4849 config->flags.output = mOutput->flags;
4850 }
Eric Laurent83b88082014-06-20 18:31:16 -07004851}
4852
Eric Laurent81784c32012-11-19 14:55:58 -08004853// ----------------------------------------------------------------------------
4854
Andy Hung4b17e882023-07-07 13:47:37 -07004855/* static */
4856sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
4857 const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
4858 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
4859 return sp<MixerThread>::make(audioFlinger, output, id, systemReady, type, mixerConfig);
4860}
4861
4862MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004863 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4864 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004865 // mAudioMixer below
4866 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004867 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004868 mFastMixerFutex(0),
4869 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004870 // mOutputSink below
4871 // mPipeSink below
4872 // mNormalSink below
4873{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004874 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004875 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004876 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004877 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004878 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4879 mNormalFrameCount);
4880 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4881
Andy Hungfbfc3952015-01-15 13:33:51 -08004882 if (type == DUPLICATING) {
4883 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4884 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4885 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4886 return;
4887 }
Eric Laurent81784c32012-11-19 14:55:58 -08004888 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004889 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004890 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004891 const NBAIO_Format offers[1] = {Format_from_SR_C(
4892 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004893#if !LOG_NDEBUG
4894 ssize_t index =
4895#else
4896 (void)
4897#endif
4898 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004899 ALOG_ASSERT(index == 0);
4900
4901 // initialize fast mixer depending on configuration
4902 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004903 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004904 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004905 } else {
4906 switch (kUseFastMixer) {
4907 case FastMixer_Never:
4908 initFastMixer = false;
4909 break;
4910 case FastMixer_Always:
4911 initFastMixer = true;
4912 break;
4913 case FastMixer_Static:
4914 case FastMixer_Dynamic:
4915 initFastMixer = mFrameCount < mNormalFrameCount;
4916 break;
4917 }
4918 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4919 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4920 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004921 }
4922 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004923 audio_format_t fastMixerFormat;
4924 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4925 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4926 } else {
4927 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4928 }
4929 if (mFormat != fastMixerFormat) {
4930 // change our Sink format to accept our intermediate precision
4931 mFormat = fastMixerFormat;
4932 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004933 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004934 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4935 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4936 }
Eric Laurent81784c32012-11-19 14:55:58 -08004937
4938 // create a MonoPipe to connect our submix to FastMixer
4939 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004940
Andy Hung1258c1a2014-05-23 21:22:17 -07004941 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004942 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004943 format.mFormat = fastMixerFormat;
4944 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4945
Eric Laurent81784c32012-11-19 14:55:58 -08004946 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4947 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4948 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4949 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07004950 const NBAIO_Format offersFast[1] = {format};
4951 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004952#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02004953 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004954#else
4955 (void)
4956#endif
Andy Hung920f6572022-10-06 12:09:49 -07004957 monoPipe->negotiate(offersFast, std::size(offersFast),
4958 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004959 ALOG_ASSERT(index == 0);
4960 monoPipe->setAvgFrames((mScreenState & 1) ?
4961 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4962 mPipeSink = monoPipe;
4963
Eric Laurent81784c32012-11-19 14:55:58 -08004964 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004965 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004966 FastMixerStateQueue *sq = mFastMixer->sq();
4967#ifdef STATE_QUEUE_DUMP
4968 sq->setObserverDump(&mStateQueueObserverDump);
4969 sq->setMutatorDump(&mStateQueueMutatorDump);
4970#endif
4971 FastMixerState *state = sq->begin();
4972 FastTrack *fastTrack = &state->mFastTracks[0];
4973 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4974 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4975 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004976 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4977 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4978 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004979 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004980 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004981 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004982 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004983 fastTrack->mGeneration++;
4984 state->mFastTracksGen++;
4985 state->mTrackMask = 1;
4986 // fast mixer will use the HAL output sink
4987 state->mOutputSink = mOutputSink.get();
4988 state->mOutputSinkGen++;
4989 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004990 // specify sink channel mask when haptic channel mask present as it can not
4991 // be calculated directly from channel count
4992 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004993 ? AUDIO_CHANNEL_NONE
4994 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004995 state->mCommand = FastMixerState::COLD_IDLE;
4996 // already done in constructor initialization list
4997 //mFastMixerFutex = 0;
4998 state->mColdFutexAddr = &mFastMixerFutex;
4999 state->mColdGen++;
5000 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08005001 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
5002 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005003 sq->end();
5004 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5005
Eric Tan0513b5d2018-09-17 10:32:48 -07005006 NBLog::thread_info_t info;
5007 info.id = mId;
5008 info.type = NBLog::FASTMIXER;
5009 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5010
Eric Laurent81784c32012-11-19 14:55:58 -08005011 // start the fast mixer
5012 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5013 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005014 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005015 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005016
5017#ifdef AUDIO_WATCHDOG
5018 // create and start the watchdog
5019 mAudioWatchdog = new AudioWatchdog();
5020 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5021 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5022 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005023 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005024#endif
Andy Hung8946a282018-04-19 20:04:56 -07005025 } else {
5026#ifdef TEE_SINK
5027 // Only use the MixerThread tee if there is no FastMixer.
5028 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5029 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5030#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005031 }
5032
5033 switch (kUseFastMixer) {
5034 case FastMixer_Never:
5035 case FastMixer_Dynamic:
5036 mNormalSink = mOutputSink;
5037 break;
5038 case FastMixer_Always:
5039 mNormalSink = mPipeSink;
5040 break;
5041 case FastMixer_Static:
5042 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5043 break;
5044 }
5045}
5046
Andy Hung4b17e882023-07-07 13:47:37 -07005047MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005048{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005049 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005050 FastMixerStateQueue *sq = mFastMixer->sq();
5051 FastMixerState *state = sq->begin();
5052 if (state->mCommand == FastMixerState::COLD_IDLE) {
5053 int32_t old = android_atomic_inc(&mFastMixerFutex);
5054 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005055 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005056 }
5057 }
5058 state->mCommand = FastMixerState::EXIT;
5059 sq->end();
5060 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5061 mFastMixer->join();
5062 // Though the fast mixer thread has exited, it's state queue is still valid.
5063 // We'll use that extract the final state which contains one remaining fast track
5064 // corresponding to our sub-mix.
5065 state = sq->begin();
5066 ALOG_ASSERT(state->mTrackMask == 1);
5067 FastTrack *fastTrack = &state->mFastTracks[0];
5068 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5069 delete fastTrack->mBufferProvider;
5070 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005071 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005072#ifdef AUDIO_WATCHDOG
5073 if (mAudioWatchdog != 0) {
5074 mAudioWatchdog->requestExit();
5075 mAudioWatchdog->requestExitAndWait();
5076 mAudioWatchdog.clear();
5077 }
5078#endif
5079 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08005080 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005081 delete mAudioMixer;
5082}
5083
Andy Hung4b17e882023-07-07 13:47:37 -07005084void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005085 PlaybackThread::onFirstRef();
5086
5087 Mutex::Autolock _l(mLock);
5088 if (mOutput != nullptr && mOutput->stream != nullptr) {
5089 status_t status = mOutput->stream->setLatencyModeCallback(this);
5090 if (status != INVALID_OPERATION) {
5091 updateHalSupportedLatencyModes_l();
5092 }
5093 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5094 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5095 mBluetoothLatencyModesEnabled.store(
5096 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5097 }
5098}
Eric Laurent81784c32012-11-19 14:55:58 -08005099
Andy Hung4b17e882023-07-07 13:47:37 -07005100uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005101{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005102 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005103 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5104 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5105 }
5106 return latency;
5107}
5108
Andy Hung4b17e882023-07-07 13:47:37 -07005109ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005110{
5111 // FIXME we should only do one push per cycle; confirm this is true
5112 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005113 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005114 FastMixerStateQueue *sq = mFastMixer->sq();
5115 FastMixerState *state = sq->begin();
5116 if (state->mCommand != FastMixerState::MIX_WRITE &&
5117 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5118 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005119
5120 // FIXME workaround for first HAL write being CPU bound on some devices
5121 ATRACE_BEGIN("write");
5122 mOutput->write((char *)mSinkBuffer, 0);
5123 ATRACE_END();
5124
Eric Laurent81784c32012-11-19 14:55:58 -08005125 int32_t old = android_atomic_inc(&mFastMixerFutex);
5126 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005127 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
5129#ifdef AUDIO_WATCHDOG
5130 if (mAudioWatchdog != 0) {
5131 mAudioWatchdog->resume();
5132 }
5133#endif
5134 }
5135 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005136#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07005137 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005138 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005139#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005140 sq->end();
5141 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5142 if (kUseFastMixer == FastMixer_Dynamic) {
5143 mNormalSink = mPipeSink;
5144 }
5145 } else {
5146 sq->end(false /*didModify*/);
5147 }
5148 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005149 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005150}
5151
Andy Hung4b17e882023-07-07 13:47:37 -07005152void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005153{
5154 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005155 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005156 FastMixerStateQueue *sq = mFastMixer->sq();
5157 FastMixerState *state = sq->begin();
5158 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005159 // Report any frames trapped in the Monopipe
5160 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5161 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5162 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5163 "monoPipeWritten:%lld monoPipeLeft:%lld",
5164 (long long)mFramesWritten, (long long)mSuspendedFrames,
5165 (long long)mPipeSink->framesWritten(), pipeFrames);
5166 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5167
Eric Laurent81784c32012-11-19 14:55:58 -08005168 state->mCommand = FastMixerState::COLD_IDLE;
5169 state->mColdFutexAddr = &mFastMixerFutex;
5170 state->mColdGen++;
5171 mFastMixerFutex = 0;
5172 sq->end();
5173 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5174 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5175 if (kUseFastMixer == FastMixer_Dynamic) {
5176 mNormalSink = mOutputSink;
5177 }
5178#ifdef AUDIO_WATCHDOG
5179 if (mAudioWatchdog != 0) {
5180 mAudioWatchdog->pause();
5181 }
5182#endif
5183 } else {
5184 sq->end(false /*didModify*/);
5185 }
5186 }
5187 PlaybackThread::threadLoop_standby();
5188}
5189
Andy Hung4b17e882023-07-07 13:47:37 -07005190bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005191{
5192 return false;
5193}
5194
Andy Hung4b17e882023-07-07 13:47:37 -07005195bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196{
5197 return !mStandby;
5198}
5199
Andy Hung4b17e882023-07-07 13:47:37 -07005200bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005201{
5202 Mutex::Autolock _l(mLock);
5203 return waitingAsyncCallback_l();
5204}
5205
Eric Laurent81784c32012-11-19 14:55:58 -08005206// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005207void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005208{
5209 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005210 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005211 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005212 // discard any pending drain or write ack by incrementing sequence
5213 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5214 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005215 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005216 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5217 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005219 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005220 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005221}
5222
Andy Hung4b17e882023-07-07 13:47:37 -07005223void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005224{
5225 ALOGV("signal playback thread");
5226 broadcast_l();
5227}
5228
Andy Hung4b17e882023-07-07 13:47:37 -07005229void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005230{
5231 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5232 invalidateTracks((audio_stream_type_t)i);
5233 }
5234}
5235
Andy Hung4b17e882023-07-07 13:47:37 -07005236void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005237{
Eric Laurent81784c32012-11-19 14:55:58 -08005238 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005239 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005240 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005241 // increase sleep time progressively when application underrun condition clears.
5242 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5243 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5244 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005245 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005246 sleepTimeShift--;
5247 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005248 mSleepTimeUs = 0;
5249 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005250 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005251
Eric Laurent81784c32012-11-19 14:55:58 -08005252}
5253
Andy Hung4b17e882023-07-07 13:47:37 -07005254void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005255{
5256 // If no tracks are ready, sleep once for the duration of an output
5257 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005258 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005259 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005260 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5261 // Using the Monopipe availableToWrite, we estimate the
5262 // sleep time to retry for more data (before we underrun).
5263 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5264 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5265 const size_t pipeFrames = monoPipe->maxFrames();
5266 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5267 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5268 const size_t framesDelay = std::min(
5269 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5270 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5271 pipeFrames, framesLeft, framesDelay);
5272 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5273 } else {
5274 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5275 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5276 mSleepTimeUs = kMinThreadSleepTimeUs;
5277 }
5278 // reduce sleep time in case of consecutive application underruns to avoid
5279 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5280 // duration we would end up writing less data than needed by the audio HAL if
5281 // the condition persists.
5282 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5283 sleepTimeShift++;
5284 }
Eric Laurent81784c32012-11-19 14:55:58 -08005285 }
5286 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005287 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005288 }
5289 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005290 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5291 // before effects processing or output.
5292 if (mMixerBufferValid) {
5293 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005294 if (mType == SPATIALIZER) {
5295 memset(mSinkBuffer, 0, mSinkBufferSize);
5296 }
Andy Hung98ef9782014-03-04 14:46:50 -08005297 } else {
5298 memset(mSinkBuffer, 0, mSinkBufferSize);
5299 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005300 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005301 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5302 "anticipated start");
5303 }
5304 // TODO add standby time extension fct of effect tail
5305}
5306
5307// prepareTracks_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07005308PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005309 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005310{
Andy Hungc0691382018-09-12 18:01:57 -07005311 // clean up deleted track ids in AudioMixer before allocating new tracks
5312 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5313 // for each trackId, destroy it in the AudioMixer
5314 if (mAudioMixer->exists(trackId)) {
5315 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005316 }
5317 });
Andy Hungc0691382018-09-12 18:01:57 -07005318 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005319
5320 mixer_state mixerStatus = MIXER_IDLE;
5321 // find out which tracks need to be processed
5322 size_t count = mActiveTracks.size();
5323 size_t mixedTracks = 0;
5324 size_t tracksWithEffect = 0;
5325 // counts only _active_ fast tracks
5326 size_t fastTracks = 0;
5327 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5328
5329 float masterVolume = mMasterVolume;
5330 bool masterMute = mMasterMute;
5331
5332 if (masterMute) {
5333 masterVolume = 0;
5334 }
5335 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005336 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005337 if (chain != 0) {
5338 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5339 chain->setVolume_l(&v, &v);
5340 masterVolume = (float)((v + (1 << 23)) >> 24);
5341 chain.clear();
5342 }
5343
5344 // prepare a new state to push
5345 FastMixerStateQueue *sq = NULL;
5346 FastMixerState *state = NULL;
5347 bool didModify = false;
5348 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005349 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005350 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005351 sq = mFastMixer->sq();
5352 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005353 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005354 }
5355
Andy Hung69aed5f2014-02-25 17:24:40 -08005356 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005357 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005358
Andy Hungbd3b2b02018-05-21 10:53:11 -07005359 // DeferredOperations handles statistics after setting mixerStatus.
5360 class DeferredOperations {
5361 public:
Andy Hungea840382020-05-05 21:50:17 -07005362 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5363 : mMixerStatus(mixerStatus)
5364 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005365
5366 // when leaving scope, tally frames properly.
5367 ~DeferredOperations() {
5368 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5369 // because that is when the underrun occurs.
5370 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005371 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005372 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005373 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005374 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005375 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005376 }
5377 }
Andy Hungea840382020-05-05 21:50:17 -07005378 // send the max underrun frames for this mixer period
5379 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005380 }
5381
5382 // tallyUnderrunFrames() is called to update the track counters
5383 // with the number of underrun frames for a particular mixer period.
5384 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005385 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005386 mUnderrunFrames.emplace_back(track, underrunFrames);
5387 }
5388
5389 private:
5390 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005391 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005392 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005393 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005394 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005395
jiabin245cdd92018-12-07 17:55:15 -08005396 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005397 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005398 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005399
5400 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005401 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005402
5403 // process fast tracks
5404 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005405 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5406 "%s(%d): FastTrack(%d) present without FastMixer",
5407 __func__, id(), track->id());
5408
jiabin245cdd92018-12-07 17:55:15 -08005409 if (track->getHapticPlaybackEnabled()) {
5410 noFastHapticTrack = false;
5411 }
Eric Laurent81784c32012-11-19 14:55:58 -08005412
5413 // It's theoretically possible (though unlikely) for a fast track to be created
5414 // and then removed within the same normal mix cycle. This is not a problem, as
5415 // the track never becomes active so it's fast mixer slot is never touched.
5416 // The converse, of removing an (active) track and then creating a new track
5417 // at the identical fast mixer slot within the same normal mix cycle,
5418 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005419 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005420 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005421 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5422 FastTrack *fastTrack = &state->mFastTracks[j];
5423
5424 // Determine whether the track is currently in underrun condition,
5425 // and whether it had a recent underrun.
5426 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5427 FastTrackUnderruns underruns = ftDump->mUnderruns;
5428 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005429 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005430 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005431 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005432 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005433 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005434 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005435 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005436 // don't count underruns that occur while stopping or pausing
5437 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005438 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005439 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5440 recentUnderruns > 0) {
5441 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005442 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005443 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005444 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005445 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005446
5447 // This is similar to the state machine for normal tracks,
5448 // with a few modifications for fast tracks.
5449 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005450 switch (track->state()) {
5451 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005452 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005453 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005454 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005455 }
5456 break;
Andy Hung11e74242023-06-26 19:20:57 -07005457 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005458 // ramp down is not yet implemented
5459 track->setPaused();
5460 break;
Andy Hung11e74242023-06-26 19:20:57 -07005461 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005462 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005463 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005464 break;
Andy Hung11e74242023-06-26 19:20:57 -07005465 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005466 if (recentFull > 0 || recentPartial > 0) {
5467 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005468 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005469 }
5470 if (recentUnderruns == 0) {
5471 // no recent underruns: stay active
5472 break;
5473 }
5474 // there has recently been an underrun of some kind
5475 if (track->sharedBuffer() == 0) {
5476 // were any of the recent underruns "empty" (no frames available)?
5477 if (recentEmpty == 0) {
5478 // no, then ignore the partial underruns as they are allowed indefinitely
5479 break;
5480 }
5481 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005482 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005483 break;
5484 }
5485 // indicate to client process that the track was disabled because of underrun;
5486 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005487 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005488 // remove from active list, but state remains ACTIVE [confusing but true]
5489 isActive = false;
5490 break;
5491 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005492 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005493 case IAfTrackBase::STOPPING_2:
5494 case IAfTrackBase::PAUSED:
5495 case IAfTrackBase::STOPPED:
5496 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005497 // Check for presentation complete if track is inactive
5498 // We have consumed all the buffers of this track.
5499 // This would be incomplete if we auto-paused on underrun
5500 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005501 uint32_t latency = 0;
5502 status_t result = mOutput->stream->getLatency(&latency);
5503 ALOGE_IF(result != OK,
5504 "Error when retrieving output stream latency: %d", result);
5505 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005506 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005507 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5508 // track stays in active list until presentation is complete
5509 break;
5510 }
5511 }
5512 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005513 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005514 }
5515 if (track->isStopped()) {
5516 // Can't reset directly, as fast mixer is still polling this track
5517 // track->reset();
5518 // So instead mark this track as needing to be reset after push with ack
5519 resetMask |= 1 << i;
5520 }
5521 isActive = false;
5522 break;
Andy Hung11e74242023-06-26 19:20:57 -07005523 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005524 default:
Andy Hung11e74242023-06-26 19:20:57 -07005525 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005526 }
5527
5528 if (isActive) {
5529 // was it previously inactive?
5530 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005531 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5532 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005533 fastTrack->mBufferProvider = eabp;
5534 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005535 fastTrack->mChannelMask = track->channelMask();
5536 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005537 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005538 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005539 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005540 fastTrack->mGeneration++;
5541 state->mTrackMask |= 1 << j;
5542 didModify = true;
5543 // no acknowledgement required for newly active tracks
5544 }
Andy Hung11e74242023-06-26 19:20:57 -07005545 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005546 float volume;
5547 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5548 volume = 0.f;
5549 } else {
5550 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5551 }
5552
5553 handleVoipVolume_l(&volume);
5554
Eric Laurent81784c32012-11-19 14:55:58 -08005555 // cache the combined master volume and stream type volume for fast mixer; this
5556 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005557 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005558 proxy->framesReleased()).first;
5559 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005560 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005561 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005562 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5563 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5564
5565 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5566 /*muteState=*/{masterVolume == 0.f,
5567 mStreamTypes[track->streamType()].volume == 0.f,
5568 mStreamTypes[track->streamType()].mute,
5569 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005570 vlf == 0.f && vrf == 0.f,
5571 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005572
5573 vlf *= volume;
5574 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005575
jiabin76d94692022-12-15 21:51:21 +00005576 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005577 ++fastTracks;
5578 } else {
5579 // was it previously active?
5580 if (state->mTrackMask & (1 << j)) {
5581 fastTrack->mBufferProvider = NULL;
5582 fastTrack->mGeneration++;
5583 state->mTrackMask &= ~(1 << j);
5584 didModify = true;
5585 // If any fast tracks were removed, we must wait for acknowledgement
5586 // because we're about to decrement the last sp<> on those tracks.
5587 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5588 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005589 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5590 // AudioTrack may start (which may not be with a start() but with a write()
5591 // after underrun) and immediately paused or released. In that case the
5592 // FastTrack state hasn't had time to update.
5593 // TODO Remove the ALOGW when this theory is confirmed.
5594 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005595 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005596 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005597 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005598 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005599 }
5600 tracksToRemove->add(track);
5601 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005602 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005603 }
jiabin245cdd92018-12-07 17:55:15 -08005604 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5605 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5606 didModify = true;
5607 }
Eric Laurent81784c32012-11-19 14:55:58 -08005608 continue;
5609 }
5610
5611 { // local variable scope to avoid goto warning
5612
5613 audio_track_cblk_t* cblk = track->cblk();
5614
5615 // The first time a track is added we wait
5616 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005617 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005618
5619 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005620 // use the trackId as the AudioMixer name.
5621 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005622 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005623 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005624 track->channelMask(),
5625 track->format(),
5626 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005627 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005628 ALOGW("%s(): AudioMixer cannot create track(%d)"
5629 " mask %#x, format %#x, sessionId %d",
5630 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005631 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005632 tracksToRemove->add(track);
5633 track->invalidate(); // consider it dead.
5634 continue;
5635 }
5636 }
5637
Eric Laurent81784c32012-11-19 14:55:58 -08005638 // make sure that we have enough frames to mix one full buffer.
5639 // enforce this condition only once to enable draining the buffer in case the client
5640 // app does not call stop() and relies on underrun to stop:
5641 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5642 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005643 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005644 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5645 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005646
5647 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005648 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005649 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5650 // add frames already consumed but not yet released by the resampler
5651 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005652 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005653
Eric Laurent81784c32012-11-19 14:55:58 -08005654 uint32_t minFrames = 1;
5655 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5656 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005657 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005658 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005659
5660 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005661 if (ATRACE_ENABLED()) {
5662 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005663 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005664 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005665 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005666 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005667 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005668 !track->isPaused() && !track->isTerminated())
5669 {
Andy Hungc0691382018-09-12 18:01:57 -07005670 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005671
5672 mixedTracks++;
5673
Andy Hung69aed5f2014-02-25 17:24:40 -08005674 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5675 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005676 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005677 if (track->mainBuffer() != mSinkBuffer &&
5678 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005679 if (mEffectBufferEnabled) {
5680 mEffectBufferValid = true; // Later can set directly.
5681 }
Eric Laurent81784c32012-11-19 14:55:58 -08005682 chain = getEffectChain_l(track->sessionId());
5683 // Delegate volume control to effect in track effect chain if needed
5684 if (chain != 0) {
5685 tracksWithEffect++;
5686 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005687 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005688 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005689 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005690 }
5691 }
5692
5693
5694 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005695 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005696 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005697 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5698 if (track->state() == IAfTrackBase::RESUMING) {
5699 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005700 // If a new track is paused immediately after start, do not ramp on resume.
5701 if (cblk->mServer != 0) {
5702 param = AudioMixer::RAMP_VOLUME;
5703 }
Eric Laurent81784c32012-11-19 14:55:58 -08005704 }
Andy Hungc0691382018-09-12 18:01:57 -07005705 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005706 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005707 // FIXME should not make a decision based on mServer
5708 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005709 // If the track is stopped before the first frame was mixed,
5710 // do not apply ramp
5711 param = AudioMixer::RAMP_VOLUME;
5712 }
5713
5714 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005715 uint32_t vl, vr; // in U8.24 integer format
5716 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005717 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005718 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005719 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005720 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005721 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005722 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005723
Eric Laurenteab90452019-06-24 15:17:46 -07005724 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5725 v = 0;
5726 }
5727
5728 handleVoipVolume_l(&v);
5729
5730 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005731 vl = vr = 0;
5732 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005733 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005734 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005735 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005736 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5737 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005738 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005739 if (vlf > GAIN_FLOAT_UNITY) {
5740 ALOGV("Track left volume out of range: %.3g", vlf);
5741 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005742 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005743 if (vrf > GAIN_FLOAT_UNITY) {
5744 ALOGV("Track right volume out of range: %.3g", vrf);
5745 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005746 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005747
5748 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
5749 /*muteState=*/{masterVolume == 0.f,
5750 mStreamTypes[track->streamType()].volume == 0.f,
5751 mStreamTypes[track->streamType()].mute,
5752 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005753 vlf == 0.f && vrf == 0.f,
5754 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005755
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005756 // now apply the master volume and stream type volume and shaper volume
5757 vlf *= v * vh;
5758 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005759 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005760 // then derive vl and vr as U8.24 versions for the effect chain
5761 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5762 vl = (uint32_t) (scaleto8_24 * vlf);
5763 vr = (uint32_t) (scaleto8_24 * vrf);
5764 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005765 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005766 // send level comes from shared memory and so may be corrupt
5767 if (sendLevel > MAX_GAIN_INT) {
5768 ALOGV("Track send level out of range: %04X", sendLevel);
5769 sendLevel = MAX_GAIN_INT;
5770 }
Andy Hung6be49402014-05-30 10:42:03 -07005771 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5772 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005773 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005774
jiabin76d94692022-12-15 21:51:21 +00005775 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005776
Eric Laurent81784c32012-11-19 14:55:58 -08005777 // Delegate volume control to effect in track effect chain if needed
5778 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5779 // Do not ramp volume if volume is controlled by effect
5780 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005781 // Update remaining floating point volume levels
5782 vlf = (float)vl / (1 << 24);
5783 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07005784 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005785 } else {
5786 // force no volume ramp when volume controller was just disabled or removed
5787 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07005788 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005789 param = AudioMixer::VOLUME;
5790 }
Andy Hung11e74242023-06-26 19:20:57 -07005791 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005792 }
5793
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07005795 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005796 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005797
Andy Hungc0691382018-09-12 18:01:57 -07005798 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5799 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5800 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005801 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005802 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005803 AudioMixer::TRACK,
5804 AudioMixer::FORMAT, (void *)track->format());
5805 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005806 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005807 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005808 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005809
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005810 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005811 mAudioMixer->setParameter(
5812 trackId,
5813 AudioMixer::TRACK,
5814 AudioMixer::MIXER_CHANNEL_MASK,
5815 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5816 } else {
5817 mAudioMixer->setParameter(
5818 trackId,
5819 AudioMixer::TRACK,
5820 AudioMixer::MIXER_CHANNEL_MASK,
5821 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5822 }
5823
Glenn Kastene3aa6592012-12-04 12:22:46 -08005824 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005825 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005826 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005827 if (reqSampleRate == 0) {
5828 reqSampleRate = mSampleRate;
5829 } else if (reqSampleRate > maxSampleRate) {
5830 reqSampleRate = maxSampleRate;
5831 }
Eric Laurent81784c32012-11-19 14:55:58 -08005832 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005833 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005834 AudioMixer::RESAMPLE,
5835 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005836 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005837
Andy Hung8edb8dc2015-03-26 19:13:55 -07005838 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005839 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005840 AudioMixer::TIMESTRETCH,
5841 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005842 // cast away constness for this generic API.
5843 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005844
Andy Hung69aed5f2014-02-25 17:24:40 -08005845 /*
5846 * Select the appropriate output buffer for the track.
5847 *
Andy Hung98ef9782014-03-04 14:46:50 -08005848 * Tracks with effects go into their own effects chain buffer
5849 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005850 *
5851 * Other tracks can use mMixerBuffer for higher precision
5852 * channel accumulation. If this buffer is enabled
5853 * (mMixerBufferEnabled true), then selected tracks will accumulate
5854 * into it.
5855 *
5856 */
5857 if (mMixerBufferEnabled
5858 && (track->mainBuffer() == mSinkBuffer
5859 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005860 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005861 mAudioMixer->setParameter(
5862 trackId,
5863 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005864 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005865 mAudioMixer->setParameter(
5866 trackId,
5867 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005868 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005869 } else {
5870 mAudioMixer->setParameter(
5871 trackId,
5872 AudioMixer::TRACK,
5873 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5874 mAudioMixer->setParameter(
5875 trackId,
5876 AudioMixer::TRACK,
5877 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5878 // TODO: override track->mainBuffer()?
5879 mMixerBufferValid = true;
5880 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005881 } else {
5882 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005883 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005884 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005885 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005886 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005887 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005888 AudioMixer::TRACK,
5889 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5890 }
Eric Laurent81784c32012-11-19 14:55:58 -08005891 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005892 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005893 AudioMixer::TRACK,
5894 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005895 mAudioMixer->setParameter(
5896 trackId,
5897 AudioMixer::TRACK,
5898 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005899 mAudioMixer->setParameter(
5900 trackId,
5901 AudioMixer::TRACK,
5902 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung11e74242023-06-26 19:20:57 -07005903 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005904 mAudioMixer->setParameter(
5905 trackId,
5906 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07005907 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005908
5909 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005910 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005911
5912 // If one track is ready, set the mixer ready if:
5913 // - the mixer was not ready during previous round OR
5914 // - no other track is not ready
5915 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5916 mixerStatus != MIXER_TRACKS_ENABLED) {
5917 mixerStatus = MIXER_TRACKS_READY;
5918 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005919
5920 // Enable the next few lines to instrument a test for underrun log handling.
5921 // TODO: Remove when we have a better way of testing the underrun log.
5922#if 0
5923 static int i;
5924 if ((++i & 0xf) == 0) {
5925 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5926 }
5927#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005928 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005929 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005930 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005931 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5932 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005933 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005934 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005935 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005936
Eric Laurent81784c32012-11-19 14:55:58 -08005937 // clear effect chain input buffer if an active track underruns to avoid sending
5938 // previous audio buffer again to effects
5939 chain = getEffectChain_l(track->sessionId());
5940 if (chain != 0) {
5941 chain->clearInputBuffer();
5942 }
5943
Andy Hungc0691382018-09-12 18:01:57 -07005944 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005945 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5946 track->isStopped() || track->isPaused()) {
5947 // We have consumed all the buffers of this track.
5948 // Remove it from the list of active tracks.
5949 // TODO: use actual buffer filling status instead of latency when available from
5950 // audio HAL
5951 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005952 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005953 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5954 if (track->isStopped()) {
5955 track->reset();
5956 }
5957 tracksToRemove->add(track);
5958 }
5959 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005960 // No buffers for this track. Give it a few chances to
5961 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07005962 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005963 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5964 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005965 tracksToRemove->add(track);
5966 // indicate to client process that the track was disabled because of underrun;
5967 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005968 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005969 // If one track is not ready, mark the mixer also not ready if:
5970 // - the mixer was ready during previous round OR
5971 // - no other track is ready
5972 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5973 mixerStatus != MIXER_TRACKS_READY) {
5974 mixerStatus = MIXER_TRACKS_ENABLED;
5975 }
5976 }
Andy Hungc0691382018-09-12 18:01:57 -07005977 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005978 }
5979
5980 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005981
5982 }
5983
jiabin245cdd92018-12-07 17:55:15 -08005984 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5985 // When there is no fast track playing haptic and FastMixer exists,
5986 // enabling the first FastTrack, which provides mixed data from normal
5987 // tracks, to play haptic data.
5988 FastTrack *fastTrack = &state->mFastTracks[0];
5989 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5990 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5991 didModify = true;
5992 }
5993 }
5994
Eric Laurent81784c32012-11-19 14:55:58 -08005995 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08005996 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005997 if (didModify) {
5998 state->mFastTracksGen++;
5999 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6000 if (kUseFastMixer == FastMixer_Dynamic &&
6001 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6002 state->mCommand = FastMixerState::COLD_IDLE;
6003 state->mColdFutexAddr = &mFastMixerFutex;
6004 state->mColdGen++;
6005 mFastMixerFutex = 0;
6006 if (kUseFastMixer == FastMixer_Dynamic) {
6007 mNormalSink = mOutputSink;
6008 }
6009 // If we go into cold idle, need to wait for acknowledgement
6010 // so that fast mixer stops doing I/O.
6011 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6012 pauseAudioWatchdog = true;
6013 }
Eric Laurent81784c32012-11-19 14:55:58 -08006014 }
6015 if (sq != NULL) {
6016 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006017 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6018 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6019 // when bringing the output sink into standby.)
6020 //
6021 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6022 //
6023 // This occurs with BT suspend when we idle the FastMixer with
6024 // active tracks, which may be added or removed.
6025 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006026 }
6027#ifdef AUDIO_WATCHDOG
6028 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6029 mAudioWatchdog->pause();
6030 }
6031#endif
6032
6033 // Now perform the deferred reset on fast tracks that have stopped
6034 while (resetMask != 0) {
6035 size_t i = __builtin_ctz(resetMask);
6036 ALOG_ASSERT(i < count);
6037 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006038 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006039 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6040 track->reset();
6041 }
6042
Andy Hung80d03d22018-04-10 10:32:11 -07006043 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6044 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6045 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6046 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6047 // See also the implementation of destroyTrack_l().
6048 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006049 const int trackId = track->id();
6050 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6051 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006052 }
6053 }
6054
Eric Laurent81784c32012-11-19 14:55:58 -08006055 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006056 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006057
Eric Laurentb3f315a2021-07-13 15:09:05 +02006058 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6059 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006060 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006061 }
6062
6063 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006064 // as long as there are effects we should clear the effects buffer, to avoid
6065 // passing a non-clean buffer to the effect chain
6066 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006067 if (mType == SPATIALIZER) {
6068 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6069 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006070 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006071 // sink or mix buffer must be cleared if all tracks are connected to an
6072 // effect chain as in this case the mixer will not write to the sink or mix buffer
6073 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006074 // always clear sink buffer for spatializer output as the output of the spatializer
6075 // effect will be accumulated into it
6076 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6077 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006078 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006079 if (mMixerBufferValid) {
6080 memset(mMixerBuffer, 0, mMixerBufferSize);
6081 // TODO: In testing, mSinkBuffer below need not be cleared because
6082 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6083 // after mixing.
6084 //
6085 // To enforce this guarantee:
6086 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6087 // (mixedTracks == 0 && fastTracks > 0))
6088 // must imply MIXER_TRACKS_READY.
6089 // Later, we may clear buffers regardless, and skip much of this logic.
6090 }
Andy Hung98ef9782014-03-04 14:46:50 -08006091 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006092 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006093 }
6094
6095 // if any fast tracks, then status is ready
6096 mMixerStatusIgnoringFastTracks = mixerStatus;
6097 if (fastTracks > 0) {
6098 mixerStatus = MIXER_TRACKS_READY;
6099 }
6100 return mixerStatus;
6101}
6102
Eric Laurentad7dd962016-09-22 12:38:37 -07006103// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006104uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006105{
6106 uint32_t trackCount = 0;
6107 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006108 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006109 trackCount++;
6110 }
6111 }
6112 return trackCount;
6113}
6114
Andy Hung4b17e882023-07-07 13:47:37 -07006115bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006116{
Brian Lindahl65e90012022-07-27 18:01:07 +02006117 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6118 // could falsely detect that the frame position has stalled due to underrun because we haven't
6119 // given the Audio HAL enough time to update.
6120 const nsecs_t nowNs = systemTime();
6121 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6122 return mLatchedValue;
6123 }
6124 mPreviousNs = nowNs;
6125 mLatchedValue = false;
6126 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006127 uint64_t position = 0;
6128 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006129 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006130 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006131 if (position != mPreviousPosition) {
6132 mPreviousPosition = position;
6133 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006134 }
6135 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006136 return mLatchedValue;
6137}
6138
Andy Hung4b17e882023-07-07 13:47:37 -07006139void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006140{
6141 mLatchedValue = true;
6142 mPreviousPosition = 0;
6143 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006144}
6145
Andy Hung1bc088a2018-02-09 15:57:31 -08006146// isTrackAllowed_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006147bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006148 audio_channel_mask_t channelMask, audio_format_t format,
6149 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006150{
Andy Hung1bc088a2018-02-09 15:57:31 -08006151 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6152 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006153 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006154 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006155 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006156 ALOGW("%s: invalid format: %#x", __func__, format);
6157 return false;
6158 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006159 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006160 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6161 return false;
6162 }
6163 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006164}
6165
Eric Laurent10351942014-05-08 18:49:52 -07006166// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006167bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006168 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006169{
Eric Laurent81784c32012-11-19 14:55:58 -08006170 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006171 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006172
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006173 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006174
Eric Laurent10351942014-05-08 18:49:52 -07006175 AudioParameter param = AudioParameter(keyValuePair);
6176 int value;
6177 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6178 reconfig = true;
6179 }
6180 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung4b17e882023-07-07 13:47:37 -07006181 if (!AudioFlinger::isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006182 status = BAD_VALUE;
6183 } else {
6184 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006185 reconfig = true;
6186 }
Eric Laurent10351942014-05-08 18:49:52 -07006187 }
6188 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung4b17e882023-07-07 13:47:37 -07006189 if (!AudioFlinger::isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006190 status = BAD_VALUE;
6191 } else {
6192 // no need to save value, since it's constant
6193 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006194 }
Eric Laurent10351942014-05-08 18:49:52 -07006195 }
6196 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6197 // do not accept frame count changes if tracks are open as the track buffer
6198 // size depends on frame count and correct behavior would not be guaranteed
6199 // if frame count is changed after track creation
6200 if (!mTracks.isEmpty()) {
6201 status = INVALID_OPERATION;
6202 } else {
6203 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006204 }
Eric Laurent10351942014-05-08 18:49:52 -07006205 }
6206 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006207 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006208 }
Eric Laurent81784c32012-11-19 14:55:58 -08006209
Eric Laurent10351942014-05-08 18:49:52 -07006210 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006211 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006212 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006213 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6214 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006215 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006216 mThreadMetrics.logEndInterval();
6217 mThreadSnapshot.onEnd();
6218 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006219 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006220 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006221 }
Eric Laurent10351942014-05-08 18:49:52 -07006222 if (status == NO_ERROR && reconfig) {
6223 readOutputParameters_l();
6224 delete mAudioMixer;
6225 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006226 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006227 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006228 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006229 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006230 track->channelMask(),
6231 track->format(),
6232 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006233 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006234 "%s(): AudioMixer cannot create track(%d)"
6235 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006236 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006237 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006238 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006239 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006240 }
Eric Laurent81784c32012-11-19 14:55:58 -08006241 }
6242
Dean Wheatley68918102021-03-19 22:09:19 +11006243 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006244}
6245
6246
Andy Hung4b17e882023-07-07 13:47:37 -07006247void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006248{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006249 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006250 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006251 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006252 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006253 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6254 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6255 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006256 if (hasFastMixer()) {
6257 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6258
6259 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6260 // while we are dumping it. It may be inconsistent, but it won't mutate!
6261 // This is a large object so we place it on the heap.
6262 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006263 const std::unique_ptr<FastMixerDumpState> copy =
6264 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006265 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006266
6267#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006268 // Similar for state queue
6269 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6270 observerCopy.dump(fd);
6271 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6272 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006273#endif
6274
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006275#ifdef AUDIO_WATCHDOG
6276 if (mAudioWatchdog != 0) {
6277 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6278 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6279 wdCopy.dump(fd);
6280 }
6281#endif
6282
6283 } else {
6284 dprintf(fd, " No FastMixer\n");
6285 }
Eric Laurent90cea102023-05-15 15:08:27 +02006286
6287 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6288 mBluetoothLatencyModesEnabled ? "" : "not ");
6289 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6290 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6291 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006292}
6293
Andy Hung4b17e882023-07-07 13:47:37 -07006294uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006295{
6296 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6297}
6298
Andy Hung4b17e882023-07-07 13:47:37 -07006299uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006300{
6301 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6302}
6303
Andy Hung4b17e882023-07-07 13:47:37 -07006304void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006305{
6306 PlaybackThread::cacheParameters_l();
6307
6308 // FIXME: Relaxed timing because of a certain device that can't meet latency
6309 // Should be reduced to 2x after the vendor fixes the driver issue
6310 // increase threshold again due to low power audio mode. The way this warning
6311 // threshold is calculated and its usefulness should be reconsidered anyway.
6312 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6313}
6314
Andy Hung4b17e882023-07-07 13:47:37 -07006315void MixerThread::onHalLatencyModesChanged_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006316 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
6317}
6318
Andy Hung4b17e882023-07-07 13:47:37 -07006319void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006320 // Only handle latency mode if:
6321 // - mBluetoothLatencyModesEnabled is true
6322 // - the HAL supports latency modes
6323 // - the selected device is Bluetooth LE or A2DP
6324 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6325 return;
6326 }
6327 if (mOutDeviceTypeAddrs.size() != 1
6328 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6329 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6330 return;
6331 }
6332
6333 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6334 if (mSupportedLatencyModes.size() == 1) {
6335 // If the HAL only support one latency mode currently, confirm the choice
6336 latencyMode = mSupportedLatencyModes[0];
6337 } else if (mSupportedLatencyModes.size() > 1) {
6338 // Request low latency if:
6339 // - At least one active track is either:
6340 // - a fast track with gaming usage or
6341 // - a track with acessibility usage
6342 for (const auto& track : mActiveTracks) {
6343 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6344 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6345 latencyMode = AUDIO_LATENCY_MODE_LOW;
6346 break;
6347 }
6348 }
6349 }
6350
6351 if (latencyMode != mSetLatencyMode) {
6352 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6353 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6354 __func__, mId, toString(latencyMode).c_str(), status);
6355 if (status == NO_ERROR) {
6356 mSetLatencyMode = latencyMode;
6357 }
6358 }
6359}
6360
Andy Hung4b17e882023-07-07 13:47:37 -07006361void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006362
6363 if (mOutput == nullptr || mOutput->stream == nullptr) {
6364 return;
6365 }
6366 std::vector<audio_latency_mode_t> latencyModes;
6367 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6368 if (status != NO_ERROR) {
6369 latencyModes.clear();
6370 }
6371 if (latencyModes != mSupportedLatencyModes) {
6372 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6373 __func__, mId, status, toString(latencyModes).c_str());
6374 mSupportedLatencyModes.swap(latencyModes);
6375 sendHalLatencyModesChangedEvent_l();
6376 }
6377}
6378
Andy Hung4b17e882023-07-07 13:47:37 -07006379status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006380 std::vector<audio_latency_mode_t>* modes) {
6381 if (modes == nullptr) {
6382 return BAD_VALUE;
6383 }
6384 Mutex::Autolock _l(mLock);
6385 *modes = mSupportedLatencyModes;
6386 return NO_ERROR;
6387}
6388
Andy Hung4b17e882023-07-07 13:47:37 -07006389void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006390 std::vector<audio_latency_mode_t> modes) {
6391 Mutex::Autolock _l(mLock);
6392 if (modes != mSupportedLatencyModes) {
6393 ALOGD("%s: thread(%d) supported latency modes: %s",
6394 __func__, mId, toString(modes).c_str());
6395 mSupportedLatencyModes.swap(modes);
6396 sendHalLatencyModesChangedEvent_l();
6397 }
6398}
6399
Andy Hung4b17e882023-07-07 13:47:37 -07006400status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006401 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6402 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6403 return INVALID_OPERATION;
6404 }
6405 mBluetoothLatencyModesEnabled.store(enabled);
6406 return NO_ERROR;
6407}
6408
Eric Laurent81784c32012-11-19 14:55:58 -08006409// ----------------------------------------------------------------------------
6410
Andy Hung4b17e882023-07-07 13:47:37 -07006411/* static */
6412sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
6413 const sp<AudioFlinger>& audioFlinger,
6414 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6415 const audio_offload_info_t& offloadInfo) {
6416 return sp<DirectOutputThread>::make(
6417 audioFlinger, output, id, systemReady, offloadInfo);
6418}
6419
6420DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006421 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6422 const audio_offload_info_t& offloadInfo)
jiabinc52b1ff2019-10-31 17:20:42 -07006423 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006424 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006425{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006426 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006427}
6428
Andy Hung4b17e882023-07-07 13:47:37 -07006429DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006430{
6431}
6432
Andy Hung4b17e882023-07-07 13:47:37 -07006433void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006434{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006435 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006436 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6437 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6438}
6439
Andy Hung4b17e882023-07-07 13:47:37 -07006440void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006441{
6442 Mutex::Autolock _l(mLock);
6443 if (mMasterBalance != balance) {
6444 mMasterBalance.store(balance);
6445 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6446 broadcast_l();
6447 }
6448}
6449
Andy Hung4b17e882023-07-07 13:47:37 -07006450void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006451{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006452 float left, right;
6453
Andy Hung333ab962019-05-28 20:23:35 -07006454 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006455 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006456
6457 const size_t framesReleased = proxy->framesReleased();
6458 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6459 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6460
6461 ALOGV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6462 __func__, framesReleased, (long long)frames, (long long)time);
6463
6464 const int64_t volumeShaperFrames =
6465 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6466 const auto [shaperVolume, shaperActive] =
6467 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006468 mVolumeShaperActive = shaperActive;
6469
Vlad Popae2f5aef2022-07-25 16:00:20 +02006470 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6471 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6472 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6473
6474 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6475
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006476 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006477 left = right = 0;
6478 } else {
6479 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006480 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006481
Glenn Kastenc56f3422014-03-21 17:53:17 -07006482 if (left > GAIN_FLOAT_UNITY) {
6483 left = GAIN_FLOAT_UNITY;
6484 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006485 if (right > GAIN_FLOAT_UNITY) {
6486 right = GAIN_FLOAT_UNITY;
6487 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006488 left *= v;
6489 right *= v;
6490 if (mAudioFlinger->getMode() != AUDIO_MODE_IN_COMMUNICATION
6491 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6492 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6493 right *= mMasterBalanceRight;
6494 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006495 }
6496
Vlad Popae8d99472022-06-30 16:02:48 +02006497 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
6498 /*muteState=*/{mMasterMute,
6499 mStreamTypes[track->streamType()].volume == 0.f,
6500 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006501 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006502 clientVolumeMute,
6503 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006504
Eric Laurentbfb1b832013-01-07 09:53:42 -08006505 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006506 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006507 if (left != mLeftVolFloat || right != mRightVolFloat) {
6508 mLeftVolFloat = left;
6509 mRightVolFloat = right;
6510
Eric Laurentbfb1b832013-01-07 09:53:42 -08006511 // Delegate volume control to effect in track effect chain if needed
6512 // only one effect chain can be present on DirectOutputThread, so if
6513 // there is one, the track is connected to it
6514 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006515 // if effect chain exists, volume is handled by it.
6516 // Convert volumes from float to 8.24
6517 uint32_t vl = (uint32_t)(left * (1 << 24));
6518 uint32_t vr = (uint32_t)(right * (1 << 24));
6519 // Direct/Offload effect chains set output volume in setVolume_l().
6520 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6521 } else {
6522 // otherwise we directly set the volume.
6523 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006524 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006525 }
6526 }
6527}
6528
Andy Hung4b17e882023-07-07 13:47:37 -07006529void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006530{
Andy Hung11e74242023-06-26 19:20:57 -07006531 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6532 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006533
Eric Laurent0f0631e2015-07-06 18:01:25 -07006534 if (previousTrack != 0 && latestTrack != 0) {
6535 if (mType == DIRECT) {
6536 if (previousTrack.get() != latestTrack.get()) {
6537 mFlushPending = true;
6538 }
6539 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006540 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6541 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006542 mFlushPending = true;
6543 }
6544 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006545 } else if (previousTrack == 0) {
6546 // there could be an old track added back during track transition for direct
6547 // output, so always issues flush to flush data of the previous track if it
6548 // was already destroyed with HAL paused, then flush can resume the playback
6549 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006550 }
6551 PlaybackThread::onAddNewTrack_l();
6552}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006553
Andy Hung4b17e882023-07-07 13:47:37 -07006554PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006555 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006556)
6557{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006558 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006559 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006560 bool doHwPause = false;
6561 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006562
6563 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006564 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006565 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006566 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006567 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006568 continue;
6569 }
6570
Andy Hung11e74242023-06-26 19:20:57 -07006571 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006572#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006573 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006574#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006575 // Only consider last track started for volume and mixer state control.
6576 // In theory an older track could underrun and restart after the new one starts
6577 // but as we only care about the transition phase between two tracks on a
6578 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006579 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006580 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006581
Kuowei Li23666472021-01-20 10:23:25 +08006582 if (track->isPausePending()) {
6583 track->pauseAck();
6584 // It is possible a track might have been flushed or stopped.
6585 // Other operations such as flush pending might occur on the next prepare.
6586 if (track->isPausing()) {
6587 track->setPaused();
6588 }
6589 // Always perform pause, as an immediate flush will change
6590 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006591 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006592 doHwPause = true;
6593 mHwPaused = true;
6594 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006595 } else if (track->isFlushPending()) {
6596 track->flushAck();
6597 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006598 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006599 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006600 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006601 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006602 if (last) {
6603 mLeftVolFloat = mRightVolFloat = -1.0;
6604 if (mHwPaused) {
6605 doHwResume = true;
6606 mHwPaused = false;
6607 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006608 }
6609 }
6610
Eric Laurent81784c32012-11-19 14:55:58 -08006611 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006612 // for all its buffers to be filled before processing it.
6613 // Allow draining the buffer in case the client
6614 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006615 // hence the test on (track->retryCount() > 1).
6616 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006617 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6618 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006619 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006620
6621 // target retry count that we will use is based on the time we wait for retries.
6622 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6623 // the retry threshold is when we accept any size for PCM data. This is slightly
6624 // smaller than the retry count so we can push small bits of data without a glitch.
6625 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006626 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006627 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006628 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006629 minFrames = mNormalFrameCount;
6630 } else {
6631 minFrames = 1;
6632 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006633
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006634 const size_t framesReady = track->framesReady();
6635 const int trackId = track->id();
6636 if (ATRACE_ENABLED()) {
6637 std::string traceName("nRdy");
6638 traceName += std::to_string(trackId);
6639 ATRACE_INT(traceName.c_str(), framesReady);
6640 }
6641 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006642 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006643 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006644 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006645
Andy Hung11e74242023-06-26 19:20:57 -07006646 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6647 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006648 if (last) {
6649 // make sure processVolume_l() will apply new volume even if 0
6650 mLeftVolFloat = mRightVolFloat = -1.0;
6651 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006652 if (!mHwSupportsPause) {
6653 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006654 }
6655 }
6656
6657 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006658 processVolume_l(track, last);
6659 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006660 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006661 if (previousTrack != 0) {
6662 if (track != previousTrack.get()) {
6663 // Flush any data still being written from last track
6664 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006665 // Invalidate previous track to force a seek when resuming.
6666 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006667 }
6668 }
6669 mPreviousTrack = track;
6670
Eric Laurentd595b7c2013-04-03 17:27:56 -07006671 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006672 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006673 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006674 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006675 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006676 doHwResume = true;
6677 mHwPaused = false;
6678 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006679 }
Eric Laurent81784c32012-11-19 14:55:58 -08006680 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006681 // clear effect chain input buffer if the last active track started underruns
6682 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006683 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006684 mEffectChains[0]->clearInputBuffer();
6685 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006686 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006687 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006688 if (last && mHwPaused) {
6689 doHwResume = true;
6690 mHwPaused = false;
6691 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006692 }
6693 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6694 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006695 // We have consumed all the buffers of this track.
6696 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006697 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006698 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006699 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006700 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006701 if (presComplete) {
6702 mOutput->presentationComplete();
6703 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006704 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006705 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006706 }
Eric Laurent81784c32012-11-19 14:55:58 -08006707 if (track->isStopped()) {
6708 track->reset();
6709 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006710 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006711 }
6712 } else {
6713 // No buffers for this track. Give it a few chances to
6714 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006715 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006716 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006717 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006718 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006719 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006720 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006721 } else {
6722 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6723 tracksToRemove->add(track);
6724 // indicate to client process that the track was disabled because of
6725 // underrun; it will then automatically call start() when data is available
6726 track->disable();
6727 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6728 // unlike mixerthread, HAL can be paused for direct output
6729 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6730 "minFrames = %u, mFormat = %#x",
6731 framesReady, minFrames, mFormat);
6732 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6733 doHwPause = true;
6734 mHwPaused = true;
6735 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006736 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006737 } else if (last) {
6738 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006739 }
6740 }
6741 }
6742 }
6743
Eric Laurentd1f69b02014-12-15 14:33:13 -08006744 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006745 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006746 for (size_t i = 0; i < mTracks.size(); i++) {
6747 if (mTracks[i]->isFlushPending()) {
6748 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006749 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006750 }
6751 }
6752 }
6753
6754 // make sure the pause/flush/resume sequence is executed in the right order.
6755 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6756 // before flush and then resume HW. This can happen in case of pause/flush/resume
6757 // if resume is received before pause is executed.
6758 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006759 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006760 status_t result = mOutput->stream->pause();
6761 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006762 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006763 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006764 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006765 flushHw_l();
6766 }
6767 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006768 status_t result = mOutput->stream->resume();
6769 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006770 }
Eric Laurent81784c32012-11-19 14:55:58 -08006771 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006772 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006773
6774 return mixerStatus;
6775}
6776
Andy Hung4b17e882023-07-07 13:47:37 -07006777void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006778{
Eric Laurent81784c32012-11-19 14:55:58 -08006779 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006780 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006781 // output audio to hardware
6782 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006783 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006784 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006785 status_t status = mActiveTrack->getNextBuffer(&buffer);
6786 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006787 // no need to pad with 0 for compressed audio
6788 if (audio_has_proportional_frames(mFormat)) {
6789 memset(curBuf, 0, frameCount * mFrameSize);
6790 }
Eric Laurent81784c32012-11-19 14:55:58 -08006791 break;
6792 }
6793 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6794 frameCount -= buffer.frameCount;
6795 curBuf += buffer.frameCount * mFrameSize;
6796 mActiveTrack->releaseBuffer(&buffer);
6797 }
Andy Hung2098f272014-02-27 14:00:06 -08006798 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006799 mSleepTimeUs = 0;
6800 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006801 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006802}
6803
Andy Hung4b17e882023-07-07 13:47:37 -07006804void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006805{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006806 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006807 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006808 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006809 return;
6810 }
Andy Hung85ba3332021-04-27 17:40:26 -07006811 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6812 mSleepTimeUs = mActiveSleepTimeUs;
6813 } else {
6814 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006815 }
Andy Hung85ba3332021-04-27 17:40:26 -07006816 // Note: In S or later, we do not write zeroes for
6817 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006818}
6819
Andy Hung4b17e882023-07-07 13:47:37 -07006820void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006821{
6822 {
6823 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006824 for (size_t i = 0; i < mTracks.size(); i++) {
6825 if (mTracks[i]->isFlushPending()) {
6826 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006827 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006828 }
6829 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006830 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006831 flushHw_l();
6832 }
6833 }
6834 PlaybackThread::threadLoop_exit();
6835}
6836
6837// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07006838bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006839{
6840 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006841 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006842
6843 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6844 // after a timeout and we will enter standby then.
6845 if (mTracks.size() > 0) {
6846 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006847 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung11e74242023-06-26 19:20:57 -07006848 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006849 }
6850
Eric Laurent5cff4032015-05-26 13:49:58 -07006851 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006852}
6853
Eric Laurent10351942014-05-08 18:49:52 -07006854// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07006855bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006856 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006857{
6858 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006859 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006860
Eric Laurent10351942014-05-08 18:49:52 -07006861 AudioParameter param = AudioParameter(keyValuePair);
6862 int value;
6863 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006864 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006865 }
Eric Laurent10351942014-05-08 18:49:52 -07006866 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6867 // do not accept frame count changes if tracks are open as the track buffer
6868 // size depends on frame count and correct behavior would not be garantied
6869 // if frame count is changed after track creation
6870 if (!mTracks.isEmpty()) {
6871 status = INVALID_OPERATION;
6872 } else {
6873 reconfig = true;
6874 }
6875 }
6876 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006877 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006878 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006879 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006880 if (!mStandby) {
6881 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006882 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006883 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006884 }
Eric Laurent10351942014-05-08 18:49:52 -07006885 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006886 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006887 }
6888 if (status == NO_ERROR && reconfig) {
6889 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006890 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006891 }
6892 }
6893
Dean Wheatley68918102021-03-19 22:09:19 +11006894 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006895}
6896
Andy Hung4b17e882023-07-07 13:47:37 -07006897uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006898{
6899 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006900 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006901 time = PlaybackThread::activeSleepTimeUs();
6902 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006903 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006904 }
6905 return time;
6906}
6907
Andy Hung4b17e882023-07-07 13:47:37 -07006908uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006909{
6910 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006911 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006912 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6913 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006914 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006915 }
6916 return time;
6917}
6918
Andy Hung4b17e882023-07-07 13:47:37 -07006919uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006920{
6921 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006922 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006923 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6924 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006925 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006926 }
6927 return time;
6928}
6929
Andy Hung4b17e882023-07-07 13:47:37 -07006930void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006931{
6932 PlaybackThread::cacheParameters_l();
6933
6934 // use shorter standby delay as on normal output to release
6935 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006936 // no delay on outputs with HW A/V sync
6937 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006938 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006939 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006940 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006941 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006942 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006943 }
Eric Laurent81784c32012-11-19 14:55:58 -08006944}
6945
Andy Hung4b17e882023-07-07 13:47:37 -07006946void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07006947{
ziyangch8f194f12021-12-01 13:48:04 -08006948 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006949 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006950 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006951 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006952 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006953 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08006954 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006955}
6956
Andy Hung4b17e882023-07-07 13:47:37 -07006957int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08006958 // If a VolumeShaper is active, we must wake up periodically to update volume.
6959 const int64_t NS_PER_MS = 1000000;
6960 return mVolumeShaperActive ?
6961 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6962}
6963
Eric Laurent81784c32012-11-19 14:55:58 -08006964// ----------------------------------------------------------------------------
6965
Andy Hung4b17e882023-07-07 13:47:37 -07006966AsyncCallbackThread::AsyncCallbackThread(
6967 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006968 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006969 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006970 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006971 mDrainSequence(0),
6972 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006973{
6974}
6975
Andy Hung4b17e882023-07-07 13:47:37 -07006976void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006977{
6978 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6979}
6980
Andy Hung4b17e882023-07-07 13:47:37 -07006981bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08006982{
6983 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006984 uint32_t writeAckSequence;
6985 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006986 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006987
6988 {
6989 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006990 while (!((mWriteAckSequence & 1) ||
6991 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006992 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006993 exitPending())) {
6994 mWaitWorkCV.wait(mLock);
6995 }
6996
Eric Laurentbfb1b832013-01-07 09:53:42 -08006997 if (exitPending()) {
6998 break;
6999 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007000 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7001 mWriteAckSequence, mDrainSequence);
7002 writeAckSequence = mWriteAckSequence;
7003 mWriteAckSequence &= ~1;
7004 drainSequence = mDrainSequence;
7005 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007006 asyncError = mAsyncError;
7007 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007008 }
7009 {
Andy Hung4b17e882023-07-07 13:47:37 -07007010 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007011 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007012 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007013 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007014 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007015 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007016 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007017 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007018 if (asyncError) {
7019 playbackThread->onAsyncError();
7020 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007021 }
7022 }
7023 }
7024 return false;
7025}
7026
Andy Hung4b17e882023-07-07 13:47:37 -07007027void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007028{
7029 ALOGV("AsyncCallbackThread::exit");
7030 Mutex::Autolock _l(mLock);
7031 requestExit();
7032 mWaitWorkCV.broadcast();
7033}
7034
Andy Hung4b17e882023-07-07 13:47:37 -07007035void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007036{
7037 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007038 // bit 0 is cleared
7039 mWriteAckSequence = sequence << 1;
7040}
7041
Andy Hung4b17e882023-07-07 13:47:37 -07007042void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007043{
7044 Mutex::Autolock _l(mLock);
7045 // ignore unexpected callbacks
7046 if (mWriteAckSequence & 2) {
7047 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007048 mWaitWorkCV.signal();
7049 }
7050}
7051
Andy Hung4b17e882023-07-07 13:47:37 -07007052void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007053{
7054 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007055 // bit 0 is cleared
7056 mDrainSequence = sequence << 1;
7057}
7058
Andy Hung4b17e882023-07-07 13:47:37 -07007059void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007060{
7061 Mutex::Autolock _l(mLock);
7062 // ignore unexpected callbacks
7063 if (mDrainSequence & 2) {
7064 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007065 mWaitWorkCV.signal();
7066 }
7067}
7068
Andy Hung4b17e882023-07-07 13:47:37 -07007069void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007070{
7071 Mutex::Autolock _l(mLock);
7072 mAsyncError = true;
7073 mWaitWorkCV.signal();
7074}
7075
Eric Laurentbfb1b832013-01-07 09:53:42 -08007076
7077// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007078
7079/* static */
7080sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
7081 const sp<AudioFlinger>& audioFlinger,
7082 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7083 const audio_offload_info_t& offloadInfo) {
7084 return sp<OffloadThread>::make(audioFlinger, output, id, systemReady, offloadInfo);
7085}
7086
7087OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007088 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7089 const audio_offload_info_t& offloadInfo)
7090 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007091 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007092{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007093 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007094 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007095 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007096}
7097
Andy Hung4b17e882023-07-07 13:47:37 -07007098void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007099{
7100 if (mFlushPending || mHwPaused) {
7101 // If a flush is pending or track was paused, just discard buffered data
7102 flushHw_l();
7103 } else {
7104 mMixerStatus = MIXER_DRAIN_ALL;
7105 threadLoop_drain();
7106 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007107 if (mUseAsyncWrite) {
7108 ALOG_ASSERT(mCallbackThread != 0);
7109 mCallbackThread->exit();
7110 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007111 PlaybackThread::threadLoop_exit();
7112}
7113
Andy Hung4b17e882023-07-07 13:47:37 -07007114PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007115 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007116)
7117{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007118 size_t count = mActiveTracks.size();
7119
7120 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007121 bool doHwPause = false;
7122 bool doHwResume = false;
7123
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007124 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007125
Eric Laurentbfb1b832013-01-07 09:53:42 -08007126 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007127 for (const sp<IAfTrack>& t : mActiveTracks) {
7128 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007129#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007130 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007131#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007132 // Only consider last track started for volume and mixer state control.
7133 // In theory an older track could underrun and restart after the new one starts
7134 // but as we only care about the transition phase between two tracks on a
7135 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007136 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007137 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007138
Haynes Mathew George7844f672014-01-15 12:32:55 -08007139 if (track->isInvalid()) {
7140 ALOGW("An invalidated track shouldn't be in active list");
7141 tracksToRemove->add(track);
7142 continue;
7143 }
7144
Andy Hung11e74242023-06-26 19:20:57 -07007145 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007146 ALOGW("An idle track shouldn't be in active list");
7147 continue;
7148 }
7149
Kuowei Li23666472021-01-20 10:23:25 +08007150 if (track->isPausePending()) {
7151 track->pauseAck();
7152 // It is possible a track might have been flushed or stopped.
7153 // Other operations such as flush pending might occur on the next prepare.
7154 if (track->isPausing()) {
7155 track->setPaused();
7156 }
7157 // Always perform pause if last, as an immediate flush will change
7158 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007159 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007160 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007161 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007162 mHwPaused = true;
7163 }
7164 // If we were part way through writing the mixbuffer to
7165 // the HAL we must save this until we resume
7166 // BUG - this will be wrong if a different track is made active,
7167 // in that case we want to discard the pending data in the
7168 // mixbuffer and tell the client to present it again when the
7169 // track is resumed
7170 mPausedWriteLength = mCurrentWriteLength;
7171 mPausedBytesRemaining = mBytesRemaining;
7172 mBytesRemaining = 0; // stop writing
7173 }
7174 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007175 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007176 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007177 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007178 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007179 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007180 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007181 track->flushAck();
7182 if (last) {
7183 mFlushPending = true;
7184 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007185 } else if (track->isResumePending()){
7186 track->resumeAck();
7187 if (last) {
7188 if (mPausedBytesRemaining) {
7189 // Need to continue write that was interrupted
7190 mCurrentWriteLength = mPausedWriteLength;
7191 mBytesRemaining = mPausedBytesRemaining;
7192 mPausedBytesRemaining = 0;
7193 }
7194 if (mHwPaused) {
7195 doHwResume = true;
7196 mHwPaused = false;
7197 // threadLoop_mix() will handle the case that we need to
7198 // resume an interrupted write
7199 }
7200 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007201 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007202
Eric Laurent3df841a2016-07-15 15:15:40 -07007203 mLeftVolFloat = mRightVolFloat = -1.0;
7204
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007205 // Do not handle new data in this iteration even if track->framesReady()
7206 mixerStatus = MIXER_TRACKS_ENABLED;
7207 }
7208 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007209 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007210 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007211 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7212 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007213 if (last) {
7214 // make sure processVolume_l() will apply new volume even if 0
7215 mLeftVolFloat = mRightVolFloat = -1.0;
7216 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007217 }
7218
7219 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007220 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007221 if (previousTrack != 0) {
7222 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007223 // Flush any data still being written from last track
7224 mBytesRemaining = 0;
7225 if (mPausedBytesRemaining) {
7226 // Last track was paused so we also need to flush saved
7227 // mixbuffer state and invalidate track so that it will
7228 // re-submit that unwritten data when it is next resumed
7229 mPausedBytesRemaining = 0;
7230 // Invalidate is a bit drastic - would be more efficient
7231 // to have a flag to tell client that some of the
7232 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007233 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007234 }
7235 // flush data already sent to the DSP if changing audio session as audio
7236 // comes from a different source. Also invalidate previous track to force a
7237 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007238 if (previousTrack->sessionId() != track->sessionId()) {
7239 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007240 }
7241 }
7242 }
7243 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007244 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007245 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007246 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007247 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007248 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007249 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007250 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007251 mixerStatus = MIXER_TRACKS_READY;
7252 }
7253 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007254 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007255 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007256 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007257 // Hardware buffer can hold a large amount of audio so we must
7258 // wait for all current track's data to drain before we say
7259 // that the track is stopped.
7260 if (mBytesRemaining == 0) {
7261 // Only start draining when all data in mixbuffer
7262 // has been written
7263 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007264 track->setState(IAfTrackBase::STOPPING_2);
7265 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007266 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7267 if (last && !mStandby) {
7268 // do not modify drain sequence if we are already draining. This happens
7269 // when resuming from pause after drain.
7270 if ((mDrainSequence & 1) == 0) {
7271 mSleepTimeUs = 0;
7272 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7273 mixerStatus = MIXER_DRAIN_TRACK;
7274 mDrainSequence += 2;
7275 }
7276 if (mHwPaused) {
7277 // It is possible to move from PAUSED to STOPPING_1 without
7278 // a resume so we must ensure hardware is running
7279 doHwResume = true;
7280 mHwPaused = false;
7281 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007282 }
7283 }
Eric Laurente93cc032016-05-05 10:15:10 -07007284 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007285 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007286 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007287 }
7288 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007289 // Drain has completed or we are in standby, signal presentation complete
7290 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007291 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007292 mOutput->presentationComplete();
7293 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007294 track->reset();
7295 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007296 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007297 if (!mUseAsyncWrite) {
7298 // If we don't get explicit drain notification we must
7299 // register discontinuity regardless of whether this is
7300 // the previous (!last) or the upcoming (last) track
7301 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007302 mTimestampVerifier.discontinuity(
7303 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007304 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007305 }
7306 } else {
7307 // No buffers for this track. Give it a few chances to
7308 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007309 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007310 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007311 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007312 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007313 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007314 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007315 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7316 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007317 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007318 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007319 // it will then automatically call start() when data is available
7320 track->disable();
7321 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007322 } else if (last){
7323 mixerStatus = MIXER_TRACKS_ENABLED;
7324 }
7325 }
7326 }
7327 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007328 if (track->isReady()) { // check ready to prevent premature start.
7329 processVolume_l(track, last);
7330 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007332
Eric Laurentea0fade2013-10-04 16:23:48 -07007333 // make sure the pause/flush/resume sequence is executed in the right order.
7334 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7335 // before flush and then resume HW. This can happen in case of pause/flush/resume
7336 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007337 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007338 status_t result = mOutput->stream->pause();
7339 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007340 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007341 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007342 if (mFlushPending) {
7343 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007344 }
Eric Laurentfd477972013-10-25 18:10:40 -07007345 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007346 status_t result = mOutput->stream->resume();
7347 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007348 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007349
Eric Laurentbfb1b832013-01-07 09:53:42 -08007350 // remove all the tracks that need to be...
7351 removeTracks_l(*tracksToRemove);
7352
7353 return mixerStatus;
7354}
7355
Eric Laurentbfb1b832013-01-07 09:53:42 -08007356// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007357bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007358{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007359 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7360 mWriteAckSequence, mDrainSequence);
7361 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007362 return true;
7363 }
7364 return false;
7365}
7366
Andy Hung4b17e882023-07-07 13:47:37 -07007367bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007368{
7369 Mutex::Autolock _l(mLock);
7370 return waitingAsyncCallback_l();
7371}
7372
Andy Hung4b17e882023-07-07 13:47:37 -07007373void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007374{
Eric Laurente659ef42014-09-29 13:06:46 -07007375 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007376 // Flush anything still waiting in the mixbuffer
7377 mCurrentWriteLength = 0;
7378 mBytesRemaining = 0;
7379 mPausedWriteLength = 0;
7380 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007381 // reset bytes written count to reflect that DSP buffers are empty after flush.
7382 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007383
Eric Laurentbfb1b832013-01-07 09:53:42 -08007384 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007385 // discard any pending drain or write ack by incrementing sequence
7386 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7387 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007388 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007389 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7390 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007391 }
7392}
7393
Andy Hung4b17e882023-07-07 13:47:37 -07007394void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007395{
7396 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007397 if (PlaybackThread::invalidateTracks_l(streamType)) {
7398 mFlushPending = true;
7399 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007400}
7401
Andy Hung4b17e882023-07-07 13:47:37 -07007402void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08007403 Mutex::Autolock _l(mLock);
7404 if (PlaybackThread::invalidateTracks_l(portIds)) {
7405 mFlushPending = true;
7406 }
7407}
7408
Eric Laurentbfb1b832013-01-07 09:53:42 -08007409// ----------------------------------------------------------------------------
7410
Andy Hung4b17e882023-07-07 13:47:37 -07007411/* static */
7412sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
7413 const sp<AudioFlinger>& audioFlinger,
7414 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
7415 return sp<DuplicatingThread>::make(audioFlinger, mainThread, id, systemReady);
7416}
7417
7418DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007419 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007420 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007421 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007422 mWaitTimeMs(UINT_MAX)
7423{
7424 addOutputTrack(mainThread);
7425}
7426
Andy Hung4b17e882023-07-07 13:47:37 -07007427DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007428{
7429 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7430 mOutputTracks[i]->destroy();
7431 }
7432}
7433
Andy Hung4b17e882023-07-07 13:47:37 -07007434void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007435{
7436 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007437 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007438 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007439 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007440 if (mMixerBufferValid) {
7441 memset(mMixerBuffer, 0, mMixerBufferSize);
7442 } else {
7443 memset(mSinkBuffer, 0, mSinkBufferSize);
7444 }
Eric Laurent81784c32012-11-19 14:55:58 -08007445 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007446 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007447 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007448 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007449 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007450}
7451
Andy Hung4b17e882023-07-07 13:47:37 -07007452void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007453{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007454 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007455 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007456 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007457 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007458 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007459 }
7460 } else if (mBytesWritten != 0) {
7461 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7462 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007463 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007464 } else {
7465 // flush remaining overflow buffers in output tracks
7466 writeFrames = 0;
7467 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007468 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007469 }
7470}
7471
Andy Hung4b17e882023-07-07 13:47:37 -07007472ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007473{
7474 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007475 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7476
7477 // Consider the first OutputTrack for timestamp and frame counting.
7478
7479 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7480 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7481 // we always claim success.
7482 if (i == 0) {
7483 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7484 ALOGD_IF(correction != 0 && writeFrames != 0,
7485 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7486 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7487 mFramesWritten -= correction;
7488 }
7489
7490 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007491 }
Andy Hungcf10d742020-04-28 15:38:24 -07007492 if (mStandby) {
7493 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007494 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007495 mStandby = false;
7496 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007497 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007498}
7499
Andy Hung4b17e882023-07-07 13:47:37 -07007500void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007501{
7502 // DuplicatingThread implements standby by stopping all tracks
7503 for (size_t i = 0; i < outputTracks.size(); i++) {
7504 outputTracks[i]->stop();
7505 }
7506}
7507
Andy Hung4b17e882023-07-07 13:47:37 -07007508void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007509{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007510 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007511
7512 std::stringstream ss;
7513 const size_t numTracks = mOutputTracks.size();
7514 ss << " " << numTracks << " OutputTracks";
7515 if (numTracks > 0) {
7516 ss << ":";
7517 for (const auto &track : mOutputTracks) {
Andy Hungfafbebc2023-06-23 19:27:19 -07007518 // TODO(b/288339104) type
Andy Hung0c1e11e2023-07-06 20:56:16 -07007519 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007520 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007521 if (thread.get() != nullptr) {
7522 ss << thread.get() << ", " << thread->id();
7523 } else {
7524 ss << "null";
7525 }
7526 ss << ")";
7527 }
7528 }
7529 ss << "\n";
7530 std::string result = ss.str();
7531 write(fd, result.c_str(), result.size());
7532}
7533
Andy Hung4b17e882023-07-07 13:47:37 -07007534void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007535{
7536 outputTracks = mOutputTracks;
7537}
7538
Andy Hung4b17e882023-07-07 13:47:37 -07007539void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007540{
7541 outputTracks.clear();
7542}
7543
Andy Hung4b17e882023-07-07 13:47:37 -07007544void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007545{
7546 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007547 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7548 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7549 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7550 const size_t frameCount =
7551 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7552 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7553 // from different OutputTracks and their associated MixerThreads (e.g. one may
7554 // nearly empty and the other may be dropping data).
7555
Svet Ganov33761132021-05-13 22:51:08 +00007556 // TODO b/182392769: use attribution source util, move to server edge
7557 AttributionSourceState attributionSource = AttributionSourceState();
7558 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007559 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007560 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007561 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007562 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007563 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007564 this,
7565 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007566 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007567 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007568 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007569 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007570 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7571 if (status != NO_ERROR) {
7572 ALOGE("addOutputTrack() initCheck failed %d", status);
7573 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007574 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007575 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7576 mOutputTracks.add(outputTrack);
7577 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7578 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007579}
7580
Andy Hung4b17e882023-07-07 13:47:37 -07007581void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007582{
7583 Mutex::Autolock _l(mLock);
7584 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7585 if (mOutputTracks[i]->thread() == thread) {
7586 mOutputTracks[i]->destroy();
7587 mOutputTracks.removeAt(i);
7588 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007589 if (thread->getOutput() == mOutput) {
7590 mOutput = NULL;
7591 }
Eric Laurent81784c32012-11-19 14:55:58 -08007592 return;
7593 }
7594 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007595 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007596}
7597
7598// caller must hold mLock
Andy Hung4b17e882023-07-07 13:47:37 -07007599void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007600{
7601 mWaitTimeMs = UINT_MAX;
7602 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hungfafbebc2023-06-23 19:27:19 -07007603 // TODO(b/288339104) type
Andy Hung0c1e11e2023-07-06 20:56:16 -07007604 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007605 if (strong != 0) {
7606 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7607 if (waitTimeMs < mWaitTimeMs) {
7608 mWaitTimeMs = waitTimeMs;
7609 }
7610 }
7611 }
7612}
7613
Andy Hung4b17e882023-07-07 13:47:37 -07007614bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007615{
7616 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007617 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007618 if (thread == 0) {
7619 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7620 outputTracks[i].get());
7621 return false;
7622 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007623 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007624 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007625 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007626 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7627 thread.get());
7628 return false;
7629 }
7630 }
7631 return true;
7632}
7633
Andy Hung4b17e882023-07-07 13:47:37 -07007634void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007635 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007636{
Kevin Rocard12381092018-04-11 09:19:59 -07007637 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7638 outputTrack->setMetadatas(metadata.tracks);
7639 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007640}
7641
Andy Hung4b17e882023-07-07 13:47:37 -07007642uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007643{
7644 return (mWaitTimeMs * 1000) / 2;
7645}
7646
Andy Hung4b17e882023-07-07 13:47:37 -07007647void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007648{
7649 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7650 updateWaitTime_l();
7651
7652 MixerThread::cacheParameters_l();
7653}
7654
Eric Laurentb3f315a2021-07-13 15:09:05 +02007655// ----------------------------------------------------------------------------
7656
Andy Hung4b17e882023-07-07 13:47:37 -07007657/* static */
7658sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
7659 const sp<AudioFlinger>& audioFlinger,
7660 AudioStreamOut* output,
7661 audio_io_handle_t id,
7662 bool systemReady,
7663 audio_config_base_t* mixerConfig) {
7664 return sp<SpatializerThread>::make(audioFlinger, output, id, systemReady, mixerConfig);
7665}
7666
7667SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007668 AudioStreamOut* output,
7669 audio_io_handle_t id,
7670 bool systemReady,
7671 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007672 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007673{
7674}
7675
Andy Hung4b17e882023-07-07 13:47:37 -07007676void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007677 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007678
Andy Hung41ccf7f2022-12-14 14:25:49 -08007679 const pid_t tid = getTid();
7680 if (tid == -1) {
7681 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7682 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7683 } else {
7684 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7685 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007686 stream()->setHalThreadPriority(priorityBoost);
7687 }
7688 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007689}
7690
Andy Hung4b17e882023-07-07 13:47:37 -07007691void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007692 // if mSupportedLatencyModes is empty, the HAL stream does not support
7693 // latency mode control and we can exit.
7694 if (mSupportedLatencyModes.empty()) {
7695 return;
7696 }
7697 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7698 if (mSupportedLatencyModes.size() == 1) {
7699 // If the HAL only support one latency mode currently, confirm the choice
7700 latencyMode = mSupportedLatencyModes[0];
7701 } else if (mSupportedLatencyModes.size() > 1) {
7702 // Request low latency if:
7703 // - The low latency mode is requested by the spatializer controller
7704 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7705 // AND
7706 // - At least one active track is spatialized
7707 bool hasSpatializedActiveTrack = false;
7708 for (const auto& track : mActiveTracks) {
7709 if (track->isSpatialized()) {
7710 hasSpatializedActiveTrack = true;
7711 break;
7712 }
7713 }
7714 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7715 latencyMode = AUDIO_LATENCY_MODE_LOW;
7716 }
7717 }
7718
7719 if (latencyMode != mSetLatencyMode) {
7720 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007721 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7722 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007723 if (status == NO_ERROR) {
7724 mSetLatencyMode = latencyMode;
7725 }
7726 }
7727}
7728
Andy Hung4b17e882023-07-07 13:47:37 -07007729status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007730 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7731 return BAD_VALUE;
7732 }
7733 Mutex::Autolock _l(mLock);
7734 mRequestedLatencyMode = mode;
7735 return NO_ERROR;
7736}
7737
Andy Hung4b17e882023-07-07 13:47:37 -07007738void SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007739{
7740 bool hasVirtualizer = false;
7741 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007742 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007743 {
7744 Mutex::Autolock _l(mLock);
Andy Hung116bc262023-06-20 18:56:17 -07007745 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007746 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007747 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007748 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7749 }
7750
7751 finalDownMixer = mFinalDownMixer;
7752 mFinalDownMixer.clear();
7753 }
7754
7755 if (hasVirtualizer) {
7756 if (finalDownMixer != nullptr) {
7757 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007758 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007759 }
7760 finalDownMixer.clear();
7761 } else if (!hasDownMixer) {
7762 std::vector<effect_descriptor_t> descriptors;
7763 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7764 EFFECT_UIID_DOWNMIX, &descriptors);
7765 if (status != NO_ERROR) {
7766 return;
7767 }
7768 ALOG_ASSERT(!descriptors.empty(),
7769 "%s getDescriptors() returned no error but empty list", __func__);
7770
7771 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7772 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007773 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007774
7775 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7776 ALOGW("%s error creating downmixer %d", __func__, status);
7777 finalDownMixer.clear();
7778 } else {
7779 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007780 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007781 }
7782 }
7783
7784 {
7785 Mutex::Autolock _l(mLock);
7786 mFinalDownMixer = finalDownMixer;
7787 }
7788}
7789
Eric Laurent81784c32012-11-19 14:55:58 -08007790// ----------------------------------------------------------------------------
7791// Record
7792// ----------------------------------------------------------------------------
7793
Andy Hung0c1e11e2023-07-06 20:56:16 -07007794sp<IAfRecordThread> IAfRecordThread::create(const sp<AudioFlinger>& audioFlinger,
7795 AudioStreamIn* input,
7796 audio_io_handle_t id,
7797 bool systemReady) {
Andy Hung4b17e882023-07-07 13:47:37 -07007798 return sp<RecordThread>::make(audioFlinger, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07007799}
7800
Andy Hung4b17e882023-07-07 13:47:37 -07007801RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent81784c32012-11-19 14:55:58 -08007802 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007803 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007804 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007805 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007806 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007807 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007808 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007809 mActiveTracks(&this->mLocalLog),
7810 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007811 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007812 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007813 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7814 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007815 // mFastCapture below
7816 , mFastCaptureFutex(0)
7817 // mInputSource
7818 // mPipeSink
7819 // mPipeSource
7820 , mPipeFramesP2(0)
7821 // mPipeMemory
7822 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007823 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007824 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007825{
Glenn Kastend7dca052015-03-05 16:05:54 -08007826 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7827 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007828
George Burgess IVa8f90c12020-05-14 11:27:19 -07007829 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007830 mIsMsdDevice = strcmp(
7831 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7832 }
7833
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007834 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007835
Andy Hungc8fddf32018-08-08 18:32:37 -07007836 // TODO: We may also match on address as well as device type for
7837 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007838 // TODO: This property should be ensure that only contains one single device type.
7839 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7840 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007841 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7842 : AUDIO_DEVICE_NONE));
7843
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007844 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007845 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007846 size_t numCounterOffers = 0;
7847 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007848#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007849 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007850#else
7851 (void)
7852#endif
7853 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007854 ALOG_ASSERT(index == 0);
7855
7856 // initialize fast capture depending on configuration
7857 bool initFastCapture;
7858 switch (kUseFastCapture) {
7859 case FastCapture_Never:
7860 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007861 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007862 break;
7863 case FastCapture_Always:
7864 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007865 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007866 break;
7867 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007868 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7869 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7870 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7871 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7872 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007873 break;
7874 // case FastCapture_Dynamic:
7875 }
7876
7877 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007878 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007879 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007880 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7881 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007882 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007883 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007884 const sp<MemoryDealer> roHeap(readOnlyHeap());
7885 sp<IMemory> pipeMemory;
7886 if ((roHeap == 0) ||
7887 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007888 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007889 ALOGE("not enough memory for pipe buffer size=%zu; "
7890 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7891 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7892 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007893 goto failed;
7894 }
7895 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7896 memset(pipeBuffer, 0, pipeSize);
7897 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007898 const NBAIO_Format offersFast[1] = {format};
7899 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007900 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007901 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007902 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007903 mPipeSink = pipe;
7904 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007905 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007906 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007907 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007908 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007909 mPipeSource = pipeReader;
7910 mPipeFramesP2 = pipeFramesP2;
7911 mPipeMemory = pipeMemory;
7912
7913 // create fast capture
7914 mFastCapture = new FastCapture();
7915 FastCaptureStateQueue *sq = mFastCapture->sq();
7916#ifdef STATE_QUEUE_DUMP
7917 // FIXME
7918#endif
7919 FastCaptureState *state = sq->begin();
7920 state->mCblk = NULL;
7921 state->mInputSource = mInputSource.get();
7922 state->mInputSourceGen++;
7923 state->mPipeSink = pipe;
7924 state->mPipeSinkGen++;
7925 state->mFrameCount = mFrameCount;
7926 state->mCommand = FastCaptureState::COLD_IDLE;
7927 // already done in constructor initialization list
7928 //mFastCaptureFutex = 0;
7929 state->mColdFutexAddr = &mFastCaptureFutex;
7930 state->mColdGen++;
7931 state->mDumpState = &mFastCaptureDumpState;
7932#ifdef TEE_SINK
7933 // FIXME
7934#endif
7935 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7936 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7937 sq->end();
7938 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7939
7940 // start the fast capture
7941 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7942 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007943 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007944 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007945#ifdef AUDIO_WATCHDOG
7946 // FIXME
7947#endif
7948
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007949 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007950 }
Andy Hung8946a282018-04-19 20:04:56 -07007951#ifdef TEE_SINK
7952 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7953 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7954#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007955failed: ;
7956
7957 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007958}
7959
Andy Hung4b17e882023-07-07 13:47:37 -07007960RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007961{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007962 if (mFastCapture != 0) {
7963 FastCaptureStateQueue *sq = mFastCapture->sq();
7964 FastCaptureState *state = sq->begin();
7965 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7966 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7967 if (old == -1) {
7968 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7969 }
7970 }
7971 state->mCommand = FastCaptureState::EXIT;
7972 sq->end();
7973 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7974 mFastCapture->join();
7975 mFastCapture.clear();
7976 }
7977 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007978 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007979 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007980}
7981
Andy Hung4b17e882023-07-07 13:47:37 -07007982void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08007983{
Glenn Kastend7dca052015-03-05 16:05:54 -08007984 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007985}
7986
Andy Hung4b17e882023-07-07 13:47:37 -07007987void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08007988{
7989 ALOGV(" preExit()");
7990 Mutex::Autolock _l(mLock);
7991 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07007992 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08007993 track->invalidate();
7994 }
7995 mActiveTracks.clear();
7996 mStartStopCond.broadcast();
7997}
7998
Andy Hung4b17e882023-07-07 13:47:37 -07007999bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008000{
Eric Laurent81784c32012-11-19 14:55:58 -08008001 nsecs_t lastWarning = 0;
8002
8003 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008004
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008005reacquire_wakelock:
Andy Hung11e74242023-06-26 19:20:57 -07008006 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008007 {
8008 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07008009 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008010 }
8011
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008012 // used to request a deferred sleep, to be executed later while mutex is unlocked
8013 uint32_t sleepUs = 0;
8014
Andy Hung446f4df2019-02-21 12:26:41 -08008015 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8016
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008017 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008018 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008019 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008020
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008021 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008022 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008023
Glenn Kasten735f45f2014-08-18 15:51:59 -07008024 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008025 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008026
Glenn Kasten735f45f2014-08-18 15:51:59 -07008027 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008028 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008029
Eric Laurent33403f02020-05-29 18:35:06 -07008030 bool silenceFastCapture = false;
8031
Eric Laurent81784c32012-11-19 14:55:58 -08008032 { // scope for mLock
8033 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08008034
Eric Laurent021cf962014-05-13 10:18:14 -07008035 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008036
Eric Laurent000a4192014-01-29 15:17:32 -08008037 // check exitPending here because checkForNewParameters_l() and
8038 // checkForNewParameters_l() can temporarily release mLock
8039 if (exitPending()) {
8040 break;
8041 }
8042
Eric Laurent5c25d562016-07-13 17:17:45 -07008043 // sleep with mutex unlocked
8044 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008045 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07008046 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
8047 ATRACE_END();
8048 sleepUs = 0;
8049 continue;
8050 }
8051
Glenn Kasten2b806402013-11-20 16:37:38 -08008052 // if no active track(s), then standby and release wakelock
8053 size_t size = mActiveTracks.size();
8054 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008055 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008056 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008057 releaseWakeLock_l();
8058 ALOGV("RecordThread: loop stopping");
8059 // go to sleep
8060 mWaitWorkCV.wait(mLock);
8061 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008062 goto reacquire_wakelock;
8063 }
8064
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008065 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008066 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008067 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008068
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008069 activeTrack = mActiveTracks[i];
8070 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008071 if (activeTrack->isFastTrack()) {
8072 ALOG_ASSERT(fastTrackToRemove == 0);
8073 fastTrackToRemove = activeTrack;
8074 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008075 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008076 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008077 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008078 continue;
8079 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008080
Andy Hung11e74242023-06-26 19:20:57 -07008081 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008082 switch (activeTrackState) {
8083
Andy Hung11e74242023-06-26 19:20:57 -07008084 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008085 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008086 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008087 doBroadcast = true;
8088 size--;
8089 continue;
8090
Andy Hung11e74242023-06-26 19:20:57 -07008091 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008092 sleepUs = 10000;
8093 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008094 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008095 continue;
8096
Andy Hung11e74242023-06-26 19:20:57 -07008097 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008098 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008099 if (mStandby) {
8100 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008101 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008102 mStandby = false;
8103 }
Andy Hung11e74242023-06-26 19:20:57 -07008104 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008105 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008106 break;
8107
Andy Hung11e74242023-06-26 19:20:57 -07008108 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008109 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008110 break;
8111
Andy Hung11e74242023-06-26 19:20:57 -07008112 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8113 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8114 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008115 default:
Andy Hungce685402018-10-05 17:23:27 -07008116 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8117 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008118 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008119
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008120 if (activeTrack->isFastTrack()) {
8121 ALOG_ASSERT(!mFastTrackAvail);
8122 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008123 // if the active fast track is silenced either:
8124 // 1) silence the whole capture from fast capture buffer if this is
8125 // the only active track
8126 // 2) invalidate this track: this will cause the client to reconnect and possibly
8127 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008128 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008129 if (activeTrack->isSilenced()) {
8130 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008131 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008132 } else {
8133 silenceFastCapture = true;
8134 }
8135 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008136 // Invalidate fast tracks if access to audio history is required as this is not
8137 // possible with fast tracks. Once the fast track has been invalidated, no new
8138 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8139 if (mMaxSharedAudioHistoryMs != 0) {
8140 invalidate = true;
8141 }
8142 if (invalidate) {
8143 activeTrack->invalidate();
8144 ALOG_ASSERT(fastTrackToRemove == 0);
8145 fastTrackToRemove = activeTrack;
8146 removeTrack_l(activeTrack);
8147 mActiveTracks.remove(activeTrack);
8148 size--;
8149 continue;
8150 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008151 fastTrack = activeTrack;
8152 }
Eric Laurent33403f02020-05-29 18:35:06 -07008153
8154 activeTracks.add(activeTrack);
8155 i++;
8156
Glenn Kasten9e982352013-08-14 14:39:50 -07008157 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008158
Andy Hungdae27702016-10-31 14:01:16 -07008159 mActiveTracks.updatePowerState(this);
8160
Kevin Rocard069c2712018-03-29 19:09:14 -07008161 updateMetadata_l();
8162
Eric Laurent5c25d562016-07-13 17:17:45 -07008163 if (allStopped) {
8164 standbyIfNotAlreadyInStandby();
8165 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008166 if (doBroadcast) {
8167 mStartStopCond.broadcast();
8168 }
8169
8170 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008171 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008172 if (sleepUs == 0) {
8173 sleepUs = kRecordThreadSleepUs;
8174 }
8175 continue;
8176 }
8177 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008178
Eric Laurent81784c32012-11-19 14:55:58 -08008179 lockEffectChains_l(effectChains);
8180 }
8181
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008182 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008183
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008184 size_t size = effectChains.size();
8185 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008186 // thread mutex is not locked, but effect chain is locked
8187 effectChains[i]->process_l();
8188 }
8189
Glenn Kasten735f45f2014-08-18 15:51:59 -07008190 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008191 if (mFastCapture != 0) {
8192 FastCaptureStateQueue *sq = mFastCapture->sq();
8193 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008194 bool didModify = false;
8195 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008196 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8197 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8198 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8199 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8200 if (old == -1) {
8201 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8202 }
8203 }
8204 state->mCommand = FastCaptureState::READ_WRITE;
8205#if 0 // FIXME
8206 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008207 FastThreadDumpState::kSamplingNforLowRamDevice :
8208 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008209#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008210 didModify = true;
8211 }
8212 audio_track_cblk_t *cblkOld = state->mCblk;
8213 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8214 if (cblkNew != cblkOld) {
8215 state->mCblk = cblkNew;
8216 // block until acked if removing a fast track
8217 if (cblkOld != NULL) {
8218 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8219 }
8220 didModify = true;
8221 }
jiabin01c8f562018-07-19 17:47:28 -07008222 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8223 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8224 if (state->mFastPatchRecordBufferProvider != abp) {
8225 state->mFastPatchRecordBufferProvider = abp;
8226 state->mFastPatchRecordFormat = fastTrack == 0 ?
8227 AUDIO_FORMAT_INVALID : fastTrack->format();
8228 didModify = true;
8229 }
Eric Laurent33403f02020-05-29 18:35:06 -07008230 if (state->mSilenceCapture != silenceFastCapture) {
8231 state->mSilenceCapture = silenceFastCapture;
8232 didModify = true;
8233 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008234 sq->end(didModify);
8235 if (didModify) {
8236 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008237#if 0
8238 if (kUseFastCapture == FastCapture_Dynamic) {
8239 mNormalSource = mPipeSource;
8240 }
8241#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008242 }
8243 }
8244
Glenn Kasten735f45f2014-08-18 15:51:59 -07008245 // now run the fast track destructor with thread mutex unlocked
8246 fastTrackToRemove.clear();
8247
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008248 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8249 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8250 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8251 // If destination is non-contiguous, first read past the nominal end of buffer, then
8252 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008253
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008254 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008255 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008256 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008257
8258 // If an NBAIO source is present, use it to read the normal capture's data
8259 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008260 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008261
8262 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8263 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8264 // we immediately retry the read() to get data and prevent another overflow.
8265 for (int retries = 0; retries <= 2; ++retries) {
8266 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8267 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8268 framesToRead);
8269 if (framesRead != OVERRUN) break;
8270 }
8271
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008272 const ssize_t availableToRead = mPipeSource->availableToRead();
8273 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008274 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008275 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008276 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8277 "more frames to read than fifo size, %zd > %zu",
8278 availableToRead, mPipeFramesP2);
8279 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8280 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8281 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8282 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008283 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8284 }
8285 if (framesRead < 0) {
8286 status_t status = (status_t) framesRead;
8287 switch (status) {
8288 case OVERRUN:
8289 ALOGW("overrun on read from pipe");
8290 framesRead = 0;
8291 break;
8292 case NEGOTIATE:
8293 ALOGE("re-negotiation is needed");
8294 framesRead = -1; // Will cause an attempt to recover.
8295 break;
8296 default:
8297 ALOGE("unknown error %d on read from pipe", status);
8298 break;
8299 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008300 }
8301 // otherwise use the HAL / AudioStreamIn directly
8302 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008303 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008304 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008305 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008306 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008307 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008308 if (result < 0) {
8309 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008310 } else {
8311 framesRead = bytesRead / mFrameSize;
8312 }
8313 }
8314
Andy Hung446f4df2019-02-21 12:26:41 -08008315 const int64_t lastIoEndNs = systemTime(); // end IO timing
8316
Andy Hung3f0c9022016-01-15 17:49:46 -08008317 // Update server timestamp with server stats
8318 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008319 if (framesRead >= 0) {
8320 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8321 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8322 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008323
8324 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008325 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008326 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008327 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008328 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8329 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8330 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008331 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008332 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8333
8334 mTimestampVerifier.add(position, time, mSampleRate);
8335
8336 // Correct timestamps
8337 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008338 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008339 id(), (long long)time, (long long)position);
8340 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8341 position = correctedTimestamp.mFrames;
8342 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008343 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008344 id(), (long long)time, (long long)position);
8345 }
8346
Andy Hung3f0c9022016-01-15 17:49:46 -08008347 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8348 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8349 // Note: In general record buffers should tend to be empty in
8350 // a properly running pipeline.
8351 //
8352 // Also, it is not advantageous to call get_presentation_position during the read
8353 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008354 } else {
8355 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008356 }
8357 }
Andy Hunge6c37112019-02-26 17:38:10 -08008358
8359 // From the timestamp, input read latency is negative output write latency.
8360 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008361 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008362 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8363 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8364 mLatencyMs.add(latencyMs);
8365 }
8366
Andy Hung3f0c9022016-01-15 17:49:46 -08008367 // Use this to track timestamp information
8368 // ALOGD("%s", mTimestamp.toString().c_str());
8369
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008370 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008371 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008372 // Force input into standby so that it tries to recover at next read attempt
8373 inputStandBy();
8374 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008375 }
8376 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008377 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008378 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008379 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008380 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008381
Andy Hung8946a282018-04-19 20:04:56 -07008382#ifdef TEE_SINK
8383 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8384#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008385 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008386 {
8387 size_t part1 = mRsmpInFramesP2 - rear;
8388 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008389 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008390 (framesRead - part1) * mFrameSize);
8391 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008392 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008393 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008394
8395 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008396
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008397 // loop over each active track
8398 for (size_t i = 0; i < size; i++) {
8399 activeTrack = activeTracks[i];
8400
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008401 // skip fast tracks, as those are handled directly by FastCapture
8402 if (activeTrack->isFastTrack()) {
8403 continue;
8404 }
8405
Andy Hung73c02e42015-03-29 01:13:58 -07008406 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008407 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8408
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008409 enum {
8410 OVERRUN_UNKNOWN,
8411 OVERRUN_TRUE,
8412 OVERRUN_FALSE
8413 } overrun = OVERRUN_UNKNOWN;
8414
8415 // loop over getNextBuffer to handle circular sink
8416 for (;;) {
8417
Andy Hung11e74242023-06-26 19:20:57 -07008418 activeTrack->sinkBuffer().frameCount = ~0;
8419 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8420 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008421 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8422
Andy Hung73c02e42015-03-29 01:13:58 -07008423 // check available frames and handle overrun conditions
8424 // if the record track isn't draining fast enough.
8425 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008426 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008427 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008428 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008429 overrun = OVERRUN_TRUE;
8430 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008431 if (framesOut == 0 || framesIn == 0) {
8432 break;
8433 }
8434
Andy Hung6770c6f2015-04-07 13:43:36 -07008435 // Don't allow framesOut to be larger than what is possible with resampling
8436 // from framesIn.
8437 // This isn't strictly necessary but helps limit buffer resizing in
8438 // RecordBufferConverter. TODO: remove when no longer needed.
8439 framesOut = min(framesOut,
8440 destinationFramesPossible(
Andy Hung11e74242023-06-26 19:20:57 -07008441 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008442
8443 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008444 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008445 // straight from RecordThread buffer to RecordTrack buffer.
8446 AudioBufferProvider::Buffer buffer;
8447 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008448 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008449 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008450 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008451 ALOGV_IF(buffer.frameCount != framesOut,
8452 "%s() read less than expected (%zu vs %zu)",
8453 __func__, buffer.frameCount, framesOut);
8454 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008455 memcpy(activeTrack->sinkBuffer().raw,
8456 buffer.raw, buffer.frameCount * mFrameSize);
8457 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008458 } else {
8459 framesOut = 0;
8460 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008461 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008462 }
8463 } else {
8464 // process frames from the RecordThread buffer provider to the RecordTrack
8465 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008466 framesOut = activeTrack->recordBufferConverter()->convert(
8467 activeTrack->sinkBuffer().raw,
8468 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008469 framesOut);
8470 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471
8472 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8473 overrun = OVERRUN_FALSE;
8474 }
8475
Andy Hung93bb5732023-05-04 21:16:34 -07008476 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8477 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008478 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008479 if (framesToDrop == 0) {
8480 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008481 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008482 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008483 // Sanitize before releasing if the track has no access to the source data
8484 // An idle UID receives silence from non virtual devices until active
8485 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008486 memset(activeTrack->sinkBuffer().raw,
8487 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008488 }
Andy Hung11e74242023-06-26 19:20:57 -07008489 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008490 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008491 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008492 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008493 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008494 }
8495 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008496
8497 switch (overrun) {
8498 case OVERRUN_TRUE:
8499 // client isn't retrieving buffers fast enough
8500 if (!activeTrack->setOverflow()) {
8501 nsecs_t now = systemTime();
8502 // FIXME should lastWarning per track?
8503 if ((now - lastWarning) > kWarningThrottleNs) {
8504 ALOGW("RecordThread: buffer overflow");
8505 lastWarning = now;
8506 }
8507 }
8508 break;
8509 case OVERRUN_FALSE:
8510 activeTrack->clearOverflow();
8511 break;
8512 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008513 break;
8514 }
8515
Andy Hung3f0c9022016-01-15 17:49:46 -08008516 // update frame information and push timestamp out
8517 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008518 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008519 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8520 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008521 }
8522
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008523unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008524 // enable changes in effect chain
8525 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008526 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008527 if (audio_has_proportional_frames(mFormat)
8528 && loopCount == lastLoopCountRead + 1) {
8529 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8530 const double jitterMs =
8531 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8532 {framesRead, readPeriodNs},
8533 {0, 0} /* lastTimestamp */, mSampleRate);
8534 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8535
8536 Mutex::Autolock _l(mLock);
8537 mIoJitterMs.add(jitterMs);
8538 mProcessTimeMs.add(processMs);
8539 }
8540 // update timing info.
8541 mLastIoBeginNs = lastIoBeginNs;
8542 mLastIoEndNs = lastIoEndNs;
8543 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008544 }
8545
Glenn Kasten93e471f2013-08-19 08:40:07 -07008546 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008547
8548 {
8549 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008550 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008551 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008552 track->invalidate();
8553 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008554 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008555 mStartStopCond.broadcast();
8556 }
8557
8558 releaseWakeLock();
8559
8560 ALOGV("RecordThread %p exiting", this);
8561 return false;
8562}
8563
Andy Hung4b17e882023-07-07 13:47:37 -07008564void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008565{
8566 if (!mStandby) {
8567 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008568 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008569 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008570 mStandby = true;
8571 }
8572}
8573
Andy Hung4b17e882023-07-07 13:47:37 -07008574void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008575{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008576 // Idle the fast capture if it's currently running
8577 if (mFastCapture != 0) {
8578 FastCaptureStateQueue *sq = mFastCapture->sq();
8579 FastCaptureState *state = sq->begin();
8580 if (!(state->mCommand & FastCaptureState::IDLE)) {
8581 state->mCommand = FastCaptureState::COLD_IDLE;
8582 state->mColdFutexAddr = &mFastCaptureFutex;
8583 state->mColdGen++;
8584 mFastCaptureFutex = 0;
8585 sq->end();
8586 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8587 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8588#if 0
8589 if (kUseFastCapture == FastCapture_Dynamic) {
8590 // FIXME
8591 }
8592#endif
8593#ifdef AUDIO_WATCHDOG
8594 // FIXME
8595#endif
8596 } else {
8597 sq->end(false /*didModify*/);
8598 }
8599 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008600 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008601 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008602
8603 // If going into standby, flush the pipe source.
8604 if (mPipeSource.get() != nullptr) {
8605 const ssize_t flushed = mPipeSource->flush();
8606 if (flushed > 0) {
8607 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8608 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8609 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8610 }
8611 }
Eric Laurent81784c32012-11-19 14:55:58 -08008612}
8613
Glenn Kasten05997e22014-03-13 15:08:33 -07008614// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07008615sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008616 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008617 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008618 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008619 audio_format_t format,
8620 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008621 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008622 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008623 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008624 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008625 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008626 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008627 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008628 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008629 audio_port_handle_t portId,
8630 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008631{
Glenn Kasten74935e42013-12-19 08:56:45 -08008632 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008633 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008634 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008635 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008636 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008637 audio_input_flags_t requestedFlags = *flags;
8638 uint32_t sampleRate;
8639
8640 lStatus = initCheck();
8641 if (lStatus != NO_ERROR) {
8642 ALOGE("createRecordTrack_l() audio driver not initialized");
8643 goto Exit;
8644 }
8645
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008646 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8647 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8648 lStatus = BAD_VALUE;
8649 goto Exit;
8650 }
8651
Eric Laurentec376dc2021-04-08 20:41:22 +02008652 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008653 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008654 lStatus = PERMISSION_DENIED;
8655 goto Exit;
8656 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008657 if (maxSharedAudioHistoryMs < 0
8658 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8659 lStatus = BAD_VALUE;
8660 goto Exit;
8661 }
8662 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008663 if (*pSampleRate == 0) {
8664 *pSampleRate = mSampleRate;
8665 }
8666 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008667
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008668 // special case for FAST flag considered OK if fast capture is present and access to
8669 // audio history is not required
8670 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008671 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8672 }
8673
Eric Laurentf14db3c2017-12-08 14:20:36 -08008674 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008675 if ((*flags & inputFlags) != *flags) {
8676 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8677 " input flags (%08x)",
8678 *flags, inputFlags);
8679 *flags = (audio_input_flags_t)(*flags & inputFlags);
8680 }
Eric Laurent81784c32012-11-19 14:55:58 -08008681
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008682 // client expresses a preference for FAST and no access to audio history,
8683 // but we get the final say
8684 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008685 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008686 // we formerly checked for a callback handler (non-0 tid),
8687 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008688 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008689 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008690 // Frame count is not specified (0), or is less than or equal the pipe depth.
8691 // It is OK to provide a higher capacity than requested.
8692 // We will force it to mPipeFramesP2 below.
8693 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008694 // PCM data
8695 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008696 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008697 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008698 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008699 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008700 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008701 hasFastCapture() &&
8702 // there are sufficient fast track slots available
8703 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008704 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008705 // check compatibility with audio effects.
8706 Mutex::Autolock _l(mLock);
8707 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008708 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008709 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008710 audio_input_flags_t old = *flags;
8711 chain->checkInputFlagCompatibility(flags);
8712 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008713 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8714 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008715 }
8716 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008717 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008718 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8719 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008720 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008721 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8722 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008723 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008724 this, frameCount, mFrameCount, mPipeFramesP2,
8725 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008726 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008727 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008728 }
8729 }
8730
Eric Laurentf14db3c2017-12-08 14:20:36 -08008731 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8732 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8733 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8734 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8735 lStatus = BAD_TYPE;
8736 goto Exit;
8737 }
8738
Glenn Kasten74105912014-07-03 12:28:53 -07008739 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008740 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008741 // fast track: frame count is exactly the pipe depth
8742 frameCount = mPipeFramesP2;
8743 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008744 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008745 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008746 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8747 // or 20 ms if there is a fast capture
8748 // TODO This could be a roundupRatio inline, and const
8749 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8750 * sampleRate + mSampleRate - 1) / mSampleRate;
8751 // minimum number of notification periods is at least kMinNotifications,
8752 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8753 static const size_t kMinNotifications = 3;
8754 static const uint32_t kMinMs = 30;
8755 // TODO This could be a roundupRatio inline
8756 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8757 // TODO This could be a roundupRatio inline
8758 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8759 maxNotificationFrames;
8760 const size_t minFrameCount = maxNotificationFrames *
8761 max(kMinNotifications, minNotificationsByMs);
8762 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008763 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8764 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008765 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008766 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008767 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008768 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008769
8770 { // scope for mLock
8771 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008772 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008773 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008774 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008775 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008776 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008777 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008778 }
Eric Laurent81784c32012-11-19 14:55:58 -08008779
Andy Hung11e74242023-06-26 19:20:57 -07008780 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008781 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008782 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07008783 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008784 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008785
Glenn Kasten03003332013-08-06 15:40:54 -07008786 lStatus = track->initCheck();
8787 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008788 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008789 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008790 goto Exit;
8791 }
8792 mTracks.add(track);
8793
Eric Laurent05067782016-06-01 18:27:28 -07008794 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008795 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8796 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8797 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008798 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008799 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008800
8801 if (maxSharedAudioHistoryMs != 0) {
8802 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8803 }
Eric Laurent81784c32012-11-19 14:55:58 -08008804 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008805
Eric Laurent81784c32012-11-19 14:55:58 -08008806 lStatus = NO_ERROR;
8807
8808Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008809 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008810 return track;
8811}
8812
Andy Hung4b17e882023-07-07 13:47:37 -07008813status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008814 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008815 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008816{
8817 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8818 sp<ThreadBase> strongMe = this;
8819 status_t status = NO_ERROR;
8820
8821 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008822 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008823 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07008824 recordTrack->synchronizedRecordState().startRecording(
Andy Hung93bb5732023-05-04 21:16:34 -07008825 mAudioFlinger->createSyncEvent(
8826 event, triggerSession,
8827 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008828 }
8829
8830 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008831 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008832 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008833 if (recordTrack->isInvalid()) {
8834 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008835 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8836 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008837 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008838 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008839 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008840 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8841 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008842 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07008843 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008844 } else {
Andy Hung11e74242023-06-26 19:20:57 -07008845 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008846 }
8847 return status;
8848 }
8849
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008850 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8851 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8852 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07008853 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008854 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008855 if (recordTrack->isExternalTrack()) {
8856 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008857 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008858 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008859 if (recordTrack->isInvalid()) {
8860 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07008861 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8862 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008863 // STARTING_2 forces destroy to call stopInput.
8864 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008865 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8866 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008867 }
Andy Hung11e74242023-06-26 19:20:57 -07008868 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008869 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07008870 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008871 // Someone else has changed state, let them take over,
8872 // leave mState in the new state.
8873 recordTrack->clearSyncStartEvent();
8874 return INVALID_OPERATION;
8875 }
8876 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008877 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008878 ALOGW("%s(%d): startInput failed, status %d",
8879 __func__, recordTrack->id(), status);
8880 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8881 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008882 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008883 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008884 return status;
8885 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008886 sendIoConfigEvent_l(
8887 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008888 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008889
8890 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8891
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008892 // Catch up with current buffer indices if thread is already running.
8893 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8894 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8895 // see previously buffered data before it called start(), but with greater risk of overrun.
8896
Andy Hung11e74242023-06-26 19:20:57 -07008897 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008898 if (!recordTrack->isDirect()) {
8899 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07008900 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008901 }
Andy Hung11e74242023-06-26 19:20:57 -07008902 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008903 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008904 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008905 return status;
8906 }
Eric Laurent81784c32012-11-19 14:55:58 -08008907}
8908
Andy Hung4b17e882023-07-07 13:47:37 -07008909void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008910{
Andy Hung4b17e882023-07-07 13:47:37 -07008911 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008912
8913 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07008914 sp<IAfTrackBase> ptr =
8915 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
8916 if (ptr != nullptr) {
8917 // TODO(b/288339104) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
8918 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08008919 }
Eric Laurent81784c32012-11-19 14:55:58 -08008920 }
8921}
8922
Andy Hung4b17e882023-07-07 13:47:37 -07008923bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008924 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008925 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008926 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07008927 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008928 return false;
8929 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008930 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07008931 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07008932
Andy Hungabfab202019-03-07 19:45:54 -08008933 // NOTE: Waiting here is important to keep stop synchronous.
8934 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07008935 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungce685402018-10-05 17:23:27 -07008936 mWaitWorkCV.broadcast(); // signal thread to stop
8937 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008938 }
Andy Hungce685402018-10-05 17:23:27 -07008939
Andy Hung11e74242023-06-26 19:20:57 -07008940 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008941 ALOGV("Record stopped OK");
8942 return true;
8943 }
Andy Hungce685402018-10-05 17:23:27 -07008944
8945 // don't handle anything - we've been invalidated or restarted and in a different state
8946 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07008947 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008948 return false;
8949}
8950
Andy Hung4b17e882023-07-07 13:47:37 -07008951bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008952{
8953 return false;
8954}
8955
Andy Hung4b17e882023-07-07 13:47:37 -07008956status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08008957{
8958#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8959 if (!isValidSyncEvent(event)) {
8960 return BAD_VALUE;
8961 }
8962
Glenn Kastend848eb42016-03-08 13:42:11 -08008963 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008964 status_t ret = NAME_NOT_FOUND;
8965
8966 Mutex::Autolock _l(mLock);
8967
8968 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008969 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08008970 if (eventSession == track->sessionId()) {
8971 (void) track->setSyncEvent(event);
8972 ret = NO_ERROR;
8973 }
8974 }
8975 return ret;
8976#else
8977 return BAD_VALUE;
8978#endif
8979}
8980
Andy Hung4b17e882023-07-07 13:47:37 -07008981status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07008982 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08008983{
8984 ALOGV("RecordThread::getActiveMicrophones");
8985 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008986 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008987 return NO_INIT;
8988 }
jiabin9ff780e2018-03-19 18:19:52 -07008989 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8990 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008991}
8992
Andy Hung4b17e882023-07-07 13:47:37 -07008993status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06008994 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008995{
Paul McLean12340082019-03-19 09:35:05 -06008996 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008997 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008998 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008999 return NO_INIT;
9000 }
Paul McLean12340082019-03-19 09:35:05 -06009001 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009002}
9003
Andy Hung4b17e882023-07-07 13:47:37 -07009004status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009005{
Paul McLean12340082019-03-19 09:35:05 -06009006 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009007 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009008 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009009 return NO_INIT;
9010 }
Paul McLean12340082019-03-19 09:35:05 -06009011 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009012}
9013
Andy Hung4b17e882023-07-07 13:47:37 -07009014status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009015 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9016 int64_t sharedAudioStartMs) {
9017 AutoMutex _l(mLock);
9018 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9019}
9020
Andy Hung4b17e882023-07-07 13:47:37 -07009021status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009022 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9023 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009024
Eric Laurentec376dc2021-04-08 20:41:22 +02009025 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9026 return BAD_VALUE;
9027 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009028
9029 if (sharedAudioStartMs < 0
9030 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009031 return BAD_VALUE;
9032 }
9033
Eric Laurent2407ce32021-04-26 14:56:03 +02009034 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9035 // As we cannot detect more than one wraparound, only accept values up current write position
9036 // after one wraparound
9037 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9038 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009039 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009040 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9041 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009042 // Bring the start frame position within the input buffer to match the documented
9043 // "best effort" behavior of the API.
9044 if (sharedOffset < 0) {
9045 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009046 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009047 sharedAudioStartFrames =
9048 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009049 }
9050
Eric Laurentec376dc2021-04-08 20:41:22 +02009051 mSharedAudioPackageName = sharedAudioPackageName;
9052 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009053 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009054 } else {
9055 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009056 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009057 }
9058 return NO_ERROR;
9059}
9060
Andy Hung4b17e882023-07-07 13:47:37 -07009061void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009062 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9063 mSharedAudioStartFrames = -1;
9064 mSharedAudioPackageName = "";
9065}
9066
Andy Hung4b17e882023-07-07 13:47:37 -07009067ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009068{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009069 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009070 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009071 }
9072 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009073 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009074 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009075 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009076 }
9077 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009078 MetadataUpdate change;
9079 change.recordMetadataUpdate = metadata.tracks;
9080 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009081}
9082
Eric Laurent81784c32012-11-19 14:55:58 -08009083// destroyTrack_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -07009084void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009085{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009086 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009087 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009088
Eric Laurent81784c32012-11-19 14:55:58 -08009089 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009090 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009091 removeTrack_l(track);
9092 }
9093}
9094
Andy Hung4b17e882023-07-07 13:47:37 -07009095void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009096{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009097 String8 result;
9098 track->appendDump(result, false /* active */);
9099 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
9100
Eric Laurent81784c32012-11-19 14:55:58 -08009101 mTracks.remove(track);
9102 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009103 if (track->isFastTrack()) {
9104 ALOG_ASSERT(!mFastTrackAvail);
9105 mFastTrackAvail = true;
9106 }
Eric Laurent81784c32012-11-19 14:55:58 -08009107}
9108
Andy Hung4b17e882023-07-07 13:47:37 -07009109void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009110{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009111 AudioStreamIn *input = mInput;
9112 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9113 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009114 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009115 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009116 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009117 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009118 }
Andy Hungbfa64962017-06-12 14:43:19 -07009119
9120 if (input != nullptr) {
9121 dprintf(fd, " Hal stream dump:\n");
9122 (void)input->stream->dump(fd);
9123 }
9124
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009125 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009126 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009127
Glenn Kasten2f90c512015-12-02 11:40:09 -08009128 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9129 // while we are dumping it. It may be inconsistent, but it won't mutate!
9130 // This is a large object so we place it on the heap.
9131 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009132 const std::unique_ptr<FastCaptureDumpState> copy =
9133 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009134 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009135}
9136
Andy Hung4b17e882023-07-07 13:47:37 -07009137void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009138{
Eric Laurent81784c32012-11-19 14:55:58 -08009139 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009140 size_t numtracks = mTracks.size();
9141 size_t numactive = mActiveTracks.size();
9142 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009143 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009144 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009145 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009146 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009147 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009148 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009149 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009150 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009151 if (track != 0) {
9152 bool active = mActiveTracks.indexOf(track) >= 0;
9153 if (active) {
9154 numactiveseen++;
9155 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009156 result.append(prefix);
9157 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009158 }
Eric Laurent81784c32012-11-19 14:55:58 -08009159 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009160 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009161 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009162 }
9163
Marco Nelissenb2208842014-02-07 14:00:50 -08009164 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009165 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009166 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009167 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009168 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009169 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009170 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009171 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009172 result.append(prefix);
9173 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009174 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009175 }
Eric Laurent81784c32012-11-19 14:55:58 -08009176
9177 }
9178 write(fd, result.string(), result.size());
9179}
9180
Andy Hung4b17e882023-07-07 13:47:37 -07009181void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009182{
9183 Mutex::Autolock _l(mLock);
9184 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009185 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009186 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009187 track->setSilenced(silenced);
9188 }
9189 }
9190}
Andy Hung73c02e42015-03-29 01:13:58 -07009191
Andy Hung11e74242023-06-26 19:20:57 -07009192void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009193{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009194 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009195 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009196 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009197 const int32_t rear = recordThread->mRsmpInRear;
9198 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009199 if (mRecordTrack->startFrames() >= 0) {
9200 int32_t startFrames = mRecordTrack->startFrames();
9201 // Accept a recent wraparound of mRsmpInRear
9202 if (startFrames <= rear) {
9203 deltaFrames = rear - startFrames;
9204 } else {
9205 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009206 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009207 // start frame cannot be further in the past than start of resampling buffer
9208 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9209 deltaFrames = recordThread->mRsmpInFrames;
9210 }
9211 }
9212 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009213}
9214
Andy Hung11e74242023-06-26 19:20:57 -07009215void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009216 size_t *framesAvailable, bool *hasOverrun)
9217{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009218 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009219 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009220 const int32_t rear = recordThread->mRsmpInRear;
9221 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009222 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009223
9224 size_t framesIn;
9225 bool overrun = false;
9226 if (filled < 0) {
9227 // should not happen, but treat like a massive overrun and re-sync
9228 framesIn = 0;
9229 mRsmpInFront = rear;
9230 overrun = true;
9231 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9232 framesIn = (size_t) filled;
9233 } else {
9234 // client is not keeping up with server, but give it latest data
9235 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009236 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9237 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009238 overrun = true;
9239 }
9240 if (framesAvailable != NULL) {
9241 *framesAvailable = framesIn;
9242 }
9243 if (hasOverrun != NULL) {
9244 *hasOverrun = overrun;
9245 }
9246}
9247
Eric Laurent81784c32012-11-19 14:55:58 -08009248// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009249status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009250 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009251{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009252 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009253 if (threadBase == 0) {
9254 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009255 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009256 return NOT_ENOUGH_DATA;
9257 }
Andy Hung4b17e882023-07-07 13:47:37 -07009258 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009259 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009260 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009261 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009262 // FIXME should not be P2 (don't want to increase latency)
9263 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009264 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009265 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009266
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009267 front &= recordThread->mRsmpInFramesP2 - 1;
9268 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009269 if (part1 > (size_t) filled) {
9270 part1 = filled;
9271 }
9272 size_t ask = buffer->frameCount;
9273 ALOG_ASSERT(ask > 0);
9274 if (part1 > ask) {
9275 part1 = ask;
9276 }
9277 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009278 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009279 buffer->raw = NULL;
9280 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009281 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009282 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009283 }
9284
Andy Hung57446612015-04-19 23:56:46 -07009285 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009286 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009287 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009288 return NO_ERROR;
9289}
9290
9291// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009292void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009293 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009294{
Hongwei Wang95e37682019-04-12 11:13:36 -07009295 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009296 if (stepCount == 0) {
9297 return;
9298 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009299 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009300 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009301 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009302 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009303 buffer->frameCount = 0;
9304}
9305
Andy Hung4b17e882023-07-07 13:47:37 -07009306void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009307{
9308 Mutex::Autolock _l(mLock);
9309 checkBtNrec_l();
9310}
9311
Andy Hung4b17e882023-07-07 13:47:37 -07009312void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009313{
9314 // disable AEC and NS if the device is a BT SCO headset supporting those
9315 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009316 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009317 mAudioFlinger->btNrecIsOff();
9318 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9319 for (size_t i = 0; i < mEffectChains.size(); i++) {
9320 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9321 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9322 }
9323 }
9324}
9325
Andy Hung97a893e2015-03-29 01:03:07 -07009326
Andy Hung4b17e882023-07-07 13:47:37 -07009327bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009328 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009329{
9330 bool reconfig = false;
9331
Eric Laurent10351942014-05-08 18:49:52 -07009332 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009333
Eric Laurent10351942014-05-08 18:49:52 -07009334 audio_format_t reqFormat = mFormat;
9335 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009336 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Jing Mike537412f2023-03-12 11:01:47 +08009337 [[maybe_unused]] audio_channel_mask_t channelMask =
9338 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009339
9340 AudioParameter param = AudioParameter(keyValuePair);
9341 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009342
9343 // scope for AutoPark extends to end of method
9344 AutoPark<FastCapture> park(mFastCapture);
9345
Eric Laurent10351942014-05-08 18:49:52 -07009346 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9347 // channel count change can be requested. Do we mandate the first client defines the
9348 // HAL sampling rate and channel count or do we allow changes on the fly?
9349 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9350 samplingRate = value;
9351 reconfig = true;
9352 }
9353 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009354 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009355 status = BAD_VALUE;
9356 } else {
9357 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009358 reconfig = true;
9359 }
Eric Laurent10351942014-05-08 18:49:52 -07009360 }
9361 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9362 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009363 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009364 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009365 status = BAD_VALUE;
9366 } else {
9367 channelMask = mask;
9368 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009369 }
Eric Laurent10351942014-05-08 18:49:52 -07009370 }
9371 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9372 // do not accept frame count changes if tracks are open as the track buffer
9373 // size depends on frame count and correct behavior would not be guaranteed
9374 // if frame count is changed after track creation
9375 if (mActiveTracks.size() > 0) {
9376 status = INVALID_OPERATION;
9377 } else {
9378 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009379 }
Eric Laurent10351942014-05-08 18:49:52 -07009380 }
9381 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009382 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009383 }
9384 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9385 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009386 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009387 }
Glenn Kastene198c362013-08-13 09:13:36 -07009388
Eric Laurent10351942014-05-08 18:49:52 -07009389 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009390 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009391 if (status == INVALID_OPERATION) {
9392 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009393 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009394 }
9395 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009396 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009397 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9398 if (mInput->stream->getAudioProperties(&config) == OK &&
9399 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9400 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009401 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009402 status = NO_ERROR;
9403 }
Eric Laurent81784c32012-11-19 14:55:58 -08009404 }
Eric Laurent10351942014-05-08 18:49:52 -07009405 if (status == NO_ERROR) {
9406 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009407 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009408 }
9409 }
Eric Laurent81784c32012-11-19 14:55:58 -08009410 }
Eric Laurent10351942014-05-08 18:49:52 -07009411
Eric Laurent81784c32012-11-19 14:55:58 -08009412 return reconfig;
9413}
9414
Andy Hung4b17e882023-07-07 13:47:37 -07009415String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009416{
Eric Laurent81784c32012-11-19 14:55:58 -08009417 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009418 if (initCheck() == NO_ERROR) {
9419 String8 out_s8;
9420 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9421 return out_s8;
9422 }
Eric Laurent81784c32012-11-19 14:55:58 -08009423 }
Andy Hung920f6572022-10-06 12:09:49 -07009424 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009425}
9426
Andy Hung4b17e882023-07-07 13:47:37 -07009427void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009428 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009429 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009430 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009431 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009432 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009433 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009434 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9435 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009436 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009437 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009438 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009439 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009440 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009441 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009442 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009443 break;
9444 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009445 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009446}
9447
Andy Hung4b17e882023-07-07 13:47:37 -07009448void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009449{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009450 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9451 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009452 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009453 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9454 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009455 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9456 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009457 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009458 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009459 ALOGI("HAL format %#x is not linear pcm", mFormat);
9460 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009461 result = mInput->stream->getFrameSize(&mFrameSize);
9462 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009463 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9464 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009465 result = mInput->stream->getBufferSize(&mBufferSize);
9466 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009467 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009468 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9469 "mBufferSize=%zu, mFrameCount=%zu",
9470 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009471
Eric Laurentec376dc2021-04-08 20:41:22 +02009472 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9473 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009474 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009475
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009476 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9477 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009478
9479 audio_input_flags_t flags = mInput->flags;
9480 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9481 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9482 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9483 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9484 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9485 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9486 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9487 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9488 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009489}
9490
Andy Hung4b17e882023-07-07 13:47:37 -07009491uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009492{
9493 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009494 uint32_t result;
9495 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9496 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009497 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009498 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009499}
9500
Andy Hung4b17e882023-07-07 13:47:37 -07009501KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009502{
Glenn Kastend848eb42016-03-08 13:42:11 -08009503 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009504 Mutex::Autolock _l(mLock);
9505 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009506 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009507 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009508 if (ids.indexOfKey(sessionId) < 0) {
9509 ids.add(sessionId, true);
9510 }
9511 }
9512 return ids;
9513}
9514
Andy Hung4b17e882023-07-07 13:47:37 -07009515AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009516{
9517 Mutex::Autolock _l(mLock);
9518 AudioStreamIn *input = mInput;
9519 mInput = NULL;
9520 return input;
9521}
9522
9523// this method must always be called either with ThreadBase mLock held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009524sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009525{
9526 if (mInput == NULL) {
9527 return NULL;
9528 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009529 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009530}
9531
Andy Hung4b17e882023-07-07 13:47:37 -07009532status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009533{
Eric Laurent81784c32012-11-19 14:55:58 -08009534 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009535 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009536 chain->setInBuffer(NULL);
9537 chain->setOutBuffer(NULL);
9538
9539 checkSuspendOnAddEffectChain_l(chain);
9540
Eric Laurent1b928682014-10-02 19:41:47 -07009541 // make sure enabled pre processing effects state is communicated to the HAL as we
9542 // just moved them to a new input stream.
9543 chain->syncHalEffectsState();
9544
Eric Laurent81784c32012-11-19 14:55:58 -08009545 mEffectChains.add(chain);
9546
9547 return NO_ERROR;
9548}
9549
Andy Hung4b17e882023-07-07 13:47:37 -07009550size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009551{
9552 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009553
9554 for (size_t i = 0; i < mEffectChains.size(); i++) {
9555 if (chain == mEffectChains[i]) {
9556 mEffectChains.removeAt(i);
9557 break;
9558 }
Eric Laurent81784c32012-11-19 14:55:58 -08009559 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009560 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009561}
9562
Andy Hung4b17e882023-07-07 13:47:37 -07009563status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009564 audio_patch_handle_t *handle)
9565{
9566 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009567
9568 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009569 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009570 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009571 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009572 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009573 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009574 }
9575
Eric Laurentd8365c52017-07-16 15:27:05 -07009576 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009577
9578 // store new source and send to effects
9579 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9580 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009581 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009582 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009583 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009584 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009585
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009586 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009587 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9588 status = hwDevice->createAudioPatch(patch->num_sources,
9589 patch->sources,
9590 patch->num_sinks,
9591 patch->sinks,
9592 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009593 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009594 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9595 patch->sinks[0].ext.mix.usecase.source,
9596 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009597 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009598 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009599
jiabinc52b1ff2019-10-31 17:20:42 -07009600 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009601 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009602 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009603 }
Eric Laurent296fb132015-05-01 11:38:42 -07009604
Andy Hungc2b11cb2020-04-22 09:04:01 -07009605 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009606 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009607 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009608 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009609 // also dispatch to active AudioRecords
9610 for (const auto &track : mActiveTracks) {
9611 track->logEndInterval();
9612 track->logBeginInterval(pathSourcesAsString);
9613 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009614 // Force meteadata update after a route change
9615 mActiveTracks.setHasChanged();
9616
Eric Laurent1c333e22014-05-20 10:48:17 -07009617 return status;
9618}
9619
Andy Hung4b17e882023-07-07 13:47:37 -07009620status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009621{
9622 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009623
jiabinc52b1ff2019-10-31 17:20:42 -07009624 mPatch = audio_patch{};
9625 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009626
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009627 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009628 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9629 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009630 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009631 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009632 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009633 // Force meteadata update after a route change
9634 mActiveTracks.setHasChanged();
9635
Eric Laurent1c333e22014-05-20 10:48:17 -07009636 return status;
9637}
9638
Andy Hung4b17e882023-07-07 13:47:37 -07009639void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009640{
wendy lin56aa82b2020-12-02 15:19:55 +08009641 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009642 mOutDevices = outDevices;
9643 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9644 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009645 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009646 }
9647}
9648
Andy Hung4b17e882023-07-07 13:47:37 -07009649int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009650{
9651 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009652 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009653 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009654 int32_t oldestFront = mRsmpInRear;
9655 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009656 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009657 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009658 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009659 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009660 if (filled > maxFilled) {
9661 oldestFront = front;
9662 maxFilled = filled;
9663 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009664 }
Andy Hung920f6572022-10-06 12:09:49 -07009665 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009666 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9667 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009668 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009669}
9670
Andy Hung4b17e882023-07-07 13:47:37 -07009671void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009672{
9673 if (offset == 0) {
9674 return;
9675 }
9676 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009677 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009678 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009679 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009680 }
9681}
9682
Andy Hung4b17e882023-07-07 13:47:37 -07009683void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009684{
9685 // This is the formula for calculating the temporary buffer size.
9686 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9687 // 1 full output buffer, regardless of the alignment of the available input.
9688 // The value is somewhat arbitrary, and could probably be even larger.
9689 // A larger value should allow more old data to be read after a track calls start(),
9690 // without increasing latency.
9691 //
9692 // Note this is independent of the maximum downsampling ratio permitted for capture.
9693 size_t minRsmpInFrames = mFrameCount * 7;
9694
9695 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9696 // capture history available to another client using the same session ID:
9697 // dimension the resampler input buffer accordingly.
9698
9699 // Get oldest client read position: getOldestFront_l() must be called before altering
9700 // mRsmpInRear, or mRsmpInFrames
9701 int32_t previousFront = getOldestFront_l();
9702 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9703 int32_t previousRear = mRsmpInRear;
9704 mRsmpInRear = 0;
9705
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009706 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -07009707 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009708 "resizeInputBuffer_l() called with invalid max shared history %d",
9709 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009710 if (maxSharedAudioHistoryMs != 0) {
9711 // resizeInputBuffer_l should never be called with a non zero shared history if the
9712 // buffer was not already allocated
9713 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9714 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9715 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9716 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009717 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009718 return;
9719 }
9720 mRsmpInFrames = rsmpInFrames;
9721 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009722 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009723 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9724 // initialized
9725 if (mRsmpInFrames < minRsmpInFrames) {
9726 mRsmpInFrames = minRsmpInFrames;
9727 }
9728 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9729
9730 // TODO optimize audio capture buffer sizes ...
9731 // Here we calculate the size of the sliding buffer used as a source
9732 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9733 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9734 // be better to have it derived from the pipe depth in the long term.
9735 // The current value is higher than necessary. However it should not add to latency.
9736
9737 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9738 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9739
9740 void *rsmpInBuffer;
9741 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9742 // if posix_memalign fails, will segv here.
9743 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9744
9745 // Copy audio history if any from old buffer before freeing it
9746 if (previousRear != 0) {
9747 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9748 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9749
9750 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9751 previousFront &= previousRsmpInFramesP2 - 1;
9752 size_t part1 = previousRsmpInFramesP2 - previousFront;
9753 if (part1 > (size_t) unread) {
9754 part1 = unread;
9755 }
9756 if (part1 != 0) {
9757 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9758 part1 * mFrameSize);
9759 mRsmpInRear = part1;
9760 part1 = unread - part1;
9761 if (part1 != 0) {
9762 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9763 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9764 mRsmpInRear += part1;
9765 }
9766 }
9767 // Update front for all clients according to new rear
9768 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9769 } else {
9770 mRsmpInRear = 0;
9771 }
9772 free(mRsmpInBuffer);
9773 mRsmpInBuffer = rsmpInBuffer;
9774}
9775
Andy Hung4b17e882023-07-07 13:47:37 -07009776void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009777{
9778 Mutex::Autolock _l(mLock);
9779 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009780 if (record->getSource()) {
9781 mSource = record->getSource();
9782 }
Eric Laurent83b88082014-06-20 18:31:16 -07009783}
9784
Andy Hung4b17e882023-07-07 13:47:37 -07009785void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009786{
9787 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009788 if (mSource == record->getSource()) {
9789 mSource = mInput;
9790 }
Eric Laurent83b88082014-06-20 18:31:16 -07009791 destroyTrack_l(record);
9792}
9793
Andy Hung4b17e882023-07-07 13:47:37 -07009794void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009795{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009796 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009797 config->role = AUDIO_PORT_ROLE_SINK;
9798 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9799 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009800 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9801 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9802 config->flags.input = mInput->flags;
9803 }
Eric Laurent83b88082014-06-20 18:31:16 -07009804}
Eric Laurent1c333e22014-05-20 10:48:17 -07009805
Eric Laurent6acd1d42017-01-04 14:23:29 -08009806// ----------------------------------------------------------------------------
9807// Mmap
9808// ----------------------------------------------------------------------------
9809
Andy Hung765de282023-07-07 15:58:48 -07009810// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9811// MmapPlaybackThread or MmapCaptureThread instance.
9812class MmapThreadHandle : public MmapStreamInterface {
9813public:
9814 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9815 ~MmapThreadHandle() override;
9816
9817 // MmapStreamInterface virtuals
9818 status_t createMmapBuffer(int32_t minSizeFrames,
9819 struct audio_mmap_buffer_info* info) final;
9820 status_t getMmapPosition(struct audio_mmap_position* position) final;
9821 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9822 status_t start(const AudioClient& client,
9823 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9824 status_t stop(audio_port_handle_t handle) final;
9825 status_t standby() final;
9826 status_t reportData(const void* buffer, size_t frameCount) final;
9827private:
9828 const sp<IAfMmapThread> mThread;
9829};
9830
9831/* static */
9832sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9833 const sp<IAfMmapThread>& mmapThread) {
9834 return sp<MmapThreadHandle>::make(mmapThread);
9835}
9836
9837MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009838 : mThread(thread)
9839{
Phil Burk9fabbf82017-08-03 12:02:00 -07009840 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009841}
9842
Andy Hung765de282023-07-07 15:58:48 -07009843// MmapStreamInterface could be directly implemented by MmapThread excepting this
9844// special handling on adapter dtor.
9845MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009846{
Phil Burk9fabbf82017-08-03 12:02:00 -07009847 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009848}
9849
Andy Hung765de282023-07-07 15:58:48 -07009850status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009851 struct audio_mmap_buffer_info *info)
9852{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009853 return mThread->createMmapBuffer(minSizeFrames, info);
9854}
9855
Andy Hung765de282023-07-07 15:58:48 -07009856status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009857{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009858 return mThread->getMmapPosition(position);
9859}
9860
Andy Hung765de282023-07-07 15:58:48 -07009861status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009862 int64_t *timeNanos) {
9863 return mThread->getExternalPosition(position, timeNanos);
9864}
9865
Andy Hung765de282023-07-07 15:58:48 -07009866status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009867 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009868{
jiabind1f1cb62020-03-24 11:57:57 -07009869 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009870}
9871
Andy Hung765de282023-07-07 15:58:48 -07009872status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009873{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874 return mThread->stop(handle);
9875}
9876
Andy Hung765de282023-07-07 15:58:48 -07009877status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009878{
Eric Laurent18b57012017-02-13 16:23:52 -08009879 return mThread->standby();
9880}
9881
Andy Hung765de282023-07-07 15:58:48 -07009882status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9883{
jiabinfc791ee2023-02-15 19:43:40 +00009884 return mThread->reportData(buffer, frameCount);
9885}
9886
Eric Laurent6acd1d42017-01-04 14:23:29 -08009887
Andy Hung4b17e882023-07-07 13:47:37 -07009888MmapThread::MmapThread(
Eric Laurent6acd1d42017-01-04 14:23:29 -08009889 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009890 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009891 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009892 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009893 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009894 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009895 mActiveTracks(&this->mLocalLog),
9896 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9897 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009898{
Eric Laurent18b57012017-02-13 16:23:52 -08009899 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009900 readHalParameters_l();
9901}
9902
Andy Hung4b17e882023-07-07 13:47:37 -07009903void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009904{
9905 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9906}
9907
Andy Hung4b17e882023-07-07 13:47:37 -07009908void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009909{
Andy Hung11e74242023-06-26 19:20:57 -07009910 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -07009911 {
9912 Mutex::Autolock _l(mLock);
Andy Hung11e74242023-06-26 19:20:57 -07009913 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -07009914 activeTracks.add(t);
9915 }
9916 }
Andy Hung11e74242023-06-26 19:20:57 -07009917 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009918 stop(t->portId());
9919 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009920 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009921 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009922 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009923 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009924 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009925 }
9926}
9927
9928
Andy Hung4b17e882023-07-07 13:47:37 -07009929void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930 audio_stream_type_t streamType __unused,
9931 audio_session_t sessionId,
9932 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009933 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934 audio_port_handle_t portId)
9935{
9936 mAttr = *attr;
9937 mSessionId = sessionId;
9938 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009939 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009940 mPortId = portId;
9941}
9942
Andy Hung4b17e882023-07-07 13:47:37 -07009943status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944 struct audio_mmap_buffer_info *info)
9945{
9946 if (mHalStream == 0) {
9947 return NO_INIT;
9948 }
Eric Laurent18b57012017-02-13 16:23:52 -08009949 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009950 return mHalStream->createMmapBuffer(minSizeFrames, info);
9951}
9952
Andy Hung4b17e882023-07-07 13:47:37 -07009953status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08009954{
9955 if (mHalStream == 0) {
9956 return NO_INIT;
9957 }
9958 return mHalStream->getMmapPosition(position);
9959}
9960
Andy Hung4b17e882023-07-07 13:47:37 -07009961status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -07009962{
Eric Laurentdda206a2022-07-08 17:28:35 +02009963 // The HAL must receive track metadata before starting the stream
9964 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -07009965 status_t ret = mHalStream->start();
9966 if (ret != NO_ERROR) {
9967 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9968 return ret;
9969 }
Andy Hungcf10d742020-04-28 15:38:24 -07009970 if (mStandby) {
9971 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009972 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009973 mStandby = false;
9974 }
Eric Laurent331679c2018-04-16 17:03:16 -07009975 return NO_ERROR;
9976}
9977
Andy Hung4b17e882023-07-07 13:47:37 -07009978status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009979 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009980 audio_port_handle_t *handle)
9981{
Eric Laurenta54f1282017-07-01 19:39:32 -07009982 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009983 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009984 if (mHalStream == 0) {
9985 return NO_INIT;
9986 }
9987
9988 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009989
Eric Laurentdda206a2022-07-08 17:28:35 +02009990 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -07009991 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +02009992 acquireWakeLock();
9993 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -07009994 }
9995
9996 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9997
9998 audio_io_handle_t io = mId;
Atneya Nairf59db5c2023-05-10 21:37:41 -07009999 AttributionSourceState adjAttributionSource = AudioFlinger::checkAttributionSourcePackage(
10000 client.attributionSource);
10001
Eric Laurenta54f1282017-07-01 19:39:32 -070010002 if (isOutput()) {
10003 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10004 config.sample_rate = mSampleRate;
10005 config.channel_mask = mChannelMask;
10006 config.format = mFormat;
10007 audio_stream_type_t stream = streamType();
10008 audio_output_flags_t flags =
10009 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010010 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010011 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010012 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010013 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010014 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10015 mSessionId,
10016 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010017 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010018 &config,
10019 flags,
10020 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010021 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010022 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010023 &isSpatialized,
10024 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010025 ALOGD_IF(!secondaryOutputs.empty(),
10026 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010027 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010028 audio_config_base_t config;
10029 config.sample_rate = mSampleRate;
10030 config.channel_mask = mChannelMask;
10031 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010032 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010033 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010034 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010035 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010036 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010037 &config,
10038 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10039 &deviceId,
10040 &portId);
10041 }
10042 // APM should not chose a different input or output stream for the same set of attributes
10043 // and audo configuration
10044 if (ret != NO_ERROR || io != mId) {
10045 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10046 __FUNCTION__, ret, io, mId);
10047 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010048 }
10049
10050 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010051 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010052 } else {
jiabin09609032022-06-15 19:26:01 +000010053 {
10054 // Add the track record before starting input so that the silent status for the
10055 // client can be cached.
10056 Mutex::Autolock _l(mLock);
10057 setClientSilencedState_l(portId, false /*silenced*/);
10058 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010059 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 }
10061
Eric Laurent331679c2018-04-16 17:03:16 -070010062 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010063 // abort if start is rejected by audio policy manager
10064 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010065 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010066 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -070010067 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010068 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010069 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010070 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010071 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010072 }
Eric Laurent331679c2018-04-16 17:03:16 -070010073 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010074 } else {
10075 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010076 }
jiabin09609032022-06-15 19:26:01 +000010077 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078 return PERMISSION_DENIED;
10079 }
10080
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010081 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010082 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10083 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010084 mChannelMask, mSessionId, isOutput(),
10085 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010086 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010087 if (!isOutput()) {
10088 track->setSilenced_l(isClientSilenced_l(portId));
10089 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010090
Eric Laurent4eb58f12018-12-07 16:41:02 -080010091 if (isOutput()) {
10092 // force volume update when a new track is added
10093 mHalVolFloat = -1.0f;
10094 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010095 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010096 if (t->isSilenced_l()
10097 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010098 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010099 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010100 }
10101 }
10102
Eric Laurent6acd1d42017-01-04 14:23:29 -080010103 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010104 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010105 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010106 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010107 chain->incTrackCnt();
10108 chain->incActiveTrackCnt();
10109 }
10110
Andy Hungc2b11cb2020-04-22 09:04:01 -070010111 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010112 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010113
10114 if (mActiveTracks.size() == 1) {
10115 ret = exitStandby_l();
10116 }
10117
Eric Laurent6acd1d42017-01-04 14:23:29 -080010118 broadcast_l();
10119
Eric Laurentdda206a2022-07-08 17:28:35 +020010120 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121
Eric Laurentdda206a2022-07-08 17:28:35 +020010122 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010123}
10124
Andy Hung4b17e882023-07-07 13:47:37 -070010125status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127 ALOGV("%s handle %d", __FUNCTION__, handle);
10128
10129 if (mHalStream == 0) {
10130 return NO_INIT;
10131 }
10132
Eric Laurenta54f1282017-07-01 19:39:32 -070010133 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010134 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010135 return NO_ERROR;
10136 }
10137
Eric Laurent331679c2018-04-16 17:03:16 -070010138 Mutex::Autolock _l(mLock);
10139
Andy Hung11e74242023-06-26 19:20:57 -070010140 sp<IAfMmapTrack> track;
10141 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010142 if (handle == t->portId()) {
10143 track = t;
10144 break;
10145 }
10146 }
10147 if (track == 0) {
10148 return BAD_VALUE;
10149 }
10150
10151 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010152 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010153
Eric Laurent331679c2018-04-16 17:03:16 -070010154 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010156 AudioSystem::stopOutput(track->portId());
10157 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010159 AudioSystem::stopInput(track->portId());
10160 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 }
Eric Laurent331679c2018-04-16 17:03:16 -070010162 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010163
Andy Hung116bc262023-06-20 18:56:17 -070010164 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 if (chain != 0) {
10166 chain->decActiveTrackCnt();
10167 chain->decTrackCnt();
10168 }
10169
Eric Laurentdda206a2022-07-08 17:28:35 +020010170 if (mActiveTracks.isEmpty()) {
10171 mHalStream->stop();
10172 }
10173
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174 broadcast_l();
10175
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176 return NO_ERROR;
10177}
10178
Andy Hung4b17e882023-07-07 13:47:37 -070010179status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010180{
10181 ALOGV("%s", __FUNCTION__);
10182
10183 if (mHalStream == 0) {
10184 return NO_INIT;
10185 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010186 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010187 return INVALID_OPERATION;
10188 }
10189 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010190 if (!mStandby) {
10191 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010192 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010193 mStandby = true;
10194 }
Eric Laurent18b57012017-02-13 16:23:52 -080010195 releaseWakeLock();
10196 return NO_ERROR;
10197}
10198
Andy Hung4b17e882023-07-07 13:47:37 -070010199status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010200 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10201 return INVALID_OPERATION;
10202}
10203
Andy Hung4b17e882023-07-07 13:47:37 -070010204void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205{
10206 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10207 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10208 mFormat = mHALFormat;
10209 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10210 result = mHalStream->getFrameSize(&mFrameSize);
10211 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010212 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10213 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010214 result = mHalStream->getBufferSize(&mBufferSize);
10215 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10216 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010217
Andy Hungcf10d742020-04-28 15:38:24 -070010218 // TODO: make a readHalParameters call?
10219 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010220 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
10221 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
10222 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10223 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10224 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10225 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10226 /*
10227 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10228 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10229 (int32_t)mHapticChannelMask)
10230 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10231 (int32_t)mHapticChannelCount)
10232 */
10233 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
10234 formatToString(mHALFormat).c_str())
10235 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10236 (int32_t)mFrameCount) // sic - added HAL
10237 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010238}
10239
Andy Hung4b17e882023-07-07 13:47:37 -070010240bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242 checkSilentMode_l();
10243
10244 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10245
10246 while (!exitPending())
10247 {
Andy Hung116bc262023-06-20 18:56:17 -070010248 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010249
Andy Hung13850be2019-03-14 11:33:09 -070010250 { // under Thread lock
10251 Mutex::Autolock _l(mLock);
10252
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253 if (mSignalPending) {
10254 // A signal was raised while we were unlocked
10255 mSignalPending = false;
10256 } else {
10257 if (mConfigEvents.isEmpty()) {
10258 // we're about to wait, flush the binder command buffer
10259 IPCThreadState::self()->flushCommands();
10260
10261 if (exitPending()) {
10262 break;
10263 }
10264
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265 // wait until we have something to do...
10266 ALOGV("%s going to sleep", myName.string());
10267 mWaitWorkCV.wait(mLock);
10268 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269
10270 checkSilentMode_l();
10271
10272 continue;
10273 }
10274 }
10275
10276 processConfigEvents_l();
10277
10278 processVolume_l();
10279
10280 checkInvalidTracks_l();
10281
10282 mActiveTracks.updatePowerState(this);
10283
Kevin Rocard069c2712018-03-29 19:09:14 -070010284 updateMetadata_l();
10285
Eric Laurent6acd1d42017-01-04 14:23:29 -080010286 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010287 } // release Thread lock
10288
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010290 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 }
Andy Hung13850be2019-03-14 11:33:09 -070010292
10293 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 unlockEffectChains(effectChains);
10295 // Effect chains will be actually deleted here if they were removed from
10296 // mEffectChains list during mixing or effects processing
10297 }
10298
10299 threadLoop_exit();
10300
10301 if (!mStandby) {
10302 threadLoop_standby();
10303 mStandby = true;
10304 }
10305
Eric Laurent6acd1d42017-01-04 14:23:29 -080010306 ALOGV("Thread %p type %d exiting", this, mType);
10307 return false;
10308}
10309
10310// checkForNewParameter_l() must be called with ThreadBase::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010311bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312 status_t& status)
10313{
10314 AudioParameter param = AudioParameter(keyValuePair);
10315 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010316 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010317 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010318 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010319 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010320 if (sendToHal) {
10321 status = mHalStream->setParameters(keyValuePair);
10322 } else {
10323 status = NO_ERROR;
10324 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325
10326 return false;
10327}
10328
Andy Hung4b17e882023-07-07 13:47:37 -070010329String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010330{
10331 Mutex::Autolock _l(mLock);
10332 String8 out_s8;
10333 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10334 return out_s8;
10335 }
Andy Hung920f6572022-10-06 12:09:49 -070010336 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337}
10338
Andy Hung4b17e882023-07-07 13:47:37 -070010339void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010340 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010341 sp<AudioIoDescriptor> desc;
10342 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343 switch (event) {
10344 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010345 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010347 isInput = true;
10348 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010350 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010352 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10353 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010354 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010355 case AUDIO_INPUT_CLOSED:
10356 case AUDIO_OUTPUT_CLOSED:
10357 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010358 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010359 break;
10360 }
10361 mAudioFlinger->ioConfigChanged(event, desc, pid);
10362}
10363
Andy Hung4b17e882023-07-07 13:47:37 -070010364status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365 audio_patch_handle_t *handle)
Andy Hung920f6572022-10-06 12:09:49 -070010366NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367{
10368 status_t status = NO_ERROR;
10369
10370 // store new device and send to effects
10371 audio_devices_t type = AUDIO_DEVICE_NONE;
10372 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010373 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10374 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10375 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 if (isOutput()) {
10377 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010378 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10379 && !mAudioHwDev->supportsAudioPatches(),
10380 "Enumerated device type(%#x) must not be used "
10381 "as it does not support audio patches",
10382 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010383 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010384 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10385 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386 }
10387 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010388 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389 } else {
10390 type = patch->sources[0].ext.device.type;
10391 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010392 numDevices = mPatch.num_sources;
10393 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010394 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010395 }
10396
10397 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010398 if (isOutput()) {
10399 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10400 } else {
10401 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10402 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010403 }
10404
jiabinc52b1ff2019-10-31 17:20:42 -070010405 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406 // store new source and send to effects
10407 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10408 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10409 for (size_t i = 0; i < mEffectChains.size(); i++) {
10410 mEffectChains[i]->setAudioSource_l(mAudioSource);
10411 }
10412 }
10413 }
10414
10415 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010416 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10417 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010418 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010419 audio_port_config port;
10420 std::optional<audio_source_t> source;
10421 if (isOutput()) {
10422 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010423 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010424 port = patch->sources[0];
10425 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010427 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428 *handle = AUDIO_PATCH_HANDLE_NONE;
10429 }
10430
jiabinc52b1ff2019-10-31 17:20:42 -070010431 if (numDevices == 0 || mDeviceId != deviceId) {
10432 if (isOutput()) {
10433 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10434 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010435 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010436 } else {
10437 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10438 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10439 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010440 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010441 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010442 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010443 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010444 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010445 }
jiabinc52b1ff2019-10-31 17:20:42 -070010446 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010447 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010449 // Force meteadata update after a route change
10450 mActiveTracks.setHasChanged();
10451
Eric Laurent6acd1d42017-01-04 14:23:29 -080010452 return status;
10453}
10454
Andy Hung4b17e882023-07-07 13:47:37 -070010455status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456{
10457 status_t status = NO_ERROR;
10458
jiabinc52b1ff2019-10-31 17:20:42 -070010459 mPatch = audio_patch{};
10460 mOutDeviceTypeAddrs.clear();
10461 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462
10463 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10464 supportsAudioPatches : false;
10465
10466 if (supportsAudioPatches) {
10467 status = mHalDevice->releaseAudioPatch(handle);
10468 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010469 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010471 // Force meteadata update after a route change
10472 mActiveTracks.setHasChanged();
10473
Eric Laurent6acd1d42017-01-04 14:23:29 -080010474 return status;
10475}
10476
Andy Hung4b17e882023-07-07 13:47:37 -070010477void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010479 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010480 if (isOutput()) {
10481 config->role = AUDIO_PORT_ROLE_SOURCE;
10482 config->ext.mix.hw_module = mAudioHwDev->handle();
10483 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10484 } else {
10485 config->role = AUDIO_PORT_ROLE_SINK;
10486 config->ext.mix.hw_module = mAudioHwDev->handle();
10487 config->ext.mix.usecase.source = mAudioSource;
10488 }
10489}
10490
Andy Hung4b17e882023-07-07 13:47:37 -070010491status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010492{
10493 audio_session_t session = chain->sessionId();
10494
10495 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10496 // Attach all tracks with same session ID to this chain.
10497 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010498 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499 if (session == track->sessionId()) {
10500 chain->incTrackCnt();
10501 chain->incActiveTrackCnt();
10502 }
10503 }
10504
10505 chain->setThread(this);
10506 chain->setInBuffer(nullptr);
10507 chain->setOutBuffer(nullptr);
10508 chain->syncHalEffectsState();
10509
10510 mEffectChains.add(chain);
10511 checkSuspendOnAddEffectChain_l(chain);
10512 return NO_ERROR;
10513}
10514
Andy Hung4b17e882023-07-07 13:47:37 -070010515size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010516{
10517 audio_session_t session = chain->sessionId();
10518
10519 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10520
10521 for (size_t i = 0; i < mEffectChains.size(); i++) {
10522 if (chain == mEffectChains[i]) {
10523 mEffectChains.removeAt(i);
10524 // detach all active tracks from the chain
10525 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010526 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010527 if (session == track->sessionId()) {
10528 chain->decActiveTrackCnt();
10529 chain->decTrackCnt();
10530 }
10531 }
10532 break;
10533 }
10534 }
10535 return mEffectChains.size();
10536}
10537
Andy Hung4b17e882023-07-07 13:47:37 -070010538void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010539{
10540 mHalStream->standby();
10541}
10542
Andy Hung4b17e882023-07-07 13:47:37 -070010543void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010544{
Phil Burk7dce7282017-09-27 13:51:41 -070010545 // Do not call callback->onTearDown() because it is redundant for thread exit
10546 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547}
10548
Andy Hung4b17e882023-07-07 13:47:37 -070010549status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550{
10551 return BAD_VALUE;
10552}
10553
Andy Hung4b17e882023-07-07 13:47:37 -070010554bool MmapThread::isValidSyncEvent(
10555 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010556{
10557 return false;
10558}
10559
Andy Hung4b17e882023-07-07 13:47:37 -070010560status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010561 const effect_descriptor_t *desc, audio_session_t sessionId)
10562{
10563 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010564 if (audio_is_global_session(sessionId)) {
10565 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010566 desc->name, mThreadName);
10567 return BAD_VALUE;
10568 }
10569
10570 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10571 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10572 desc->name);
10573 return BAD_VALUE;
10574 }
10575 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010576 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10577 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 return BAD_VALUE;
10579 }
10580
10581 // Only allow effects without processing load or latency
10582 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10583 return BAD_VALUE;
10584 }
10585
Andy Hung116bc262023-06-20 18:56:17 -070010586 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010587 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10588 return BAD_VALUE;
10589 }
10590
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592}
10593
Andy Hung4b17e882023-07-07 13:47:37 -070010594void MmapThread::checkInvalidTracks_l()
Andy Hung920f6572022-10-06 12:09:49 -070010595NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010596{
Eric Laurent039c24a2022-10-07 14:01:59 +020010597 sp<MmapStreamCallback> callback;
Andy Hung11e74242023-06-26 19:20:57 -070010598 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010600 callback = mCallback.promote();
10601 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10602 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10603 mNoCallbackWarningCount++;
10604 }
10605 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010606 }
10607 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010608 if (callback != 0) {
10609 mLock.unlock();
10610 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10611 mLock.lock();
jiabindfa32482022-10-06 19:45:50 +000010612 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010613}
10614
Andy Hung4b17e882023-07-07 13:47:37 -070010615void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10618 mAttr.content_type, mAttr.usage, mAttr.source);
10619 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010620 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621 dprintf(fd, " No active clients\n");
10622 }
10623}
10624
Andy Hung4b17e882023-07-07 13:47:37 -070010625void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010626{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010628 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010629 dprintf(fd, " %zu Tracks\n", numtracks);
10630 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010631 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010632 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010633 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010635 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010636 result.append(prefix);
10637 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010638 }
10639 } else {
10640 dprintf(fd, "\n");
10641 }
10642 write(fd, result.string(), result.size());
10643}
10644
Andy Hung4b17e882023-07-07 13:47:37 -070010645/* static */
10646sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
10647 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
10648 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
10649 return sp<MmapPlaybackThread>::make(audioFlinger, id, hwDev, output, systemReady);
10650}
10651
10652MmapPlaybackThread::MmapPlaybackThread(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010654 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010655 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010656 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010657 mStreamVolume(1.0),
10658 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010659 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660{
10661 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10662 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10663 mMasterVolume = audioFlinger->masterVolume_l();
10664 mMasterMute = audioFlinger->masterMute_l();
10665 if (mAudioHwDev) {
10666 if (mAudioHwDev->canSetMasterVolume()) {
10667 mMasterVolume = 1.0;
10668 }
10669
10670 if (mAudioHwDev->canSetMasterMute()) {
10671 mMasterMute = false;
10672 }
10673 }
10674}
10675
Andy Hung4b17e882023-07-07 13:47:37 -070010676void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010677 audio_stream_type_t streamType,
10678 audio_session_t sessionId,
10679 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010680 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681 audio_port_handle_t portId)
10682{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010683 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010684 mStreamType = streamType;
10685}
10686
Andy Hung4b17e882023-07-07 13:47:37 -070010687AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688{
10689 Mutex::Autolock _l(mLock);
10690 AudioStreamOut *output = mOutput;
10691 mOutput = NULL;
10692 return output;
10693}
10694
Andy Hung4b17e882023-07-07 13:47:37 -070010695void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696{
10697 Mutex::Autolock _l(mLock);
10698 // Don't apply master volume in SW if our HAL can do it for us.
10699 if (mAudioHwDev &&
10700 mAudioHwDev->canSetMasterVolume()) {
10701 mMasterVolume = 1.0;
10702 } else {
10703 mMasterVolume = value;
10704 }
10705}
10706
Andy Hung4b17e882023-07-07 13:47:37 -070010707void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708{
10709 Mutex::Autolock _l(mLock);
10710 // Don't apply master mute in SW if our HAL can do it for us.
10711 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10712 mMasterMute = false;
10713 } else {
10714 mMasterMute = muted;
10715 }
10716}
10717
Andy Hung4b17e882023-07-07 13:47:37 -070010718void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719{
10720 Mutex::Autolock _l(mLock);
10721 if (stream == mStreamType) {
10722 mStreamVolume = value;
10723 broadcast_l();
10724 }
10725}
10726
Andy Hung4b17e882023-07-07 13:47:37 -070010727float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010728{
10729 Mutex::Autolock _l(mLock);
10730 if (stream == mStreamType) {
10731 return mStreamVolume;
10732 }
10733 return 0.0f;
10734}
10735
Andy Hung4b17e882023-07-07 13:47:37 -070010736void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737{
10738 Mutex::Autolock _l(mLock);
10739 if (stream == mStreamType) {
10740 mStreamMute= muted;
10741 broadcast_l();
10742 }
10743}
10744
Andy Hung4b17e882023-07-07 13:47:37 -070010745void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746{
10747 Mutex::Autolock _l(mLock);
10748 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070010749 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750 track->invalidate();
10751 }
10752 broadcast_l();
10753 }
10754}
10755
Andy Hung4b17e882023-07-07 13:47:37 -070010756void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010757{
10758 Mutex::Autolock _l(mLock);
10759 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070010760 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010761 if (portIds.find(track->portId()) != portIds.end()) {
10762 track->invalidate();
10763 trackMatch = true;
10764 portIds.erase(track->portId());
10765 }
10766 if (portIds.empty()) {
10767 break;
10768 }
10769 }
10770 if (trackMatch) {
10771 broadcast_l();
10772 }
10773}
10774
Andy Hung4b17e882023-07-07 13:47:37 -070010775void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010776NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010777{
10778 float volume;
10779
10780 if (mMasterMute || mStreamMute) {
10781 volume = 0;
10782 } else {
10783 volume = mMasterVolume * mStreamVolume;
10784 }
10785
10786 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787
10788 // Convert volumes from float to 8.24
10789 uint32_t vol = (uint32_t)(volume * (1 << 24));
10790
10791 // Delegate volume control to effect in track effect chain if needed
10792 // only one effect chain can be present on DirectOutputThread, so if
10793 // there is one, the track is connected to it
10794 if (!mEffectChains.isEmpty()) {
10795 mEffectChains[0]->setVolume_l(&vol, &vol);
10796 volume = (float)vol / (1 << 24);
10797 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010798 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010799 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10800 mHalVolFloat = volume; // HW volume control worked, so update value.
10801 mNoCallbackWarningCount = 0;
10802 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010803 sp<MmapStreamCallback> callback = mCallback.promote();
10804 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010805 mHalVolFloat = volume; // SW volume control worked, so update value.
10806 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010807 mLock.unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010808 callback->onVolumeChanged(volume);
Eric Laurent734046e2018-04-16 14:50:52 -070010809 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010810 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010811 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10812 ALOGW("Could not set MMAP stream volume: no volume callback!");
10813 mNoCallbackWarningCount++;
10814 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010815 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010816 }
Andy Hung11e74242023-06-26 19:20:57 -070010817 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010818 track->setMetadataHasChanged();
Vlad Popaec1788e2022-08-04 11:23:30 +020010819 track->processMuteEvent_l(mAudioFlinger->getOrCreateAudioManager(),
10820 /*muteState=*/{mMasterMute,
10821 mStreamVolume == 0.f,
10822 mStreamMute,
10823 // TODO(b/241533526): adjust logic to include mute from AppOps
10824 false /*muteFromPlaybackRestricted*/,
10825 false /*muteFromClientVolume*/,
10826 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010827 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010828 }
10829}
10830
Andy Hung4b17e882023-07-07 13:47:37 -070010831ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010832{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010833 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010834 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010835 }
10836 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070010837 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010838 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010839 playback_track_metadata_v7_t trackMetadata;
10840 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010841 .usage = track->attributes().usage,
10842 .content_type = track->attributes().content_type,
10843 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010844 };
10845 trackMetadata.channel_mask = track->channelMask(),
10846 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10847 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010848 }
10849 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010850
10851 MetadataUpdate change;
10852 change.playbackMetadataUpdate = metadata.tracks;
10853 return change;
10854};
Kevin Rocard069c2712018-03-29 19:09:14 -070010855
Andy Hung4b17e882023-07-07 13:47:37 -070010856void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010857{
10858 if (!mMasterMute) {
10859 char value[PROPERTY_VALUE_MAX];
10860 if (property_get("ro.audio.silent", value, "0") > 0) {
10861 char *endptr;
10862 unsigned long ul = strtoul(value, &endptr, 0);
10863 if (*endptr == '\0' && ul != 0) {
10864 ALOGD("Silence is golden");
10865 // The setprop command will not allow a property to be changed after
10866 // the first time it is set, so we don't have to worry about un-muting.
10867 setMasterMute_l(true);
10868 }
10869 }
10870 }
10871}
10872
Andy Hung4b17e882023-07-07 13:47:37 -070010873void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010874{
10875 MmapThread::toAudioPortConfig(config);
10876 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10877 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10878 config->flags.output = mOutput->flags;
10879 }
10880}
10881
Andy Hung4b17e882023-07-07 13:47:37 -070010882status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070010883 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010884{
10885 if (mOutput == nullptr) {
10886 return NO_INIT;
10887 }
10888 struct timespec timestamp;
10889 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10890 if (status == NO_ERROR) {
10891 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10892 }
10893 return status;
10894}
10895
Andy Hung4b17e882023-07-07 13:47:37 -070010896status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010897 // Send to MelProcessor for sound dose measurement.
10898 auto processor = mMelProcessor.load();
10899 if (processor) {
10900 processor->process(buffer, frameCount * mFrameSize);
10901 }
10902
jiabinfc791ee2023-02-15 19:43:40 +000010903 return NO_ERROR;
10904}
10905
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010906// startMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010907void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010908 const sp<audio_utils::MelProcessor>& processor)
10909{
10910 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010911 mMelProcessor.store(processor);
10912 if (processor) {
10913 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010914 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010915
10916 // no need to update output format for MMapPlaybackThread since it is
10917 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010918}
10919
10920// stopMelComputation_l() must be called with AudioFlinger::mLock held
Andy Hung4b17e882023-07-07 13:47:37 -070010921void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010922{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020010923 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
10924 auto melProcessor = mMelProcessor.load();
10925 if (melProcessor != nullptr) {
10926 melProcessor->pause();
10927 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010928}
10929
Andy Hung4b17e882023-07-07 13:47:37 -070010930void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010931{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010932 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010933
Glenn Kastend3bb6452016-12-05 18:14:37 -080010934 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10935 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010936 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10937}
10938
Andy Hung4b17e882023-07-07 13:47:37 -070010939/* static */
10940sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
10941 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
10942 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
10943 return sp<MmapCaptureThread>::make(audioFlinger, id, hwDev, input, systemReady);
10944}
10945
10946MmapCaptureThread::MmapCaptureThread(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010947 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010948 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010949 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010950 mInput(input)
10951{
10952 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10953 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10954}
10955
Andy Hung4b17e882023-07-07 13:47:37 -070010956status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010957{
Phil Burkf054fc32018-12-06 09:45:59 -080010958 {
10959 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080010960 if (mInput != nullptr && mInput->stream != nullptr) {
10961 mInput->stream->setGain(1.0f);
10962 }
10963 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010964 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010965}
10966
Andy Hung4b17e882023-07-07 13:47:37 -070010967AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010968{
10969 Mutex::Autolock _l(mLock);
10970 AudioStreamIn *input = mInput;
10971 mInput = NULL;
10972 return input;
10973}
Kevin Rocard069c2712018-03-29 19:09:14 -070010974
Andy Hung4b17e882023-07-07 13:47:37 -070010975void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010976{
10977 bool changed = false;
10978 bool silenced = false;
10979
10980 sp<MmapStreamCallback> callback = mCallback.promote();
10981 if (callback == 0) {
10982 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10983 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10984 mNoCallbackWarningCount++;
10985 }
10986 }
10987
10988 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10989 // track is silenced and unmute otherwise
10990 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10991 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10992 changed = true;
10993 silenced = mActiveTracks[i]->isSilenced_l();
10994 }
10995 }
10996
10997 if (changed) {
10998 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10999 }
11000}
11001
Andy Hung4b17e882023-07-07 13:47:37 -070011002ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011003{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011004 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011005 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011006 }
11007 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011008 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011009 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011010 record_track_metadata_v7_t trackMetadata;
11011 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011012 .source = track->attributes().source,
11013 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011014 };
11015 trackMetadata.channel_mask = track->channelMask(),
11016 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11017 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011018 }
11019 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011020 MetadataUpdate change;
11021 change.recordMetadataUpdate = metadata.tracks;
11022 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011023}
11024
Andy Hung4b17e882023-07-07 13:47:37 -070011025void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011026{
11027 Mutex::Autolock _l(mLock);
11028 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011029 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011030 mActiveTracks[i]->setSilenced_l(silenced);
11031 broadcast_l();
11032 }
11033 }
jiabin09609032022-06-15 19:26:01 +000011034 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011035}
11036
Andy Hung4b17e882023-07-07 13:47:37 -070011037void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011038{
11039 MmapThread::toAudioPortConfig(config);
11040 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11041 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11042 config->flags.input = mInput->flags;
11043 }
11044}
11045
Andy Hung4b17e882023-07-07 13:47:37 -070011046status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011047 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011048{
11049 if (mInput == nullptr) {
11050 return NO_INIT;
11051 }
11052 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11053}
11054
jiabinc658e452022-10-21 20:52:21 +000011055// ----------------------------------------------------------------------------
11056
Andy Hung4b17e882023-07-07 13:47:37 -070011057/* static */
11058sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
11059 const sp<AudioFlinger>& audioflinger,
11060 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
11061 return sp<BitPerfectThread>::make(audioflinger, output, id, systemReady);
11062}
11063
11064BitPerfectThread::BitPerfectThread(const sp<AudioFlinger> &audioflinger,
jiabinc658e452022-10-21 20:52:21 +000011065 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
11066 : MixerThread(audioflinger, output, id, systemReady, BIT_PERFECT) {}
11067
Andy Hung4b17e882023-07-07 13:47:37 -070011068PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011069 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011070 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11071 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011072 float volumeLeft = 1.0f;
11073 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011074 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11075 const int trackId = mActiveTracks[0]->id();
11076 mAudioMixer->setParameter(
11077 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11078 mAudioMixer->setParameter(
11079 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11080 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011081 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011082 mIsBitPerfect = true;
11083 } else {
11084 mIsBitPerfect = false;
11085 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11086 // active.
11087 for (const auto& track : mActiveTracks) {
11088 const int trackId = track->id();
11089 mAudioMixer->setParameter(
11090 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11091 }
11092 }
jiabin76d94692022-12-15 21:51:21 +000011093 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11094 mVolumeLeft = volumeLeft;
11095 mVolumeRight = volumeRight;
11096 setVolumeForOutput_l(volumeLeft, volumeRight);
11097 }
jiabinc658e452022-10-21 20:52:21 +000011098 return result;
11099}
11100
Andy Hung4b17e882023-07-07 13:47:37 -070011101void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011102 MixerThread::threadLoop_mix();
11103 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11104}
11105
Glenn Kasten63238ef2015-03-02 15:50:29 -080011106} // namespace android