blob: 58a1acb736eb34aaf509d2bc19a8d2cafc67e016 [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
Andy Hung409572b2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
jiabin220eea12024-05-17 17:55:20 +000036#include <com_android_media_audioserver.h>
Andy Hung409572b2023-07-19 12:47:35 -070037#ifdef DEBUG_CPU_USAGE
38#include <audio_utils/Statistics.h>
39#include <cpustats/ThreadCpuUsage.h>
40#endif
41#include <audio_utils/channels.h>
42#include <audio_utils/format.h>
43#include <audio_utils/minifloat.h>
44#include <audio_utils/mono_blend.h>
45#include <audio_utils/primitives.h>
46#include <audio_utils/safe_math.h>
47#include <audiomanager/AudioManager.h>
48#include <binder/IPCThreadState.h>
49#include <binder/IServiceManager.h>
50#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010051#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070052#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053#include <cutils/properties.h>
Andy Hung409572b2023-07-19 12:47:35 -070054#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070055#include <media/AudioContainers.h>
56#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070057#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070058#include <media/AudioResamplerPublic.h>
Andy Hung409572b2023-07-19 12:47:35 -070059#ifdef ADD_BATTERY_DATA
60#include <media/IMediaPlayerService.h>
61#include <media/IMediaDeathNotifier.h>
62#endif
63#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080064#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070065#include <media/TypeConverter.h>
Andy Hung409572b2023-07-19 12:47:35 -070066#include <media/audiohal/EffectsFactoryHalInterface.h>
67#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070068#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069#include <media/nbaio/AudioStreamOutSink.h>
70#include <media/nbaio/MonoPipe.h>
71#include <media/nbaio/MonoPipeReader.h>
72#include <media/nbaio/Pipe.h>
73#include <media/nbaio/PipeReader.h>
74#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080075#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070076#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070077#include <mediautils/SchedulingPolicyService.h>
78#include <mediautils/ServiceUtilities.h>
Andy Hung409572b2023-07-19 12:47:35 -070079#include <powermanager/PowerManager.h>
80#include <private/android_filesystem_config.h>
81#include <private/media/AudioTrackShared.h>
82#include <system/audio_effects/effect_aec.h>
83#include <system/audio_effects/effect_downmix.h>
84#include <system/audio_effects/effect_ns.h>
85#include <system/audio_effects/effect_spatializer.h>
86#include <utils/Log.h>
87#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080088
Andy Hung409572b2023-07-19 12:47:35 -070089#include <fcntl.h>
90#include <linux/futex.h>
91#include <math.h>
92#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080093#include <pthread.h>
Andy Hung409572b2023-07-19 12:47:35 -070094#include <sstream>
95#include <string>
96#include <sys/stat.h>
97#include <sys/syscall.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
Andy Hung409572b2023-07-19 12:47:35 -0700129// Keep in sync with java definition in media/java/android/media/AudioRecord.java
130static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
131
Eric Laurent81784c32012-11-19 14:55:58 -0800132// retry counts for buffer fill timeout
133// 50 * ~20msecs = 1 second
134static const int8_t kMaxTrackRetries = 50;
135static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700136
Eric Laurent81784c32012-11-19 14:55:58 -0800137// allow less retry attempts on direct output thread.
138// direct outputs can be a scarce resource in audio hardware and should
139// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700140// Notes:
141// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
142// in case the data write is bursty for the AudioTrack. The application
143// should endeavor to write at least once every kMaxTrackRetriesDirectMs
144// to prevent an underrun situation. If the data is bursty, then
145// the application can also throttle the data sent to be even.
146// 2) For compressed audio data, any data present in the AudioTrack buffer
147// will be sent and reset the retry count. This delivers data as
148// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
149// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
150// of data to be available, then any remaining data is delivered.
151// This is required to ensure the last bit of data is delivered before underrun.
152//
153// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
154// or the size of the HAL period for proportional / linear PCM tracks.
155static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800156
157// don't warn about blocked writes or record buffer overflows more often than this
158static const nsecs_t kWarningThrottleNs = seconds(5);
159
160// RecordThread loop sleep time upon application overrun or audio HAL read error
161static const int kRecordThreadSleepUs = 5000;
162
Eric Laurent10351942014-05-08 18:49:52 -0700163// maximum time to wait in sendConfigEvent_l() for a status to be received
164static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800165
166// minimum sleep time for the mixer thread loop when tracks are active but in underrun
167static const uint32_t kMinThreadSleepTimeUs = 5000;
168// maximum divider applied to the active sleep time in the mixer thread loop
169static const uint32_t kMaxThreadSleepTimeShift = 2;
170
Andy Hung09a50072014-02-27 14:30:47 -0800171// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700172// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800173static const uint32_t kMinNormalSinkBufferSizeMs = 20;
174// maximum normal sink buffer size
175static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800176
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700177// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
178// FIXME This should be based on experimentally observed scheduling jitter
179static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
180
Eric Laurent972a1732013-09-04 09:42:59 -0700181// Offloaded output thread standby delay: allows track transition without going to standby
182static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
183
Eric Laurent51716182016-02-29 18:00:56 -0800184// Direct output thread minimum sleep time in idle or active(underrun) state
185static const nsecs_t kDirectMinSleepTimeUs = 10000;
186
Brian Lindahl65e90012022-07-27 18:01:07 +0200187// Minimum amount of time between checking to see if the timestamp is advancing
188// for underrun detection. If we check too frequently, we may not detect a
189// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800190static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200191
Glenn Kasten1b291842016-07-18 14:55:21 -0700192// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
193// balance between power consumption and latency, and allows threads to be scheduled reliably
194// by the CFS scheduler.
195// FIXME Express other hardcoded references to 20ms with references to this constant and move
196// it appropriately.
197#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800198
Eric Laurent81784c32012-11-19 14:55:58 -0800199// Whether to use fast mixer
200static const enum {
201 FastMixer_Never, // never initialize or use: for debugging only
202 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
203 // normal mixer multiplier is 1
204 FastMixer_Static, // initialize if needed, then use all the time if initialized,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
207 // multiplier is calculated based on min & max normal mixer buffer size
208 // FIXME for FastMixer_Dynamic:
209 // Supporting this option will require fixing HALs that can't handle large writes.
210 // For example, one HAL implementation returns an error from a large write,
211 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
212 // We could either fix the HAL implementations, or provide a wrapper that breaks
213 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
214} kUseFastMixer = FastMixer_Static;
215
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700216// Whether to use fast capture
217static const enum {
218 FastCapture_Never, // never initialize or use: for debugging only
219 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
220 FastCapture_Static, // initialize if needed, then use all the time if initialized
221} kUseFastCapture = FastCapture_Static;
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223// Priorities for requestPriority
224static const int kPriorityAudioApp = 2;
225static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700226static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000227// Request real-time priority for PlaybackThread in ARC
228static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800229
Glenn Kastenea38ee72016-04-18 11:08:01 -0700230// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
231// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
232// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700233
234// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800235static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800236
Glenn Kasten03490092014-05-27 12:30:54 -0700237// The minimum and maximum allowed values
238static const int kFastTrackMultiplierMin = 1;
239static const int kFastTrackMultiplierMax = 2;
240
241// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
242static int sFastTrackMultiplier = kFastTrackMultiplier;
243
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700244// See Thread::readOnlyHeap().
245// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
246// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
247// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700248static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700249
Andy Hung409572b2023-07-19 12:47:35 -0700250static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hungd58c4732023-07-20 21:31:38 -0700251
252static nsecs_t getStandbyTimeInNanos() {
253 static nsecs_t standbyTimeInNanos = []() {
254 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
255 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
256 ALOGI("%s: Using %d ms as standby time", __func__, ms);
257 return milliseconds(ms);
258 }();
259 return standbyTimeInNanos;
260}
261
Andy Hungd21a2ab2023-07-20 21:44:14 -0700262// Set kEnableExtendedChannels to true to enable greater than stereo output
263// for the MixerThread and device sink. Number of channels allowed is
264// FCC_2 <= channels <= FCC_LIMIT.
265constexpr bool kEnableExtendedChannels = true;
266
267// Returns true if channel mask is permitted for the PCM sink in the MixerThread
268/* static */
269bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
270 switch (audio_channel_mask_get_representation(channelMask)) {
271 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
272 // Haptic channel mask is only applicable for channel position mask.
273 const uint32_t channelCount = audio_channel_count_from_out_mask(
274 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
275 const uint32_t maxChannelCount = kEnableExtendedChannels
276 ? FCC_LIMIT : FCC_2;
277 if (channelCount < FCC_2 // mono is not supported at this time
278 || channelCount > maxChannelCount) {
279 return false;
280 }
281 // check that channelMask is the "canonical" one we expect for the channelCount.
282 return audio_channel_position_mask_is_out_canonical(channelMask);
283 }
284 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
285 if (kEnableExtendedChannels) {
286 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
287 if (channelCount >= FCC_2 // mono is not supported at this time
288 && channelCount <= FCC_LIMIT) {
289 return true;
290 }
291 }
292 return false;
293 default:
294 return false;
295 }
296}
297
298// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
299constexpr bool kEnableExtendedPrecision = true;
300
301// Returns true if format is permitted for the PCM sink in the MixerThread
302/* static */
303bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
304 switch (format) {
305 case AUDIO_FORMAT_PCM_16_BIT:
306 return true;
307 case AUDIO_FORMAT_PCM_FLOAT:
308 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
309 case AUDIO_FORMAT_PCM_32_BIT:
310 case AUDIO_FORMAT_PCM_8_24_BIT:
311 return kEnableExtendedPrecision;
312 default:
313 return false;
314 }
315}
316
Eric Laurent81784c32012-11-19 14:55:58 -0800317// ----------------------------------------------------------------------------
318
Andy Hung409572b2023-07-19 12:47:35 -0700319// formatToString() needs to be exact for MediaMetrics purposes.
320// Do not use media/TypeConverter.h toString().
321/* static */
322std::string IAfThreadBase::formatToString(audio_format_t format) {
323 std::string result;
324 FormatConverter::toString(format, result);
325 return result;
326}
327
Andy Hungb68f5eb2019-12-03 16:49:17 -0800328// TODO: move all toString helpers to audio.h
329// under #ifdef __cplusplus #endif
330static std::string patchSinksToString(const struct audio_patch *patch)
331{
332 std::stringstream ss;
333 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700334 if (i > 0) {
335 ss << "|";
336 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800337 ss << "(" << toString(patch->sinks[i].ext.device.type)
338 << ", " << patch->sinks[i].ext.device.address << ")";
339 }
340 return ss.str();
341}
342
343static std::string patchSourcesToString(const struct audio_patch *patch)
344{
345 std::stringstream ss;
346 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700347 if (i > 0) {
348 ss << "|";
349 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800350 ss << "(" << toString(patch->sources[i].ext.device.type)
351 << ", " << patch->sources[i].ext.device.address << ")";
352 }
353 return ss.str();
354}
355
Andy Hung4bd53e72022-11-17 17:21:45 -0800356static std::string toString(audio_latency_mode_t mode) {
357 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000358 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
359 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800360}
361
362// Could be made a template, but other toString overloads for std::vector are confused.
363static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
364 std::string s("{ ");
365 for (const auto& e : elements) {
366 s.append(toString(e));
367 s.append(" ");
368 }
369 s.append("}");
370 return s;
371}
372
Glenn Kasten03490092014-05-27 12:30:54 -0700373static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
374
375static void sFastTrackMultiplierInit()
376{
377 char value[PROPERTY_VALUE_MAX];
378 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
379 char *endptr;
380 unsigned long ul = strtoul(value, &endptr, 0);
381 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
382 sFastTrackMultiplier = (int) ul;
383 }
384 }
385}
386
387// ----------------------------------------------------------------------------
388
Eric Laurent81784c32012-11-19 14:55:58 -0800389#ifdef ADD_BATTERY_DATA
390// To collect the amplifier usage
391static void addBatteryData(uint32_t params) {
392 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
393 if (service == NULL) {
394 // it already logged
395 return;
396 }
397
398 service->addBatteryData(params);
399}
400#endif
401
Andy Hung3f0c9022016-01-15 17:49:46 -0800402// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
403struct {
404 // call when you acquire a partial wakelock
405 void acquire(const sp<IBinder> &wakeLockToken) {
406 pthread_mutex_lock(&mLock);
407 if (wakeLockToken.get() == nullptr) {
408 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
409 } else {
410 if (mCount == 0) {
411 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
412 }
413 ++mCount;
414 }
415 pthread_mutex_unlock(&mLock);
416 }
417
418 // call when you release a partial wakelock.
419 void release(const sp<IBinder> &wakeLockToken) {
420 if (wakeLockToken.get() == nullptr) {
421 return;
422 }
423 pthread_mutex_lock(&mLock);
424 if (--mCount < 0) {
425 ALOGE("negative wakelock count");
426 mCount = 0;
427 }
428 pthread_mutex_unlock(&mLock);
429 }
430
431 // retrieves the boottime timebase offset from monotonic.
432 int64_t getBoottimeOffset() {
433 pthread_mutex_lock(&mLock);
434 int64_t boottimeOffset = mBoottimeOffset;
435 pthread_mutex_unlock(&mLock);
436 return boottimeOffset;
437 }
438
439 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
440 // and the selected timebase.
441 // Currently only TIMEBASE_BOOTTIME is allowed.
442 //
443 // This only needs to be called upon acquiring the first partial wakelock
444 // after all other partial wakelocks are released.
445 //
446 // We do an empirical measurement of the offset rather than parsing
447 // /proc/timer_list since the latter is not a formal kernel ABI.
448 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
449 int clockbase;
450 switch (timebase) {
451 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
452 clockbase = SYSTEM_TIME_BOOTTIME;
453 break;
454 default:
455 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
456 break;
457 }
458 // try three times to get the clock offset, choose the one
459 // with the minimum gap in measurements.
460 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700461 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800462 for (int i = 0; i < tries; ++i) {
463 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
464 const nsecs_t tbase = systemTime(clockbase);
465 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
466 const nsecs_t gap = tmono2 - tmono;
467 if (i == 0 || gap < bestGap) {
468 bestGap = gap;
469 measured = tbase - ((tmono + tmono2) >> 1);
470 }
471 }
472
473 // to avoid micro-adjusting, we don't change the timebase
474 // unless it is significantly different.
475 //
476 // Assumption: It probably takes more than toleranceNs to
477 // suspend and resume the device.
478 static int64_t toleranceNs = 10000; // 10 us
479 if (llabs(*offset - measured) > toleranceNs) {
480 ALOGV("Adjusting timebase offset old: %lld new: %lld",
481 (long long)*offset, (long long)measured);
482 *offset = measured;
483 }
484 }
485
486 pthread_mutex_t mLock;
487 int32_t mCount;
488 int64_t mBoottimeOffset;
489} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800490
491// ----------------------------------------------------------------------------
492// CPU Stats
493// ----------------------------------------------------------------------------
494
495class CpuStats {
496public:
497 CpuStats();
498 void sample(const String8 &title);
499#ifdef DEBUG_CPU_USAGE
500private:
501 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700502 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800503
Andy Hung16698b82018-08-01 10:48:38 -0700504 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800505
506 int mCpuNum; // thread's current CPU number
507 int mCpukHz; // frequency of thread's current CPU in kHz
508#endif
509};
510
511CpuStats::CpuStats()
512#ifdef DEBUG_CPU_USAGE
513 : mCpuNum(-1), mCpukHz(-1)
514#endif
515{
516}
517
Glenn Kasten0f11b512014-01-31 16:18:54 -0800518void CpuStats::sample(const String8 &title
519#ifndef DEBUG_CPU_USAGE
520 __unused
521#endif
522 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800523#ifdef DEBUG_CPU_USAGE
524 // get current thread's delta CPU time in wall clock ns
525 double wcNs;
526 bool valid = mCpuUsage.sampleAndEnable(wcNs);
527
528 // record sample for wall clock statistics
529 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700530 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800531 }
532
533 // get the current CPU number
534 int cpuNum = sched_getcpu();
535
536 // get the current CPU frequency in kHz
537 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
538
539 // check if either CPU number or frequency changed
540 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
541 mCpuNum = cpuNum;
542 mCpukHz = cpukHz;
543 // ignore sample for purposes of cycles
544 valid = false;
545 }
546
547 // if no change in CPU number or frequency, then record sample for cycle statistics
548 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700549 const double cycles = wcNs * cpukHz * 0.000001;
550 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800551 }
552
Eric Tan5b13ff82018-07-27 11:20:17 -0700553 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800554 // mCpuUsage.elapsed() is expensive, so don't call it every loop
555 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700556 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800557 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700558 const double perLoop = elapsed / (double) n;
559 const double perLoop100 = perLoop * 0.01;
560 const double perLoop1k = perLoop * 0.001;
561 const double mean = mWcStats.getMean();
562 const double stddev = mWcStats.getStdDev();
563 const double minimum = mWcStats.getMin();
564 const double maximum = mWcStats.getMax();
565 const double meanCycles = mHzStats.getMean();
566 const double stddevCycles = mHzStats.getStdDev();
567 const double minCycles = mHzStats.getMin();
568 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800569 mCpuUsage.resetElapsed();
570 mWcStats.reset();
571 mHzStats.reset();
572 ALOGD("CPU usage for %s over past %.1f secs\n"
573 " (%u mixer loops at %.1f mean ms per loop):\n"
574 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
575 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
576 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000577 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800578 elapsed * .000000001, n, perLoop * .000001,
579 mean * .001,
580 stddev * .001,
581 minimum * .001,
582 maximum * .001,
583 mean / perLoop100,
584 stddev / perLoop100,
585 minimum / perLoop100,
586 maximum / perLoop100,
587 meanCycles / perLoop1k,
588 stddevCycles / perLoop1k,
589 minCycles / perLoop1k,
590 maxCycles / perLoop1k);
591
592 }
593 }
594#endif
595};
596
597// ----------------------------------------------------------------------------
598// ThreadBase
599// ----------------------------------------------------------------------------
600
Glenn Kasten97b7b752014-09-28 13:04:24 -0700601// static
Andy Hung4b17e882023-07-07 13:47:37 -0700602const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700603{
604 switch (type) {
605 case MIXER:
606 return "MIXER";
607 case DIRECT:
608 return "DIRECT";
609 case DUPLICATING:
610 return "DUPLICATING";
611 case RECORD:
612 return "RECORD";
613 case OFFLOAD:
614 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700615 case MMAP_PLAYBACK:
616 return "MMAP_PLAYBACK";
617 case MMAP_CAPTURE:
618 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200619 case SPATIALIZER:
620 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000621 case BIT_PERFECT:
622 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700623 default:
624 return "unknown";
625 }
626}
627
Andy Hung7535ed92023-07-17 17:05:00 -0700628ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700629 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800630 : Thread(false /*canCallJava*/),
631 mType(type),
Andy Hung7535ed92023-07-17 17:05:00 -0700632 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700633 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
634 isOut),
635 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700636 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800637 // are set by PlaybackThread::readOutputParameters_l() or
638 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700639 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700640 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700641 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800642 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700643 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800644 mSystemReady(systemReady),
645 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800646{
Andy Hungcf10d742020-04-28 15:38:24 -0700647 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700648 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800649}
650
Andy Hung4b17e882023-07-07 13:47:37 -0700651ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800652{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700653 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700654 mConfigEvents.clear();
655
Eric Laurent81784c32012-11-19 14:55:58 -0800656 // do not lock the mutex in destructor
657 releaseWakeLock_l();
658 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800659 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800660 binder->unlinkToDeath(mDeathRecipient);
661 }
Andy Hungd0979812019-02-21 15:51:44 -0800662
663 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800664}
665
Andy Hung4b17e882023-07-07 13:47:37 -0700666status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700667{
668 status_t status = initCheck();
669 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800670 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700671 } else {
672 ALOGE("No working audio driver found.");
673 }
674 return status;
675}
676
Andy Hung4b17e882023-07-07 13:47:37 -0700677void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800678{
679 ALOGV("ThreadBase::exit");
680 // do any cleanup required for exit to succeed
681 preExit();
682 {
683 // This lock prevents the following race in thread (uniprocessor for illustration):
684 // if (!exitPending()) {
685 // // context switch from here to exit()
686 // // exit() calls requestExit(), what exitPending() observes
687 // // exit() calls signal(), which is dropped since no waiters
688 // // context switch back from exit() to here
689 // mWaitWorkCV.wait(...);
690 // // now thread is hung
691 // }
Andy Hungb17d24b2023-08-29 14:26:09 -0700692 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800693 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -0700694 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800695 }
696 // When Thread::requestExitAndWait is made virtual and this method is renamed to
697 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hungef2096d2024-03-21 19:43:05 -0700698
699 // For TimeCheck: track waiting on the thread join of getTid().
700 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
701
Eric Laurent81784c32012-11-19 14:55:58 -0800702 requestExitAndWait();
703}
704
Andy Hung4b17e882023-07-07 13:47:37 -0700705status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800706{
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000707 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hungf8635b62023-08-31 16:13:39 -0700708 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800709
Eric Laurent10351942014-05-08 18:49:52 -0700710 return sendSetParameterConfigEvent_l(keyValuePairs);
711}
712
713// sendConfigEvent_l() must be called with ThreadBase::mLock held
714// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hung4b17e882023-07-07 13:47:37 -0700715status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700716NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700717{
718 status_t status = NO_ERROR;
719
Eric Laurent72e3f392015-05-20 14:43:50 -0700720 if (event->mRequiresSystemReady && !mSystemReady) {
721 event->mWaitStatus = false;
722 mPendingConfigEvents.add(event);
723 return status;
724 }
Eric Laurent10351942014-05-08 18:49:52 -0700725 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700726 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungb17d24b2023-08-29 14:26:09 -0700727 mWaitWorkCV.notify_one();
728 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700729 {
Andy Hungb17d24b2023-08-29 14:26:09 -0700730 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700731 while (event->mWaitStatus) {
Andy Hung5529c132024-01-25 17:02:30 -0800732 if (event->mCondition.wait_for(
733 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
734 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700735 event->mStatus = TIMED_OUT;
736 event->mWaitStatus = false;
737 }
738 }
739 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Andy Hungb17d24b2023-08-29 14:26:09 -0700741 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800742 return status;
743}
744
Andy Hung4b17e882023-07-07 13:47:37 -0700745void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700746 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800747{
Andy Hungf8635b62023-08-31 16:13:39 -0700748 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700749 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800750}
751
Andy Hungb17d24b2023-08-29 14:26:09 -0700752// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700753void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700754 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800755{
Andy Hungd0979812019-02-21 15:51:44 -0800756 // The audio statistics history is exponentially weighted to forget events
757 // about five or more seconds in the past. In order to have
758 // crisper statistics for mediametrics, we reset the statistics on
759 // an IoConfigEvent, to reflect different properties for a new device.
760 mIoJitterMs.reset();
761 mLatencyMs.reset();
762 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000763 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100764 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800765
Eric Laurent09f1ed22019-04-24 17:45:17 -0700766 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700767 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800768}
769
Andy Hung4b17e882023-07-07 13:47:37 -0700770void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700771{
Andy Hungf8635b62023-08-31 16:13:39 -0700772 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800773 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700774}
775
Andy Hungb17d24b2023-08-29 14:26:09 -0700776// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700777void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800778 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800779{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800780 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700781 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800782}
783
Andy Hungb17d24b2023-08-29 14:26:09 -0700784// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -0700785status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800786{
Andy Hung2ddee192015-12-18 17:34:44 -0800787 sp<ConfigEvent> configEvent;
788 AudioParameter param(keyValuePair);
789 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700790 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800791 setMasterMono_l(value != 0);
792 if (param.size() == 1) {
793 return NO_ERROR; // should be a solo parameter - we don't pass down
794 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700795 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800796 configEvent = new SetParameterConfigEvent(param.toString());
797 } else {
798 configEvent = new SetParameterConfigEvent(keyValuePair);
799 }
Eric Laurent10351942014-05-08 18:49:52 -0700800 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700801}
802
Andy Hung4b17e882023-07-07 13:47:37 -0700803status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700804 const struct audio_patch *patch,
805 audio_patch_handle_t *handle)
806{
Andy Hungf8635b62023-08-31 16:13:39 -0700807 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700808 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
809 status_t status = sendConfigEvent_l(configEvent);
810 if (status == NO_ERROR) {
811 CreateAudioPatchConfigEventData *data =
812 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
813 *handle = data->mHandle;
814 }
815 return status;
816}
817
Andy Hung4b17e882023-07-07 13:47:37 -0700818status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700819 const audio_patch_handle_t handle)
820{
Andy Hungf8635b62023-08-31 16:13:39 -0700821 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700822 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
823 return sendConfigEvent_l(configEvent);
824}
825
Andy Hung4b17e882023-07-07 13:47:37 -0700826status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700827 const DeviceDescriptorBaseVector& outDevices)
828{
829 if (type() != RECORD) {
830 // The update out device operation is only for record thread.
831 return INVALID_OPERATION;
832 }
Andy Hungf8635b62023-08-31 16:13:39 -0700833 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700834 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
835 return sendConfigEvent_l(configEvent);
836}
837
Andy Hung4b17e882023-07-07 13:47:37 -0700838void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200839{
840 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
841 sp<ConfigEvent> configEvent =
842 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
843 sendConfigEvent_l(configEvent);
844}
Eric Laurent1c333e22014-05-20 10:48:17 -0700845
Andy Hung4b17e882023-07-07 13:47:37 -0700846void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200847{
Andy Hungf8635b62023-08-31 16:13:39 -0700848 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200849 sendCheckOutputStageEffectsEvent_l();
850}
851
Andy Hung4b17e882023-07-07 13:47:37 -0700852void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200853{
854 sp<ConfigEvent> configEvent =
855 (ConfigEvent *)new CheckOutputStageEffectsEvent();
856 sendConfigEvent_l(configEvent);
857}
858
Andy Hung4b17e882023-07-07 13:47:37 -0700859void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200860{
861 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
862 sendConfigEvent_l(configEvent);
863}
864
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700865// post condition: mConfigEvents.isEmpty()
Andy Hung4b17e882023-07-07 13:47:37 -0700866void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700867{
Eric Laurent10351942014-05-08 18:49:52 -0700868 bool configChanged = false;
869
Eric Laurent81784c32012-11-19 14:55:58 -0800870 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700871 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700872 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800873 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700874 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700875 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700876 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
877 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800878 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700879 true /*asynchronous*/);
880 if (err != 0) {
881 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700882 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700883 }
884 } break;
885 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700886 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hung94dfbb42023-09-06 19:41:47 -0700887 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700888 } break;
889 case CFG_EVENT_SET_PARAMETER: {
890 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
891 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
892 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700893 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000894 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700895 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700896 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700897 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700898 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700899 CreateAudioPatchConfigEventData *data =
900 (CreateAudioPatchConfigEventData *)event->mData.get();
901 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700902 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200903 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700904 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
905 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
906 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700907 } break;
908 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung94dfbb42023-09-06 19:41:47 -0700909 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700910 ReleaseAudioPatchConfigEventData *data =
911 (ReleaseAudioPatchConfigEventData *)event->mData.get();
912 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung94dfbb42023-09-06 19:41:47 -0700913 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200914 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700915 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
916 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
917 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
918 } break;
919 case CFG_EVENT_UPDATE_OUT_DEVICE: {
920 UpdateOutDevicesConfigEventData *data =
921 (UpdateOutDevicesConfigEventData *)event->mData.get();
922 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700923 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200924 case CFG_EVENT_RESIZE_BUFFER: {
925 ResizeBufferConfigEventData *data =
926 (ResizeBufferConfigEventData *)event->mData.get();
927 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
928 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200929
930 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
931 setCheckOutputStageEffects();
932 } break;
933
Eric Laurent68a40a82022-05-03 18:15:04 +0200934 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
935 onHalLatencyModesChanged_l();
936 } break;
937
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700938 default:
Eric Laurent10351942014-05-08 18:49:52 -0700939 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700940 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800941 }
Eric Laurent10351942014-05-08 18:49:52 -0700942 {
Andy Hungf8635b62023-08-31 16:13:39 -0700943 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700944 if (event->mWaitStatus) {
945 event->mWaitStatus = false;
Andy Hungb17d24b2023-08-29 14:26:09 -0700946 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700947 }
948 }
949 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
950 }
951
952 if (configChanged) {
953 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800954 }
Eric Laurent81784c32012-11-19 14:55:58 -0800955}
956
Marco Nelissenb2208842014-02-07 14:00:50 -0800957String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
958 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700959 const audio_channel_representation_t representation =
960 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700961
962 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800963 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700964 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
965 if (output) {
966 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
967 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
968 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700969 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700970 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
971 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
972 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
973 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
974 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
975 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
976 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
978 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
981 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700982 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
983 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
984 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
985 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
986 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
987 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
988 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700989 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700990 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
991 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700992 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
993 } else {
994 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
995 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
996 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
997 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
998 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
999 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1000 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1001 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1002 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1003 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1004 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1005 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001006 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1007 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1008 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001009 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001010 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1011 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001012 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1013 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1014 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1015 }
1016 const int len = s.length();
1017 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001018 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001019 s.unlockBuffer(len - 2); // remove trailing ", "
1020 }
1021 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001022 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001023 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1024 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1025 return s;
1026 default:
1027 s.appendFormat("unknown mask, representation:%d bits:%#x",
1028 representation, audio_channel_mask_get_bits(mask));
1029 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001030 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001031}
1032
Andy Hung4b17e882023-07-07 13:47:37 -07001033void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001034NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001035{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001036 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1037 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1038
Andy Hungb17d24b2023-08-29 14:26:09 -07001039 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001040 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001041 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001042 }
1043
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001044 dumpBase_l(fd, args);
1045 dumpInternals_l(fd, args);
1046 dumpTracks_l(fd, args);
1047 dumpEffectChains_l(fd, args);
1048
1049 if (locked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001050 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001051 }
1052
1053 dprintf(fd, " Local log:\n");
1054 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001055
1056 // --all does the statistics
1057 bool dumpAll = false;
1058 for (const auto &arg : args) {
1059 if (arg == String16("--all")) {
1060 dumpAll = true;
1061 }
1062 }
1063 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001064 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001065 if (!sched.empty()) {
1066 (void)write(fd, sched.c_str(), sched.size());
1067 }
1068 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001069}
1070
Andy Hung4b17e882023-07-07 13:47:37 -07001071void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001072{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001073 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001074 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001075 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001076 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung409572b2023-07-19 12:47:35 -07001077 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1078 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001079 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001080 dprintf(fd, " Channel count: %u\n", mChannelCount);
1081 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00001082 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung409572b2023-07-19 12:47:35 -07001083 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1084 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001085 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001086 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001087 size_t numConfig = mConfigEvents.size();
1088 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001089 const size_t SIZE = 256;
1090 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001091 for (size_t i = 0; i < numConfig; i++) {
1092 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001093 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001094 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001095 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001096 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001097 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001098 }
Andy Hung293558a2017-03-21 12:19:20 -07001099 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001100 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001101 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001102 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hung94dfbb42023-09-06 19:41:47 -07001103 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001104 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001105
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001106 // Dump timestamp statistics for the Thread types that support it.
1107 if (mType == RECORD
1108 || mType == MIXER
1109 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001110 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001111 || mType == OFFLOAD
1112 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001113 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hung94dfbb42023-09-06 19:41:47 -07001114 dprintf(fd, " Timestamp corrected: %s\n",
1115 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001116 }
1117
Andy Hung446f4df2019-02-21 12:26:41 -08001118 if (mLastIoBeginNs > 0) { // MMAP may not set this
1119 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1120 isOutput() ? "write" : "read",
1121 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1122 }
1123
1124 if (mProcessTimeMs.getN() > 0) {
1125 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1126 }
1127
1128 if (mIoJitterMs.getN() > 0) {
1129 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1130 isOutput() ? "write" : "read",
1131 mIoJitterMs.toString().c_str());
1132 }
1133
Andy Hunge6c37112019-02-26 17:38:10 -08001134 if (mLatencyMs.getN() > 0) {
1135 dprintf(fd, " Threadloop %s latency stats: %s\n",
1136 isOutput() ? "write" : "read",
1137 mLatencyMs.toString().c_str());
1138 }
Robert Wu06db0a32021-08-10 19:05:34 +00001139
1140 if (mMonopipePipeDepthStats.getN() > 0) {
1141 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1142 isOutput() ? "write" : "read",
1143 mMonopipePipeDepthStats.toString().c_str());
1144 }
Eric Laurent81784c32012-11-19 14:55:58 -08001145}
1146
Andy Hung4b17e882023-07-07 13:47:37 -07001147void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001148{
1149 const size_t SIZE = 256;
1150 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001151
Marco Nelissenb2208842014-02-07 14:00:50 -08001152 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001153 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001154 write(fd, buffer, strlen(buffer));
1155
Marco Nelissenb2208842014-02-07 14:00:50 -08001156 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001157 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001158 if (chain != 0) {
1159 chain->dump(fd, args);
1160 }
1161 }
1162}
1163
Andy Hung4b17e882023-07-07 13:47:37 -07001164void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001165{
Andy Hungf8635b62023-08-31 16:13:39 -07001166 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001167 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001168}
1169
Andy Hung4b17e882023-07-07 13:47:37 -07001170String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001171{
1172 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001173 case MIXER:
1174 return String16("AudioMix");
1175 case DIRECT:
1176 return String16("AudioDirectOut");
1177 case DUPLICATING:
1178 return String16("AudioDup");
1179 case RECORD:
1180 return String16("AudioIn");
1181 case OFFLOAD:
1182 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001183 case MMAP_PLAYBACK:
1184 return String16("MmapPlayback");
1185 case MMAP_CAPTURE:
1186 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001187 case SPATIALIZER:
1188 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001189 default:
1190 ALOG_ASSERT(false);
1191 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001192 }
1193}
1194
Andy Hung4b17e882023-07-07 13:47:37 -07001195void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001196{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001197 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001198 if (mPowerManager != 0) {
1199 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001200 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001201 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1202 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001203 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001204 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001205 {} /* workSource */,
1206 {} /* historyTag */);
1207 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001208 mWakeLockToken = binder;
1209 }
Chris Ye6597d732020-02-28 22:38:25 -08001210 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001211 }
Wei Jia3f273d12015-11-24 09:06:49 -08001212
Andy Hung3f0c9022016-01-15 17:49:46 -08001213 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001214 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1215 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001216}
1217
Andy Hung4b17e882023-07-07 13:47:37 -07001218void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001219{
Andy Hungf8635b62023-08-31 16:13:39 -07001220 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001221 releaseWakeLock_l();
1222}
1223
Andy Hung4b17e882023-07-07 13:47:37 -07001224void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001225{
Andy Hung3f0c9022016-01-15 17:49:46 -08001226 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001227 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001228 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001229 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001230 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001231 }
1232 mWakeLockToken.clear();
1233 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001234}
1235
Andy Hung4b17e882023-07-07 13:47:37 -07001236void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001237 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001238 // use checkService() to avoid blocking if power service is not up yet
1239 sp<IBinder> binder =
1240 defaultServiceManager()->checkService(String16("power"));
1241 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001242 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001243 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001244 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001245 binder->linkToDeath(mDeathRecipient);
1246 }
1247 }
1248}
1249
Andy Hung4b17e882023-07-07 13:47:37 -07001250void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001251 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001252
1253#if !LOG_NDEBUG
1254 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001255 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001256 s << uid << " ";
1257 }
1258 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1259#endif
1260
Andy Hung438e7572015-12-14 15:51:17 -08001261 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1262 if (mSystemReady) {
1263 ALOGE("no wake lock to update, but system ready!");
1264 } else {
1265 ALOGW("no wake lock to update, system not ready yet");
1266 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001267 return;
1268 }
1269 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001270 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001271 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1272 mWakeLockToken, uidsAsInt);
1273 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001274 }
1275}
1276
Andy Hung4b17e882023-07-07 13:47:37 -07001277void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001278{
Andy Hungf8635b62023-08-31 16:13:39 -07001279 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001280 releaseWakeLock_l();
1281 mPowerManager.clear();
1282}
1283
Andy Hung4b17e882023-07-07 13:47:37 -07001284void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001285 const DeviceDescriptorBaseVector& outDevices __unused)
1286{
1287 ALOGE("%s should only be called in RecordThread", __func__);
1288}
1289
Andy Hung4b17e882023-07-07 13:47:37 -07001290void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001291{
1292 ALOGE("%s should only be called in RecordThread", __func__);
1293}
1294
Andy Hung4b17e882023-07-07 13:47:37 -07001295void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001296{
1297 sp<ThreadBase> thread = mThread.promote();
1298 if (thread != 0) {
1299 thread->clearPowerManager();
1300 }
1301 ALOGW("power manager service died !!!");
1302}
1303
Andy Hung4b17e882023-07-07 13:47:37 -07001304void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001305 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001306{
Andy Hung116bc262023-06-20 18:56:17 -07001307 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001308 if (chain != 0) {
1309 if (type != NULL) {
1310 chain->setEffectSuspended_l(type, suspend);
1311 } else {
1312 chain->setEffectSuspendedAll_l(suspend);
1313 }
1314 }
1315
1316 updateSuspendedSessions_l(type, suspend, sessionId);
1317}
1318
Andy Hung4b17e882023-07-07 13:47:37 -07001319void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001320{
1321 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1322 if (index < 0) {
1323 return;
1324 }
1325
1326 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1327 mSuspendedSessions.valueAt(index);
1328
1329 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001330 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001331 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001332 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001333 chain->setEffectSuspendedAll_l(true);
1334 } else {
1335 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1336 desc->mType.timeLow);
1337 chain->setEffectSuspended_l(&desc->mType, true);
1338 }
1339 }
1340 }
1341}
1342
Andy Hung4b17e882023-07-07 13:47:37 -07001343void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001344 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001345 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001346{
1347 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1348
1349 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1350
1351 if (suspend) {
1352 if (index >= 0) {
1353 sessionEffects = mSuspendedSessions.valueAt(index);
1354 } else {
1355 mSuspendedSessions.add(sessionId, sessionEffects);
1356 }
1357 } else {
1358 if (index < 0) {
1359 return;
1360 }
1361 sessionEffects = mSuspendedSessions.valueAt(index);
1362 }
1363
1364
Andy Hung116bc262023-06-20 18:56:17 -07001365 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001366 if (type != NULL) {
1367 key = type->timeLow;
1368 }
1369 index = sessionEffects.indexOfKey(key);
1370
1371 sp<SuspendedSessionDesc> desc;
1372 if (suspend) {
1373 if (index >= 0) {
1374 desc = sessionEffects.valueAt(index);
1375 } else {
1376 desc = new SuspendedSessionDesc();
1377 if (type != NULL) {
1378 desc->mType = *type;
1379 }
1380 sessionEffects.add(key, desc);
1381 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1382 }
1383 desc->mRefCount++;
1384 } else {
1385 if (index < 0) {
1386 return;
1387 }
1388 desc = sessionEffects.valueAt(index);
1389 if (--desc->mRefCount == 0) {
1390 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1391 sessionEffects.removeItemsAt(index);
1392 if (sessionEffects.isEmpty()) {
1393 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1394 sessionId);
1395 mSuspendedSessions.removeItem(sessionId);
1396 }
1397 }
1398 }
1399 if (!sessionEffects.isEmpty()) {
1400 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1401 }
1402}
1403
Andy Hung4b17e882023-07-07 13:47:37 -07001404void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001405 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001406 bool threadLocked)
1407NO_THREAD_SAFETY_ANALYSIS // manual locking
1408{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001409 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001410 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001411 }
Eric Laurent81784c32012-11-19 14:55:58 -08001412
Eric Laurent81784c32012-11-19 14:55:58 -08001413 if (mType != RECORD) {
1414 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1415 // another session. This gives the priority to well behaved effect control panels
1416 // and applications not using global effects.
1417 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1418 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001419 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001420 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1421 }
1422 }
1423
Eric Laurent6b446ce2019-12-13 10:56:31 -08001424 if (!threadLocked) {
Andy Hungb17d24b2023-08-29 14:26:09 -07001425 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001426 }
1427}
1428
Andy Hungb17d24b2023-08-29 14:26:09 -07001429// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001430status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001431 const effect_descriptor_t *desc, audio_session_t sessionId)
1432{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001433 // No global output effect sessions on record threads
1434 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1435 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001436 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1437 desc->name, mThreadName);
1438 return BAD_VALUE;
1439 }
1440 // only pre processing effects on record thread
1441 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1442 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1443 desc->name, mThreadName);
1444 return BAD_VALUE;
1445 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001446
1447 // always allow effects without processing load or latency
1448 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1449 return NO_ERROR;
1450 }
1451
Eric Laurent4c415062016-06-17 16:14:16 -07001452 audio_input_flags_t flags = mInput->flags;
1453 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1454 if (flags & AUDIO_INPUT_FLAG_RAW) {
1455 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1456 desc->name, mThreadName);
1457 return BAD_VALUE;
1458 }
1459 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1460 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1461 desc->name, mThreadName);
1462 return BAD_VALUE;
1463 }
1464 }
jiabineb3bda02020-06-30 14:07:03 -07001465
Andy Hung116bc262023-06-20 18:56:17 -07001466 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001467 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1468 return BAD_VALUE;
1469 }
Eric Laurent4c415062016-06-17 16:14:16 -07001470 return NO_ERROR;
1471}
1472
Andy Hungb17d24b2023-08-29 14:26:09 -07001473// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001474status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001475 const effect_descriptor_t *desc, audio_session_t sessionId)
1476{
1477 // no preprocessing on playback threads
1478 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001479 ALOGW("%s: pre processing effect %s created on playback"
1480 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001481 return BAD_VALUE;
1482 }
1483
Eric Laurent3e4de772017-07-16 16:55:08 -07001484 // always allow effects without processing load or latency
1485 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1486 return NO_ERROR;
1487 }
1488
Andy Hung116bc262023-06-20 18:56:17 -07001489 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001490 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1491 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001492 return BAD_VALUE;
1493 }
1494
Eric Laurent4eb45d02023-12-20 12:07:17 +01001495 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001496 && mType != SPATIALIZER) {
1497 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1498 __func__, mType);
1499 return BAD_VALUE;
1500 }
1501
Eric Laurent4c415062016-06-17 16:14:16 -07001502 switch (mType) {
1503 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001504 audio_output_flags_t flags = mOutput->flags;
1505 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1506 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1507 // global effects are applied only to non fast tracks if they are SW
1508 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1509 break;
1510 }
1511 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1512 // only post processing on output stage session
1513 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001514 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1515 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001516 return BAD_VALUE;
1517 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001518 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1519 // only post processing on output stage session
1520 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001521 ALOGW("%s: non post processing effect %s not allowed on device session",
1522 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001523 return BAD_VALUE;
1524 }
Eric Laurent4c415062016-06-17 16:14:16 -07001525 } else {
1526 // no restriction on effects applied on non fast tracks
1527 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1528 break;
1529 }
1530 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001531
Eric Laurent4c415062016-06-17 16:14:16 -07001532 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001533 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001534 return BAD_VALUE;
1535 }
1536 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001537 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1538 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001539 return BAD_VALUE;
1540 }
1541 }
1542 } break;
1543 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001544 // nothing actionable on offload threads, if the effect:
1545 // - is offloadable: the effect can be created
1546 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1547 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001548 break;
1549 case DIRECT:
1550 // Reject any effect on Direct output threads for now, since the format of
1551 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001552 ALOGW("%s: effect %s on DIRECT output thread %s",
1553 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001554 return BAD_VALUE;
1555 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001556 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001557 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1558 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001559 return BAD_VALUE;
1560 }
1561 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001562 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1563 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001564 return BAD_VALUE;
1565 }
1566 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001567 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1568 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001569 return BAD_VALUE;
1570 }
1571 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001572 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001573 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1574 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1575 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1576 // are supported and added after the spatializer.
1577 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1578 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1579 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001580 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001581 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1582 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001583 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001584 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1585 break;
1586 }
1587 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1588 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1589 __func__, desc->name);
1590 return BAD_VALUE;
1591 }
1592 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1593 // only post processing on output stage session
1594 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1595 ALOGW("%s: non post processing effect %s not allowed on device session",
1596 __func__, desc->name);
1597 return BAD_VALUE;
1598 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001599 }
1600 break;
jiabinc658e452022-10-21 20:52:21 +00001601 case BIT_PERFECT:
1602 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1603 // Allow HW accelerated effects of tunnel type
1604 break;
1605 }
1606 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1607 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1608 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1609 // 3) there is any bit-perfect track with the given session id.
1610 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1611 sessionId == AUDIO_SESSION_DEVICE) {
1612 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1613 __func__, desc->name, mThreadName);
1614 return BAD_VALUE;
1615 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1616 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1617 __func__, desc->name, sessionId);
1618 return BAD_VALUE;
1619 }
1620 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001621 default:
1622 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1623 }
1624
1625 return NO_ERROR;
1626}
1627
Andy Hungb17d24b2023-08-29 14:26:09 -07001628// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07001629sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001630 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001631 const sp<IEffectClient>& effectClient,
1632 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001633 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001634 effect_descriptor_t *desc,
1635 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001636 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001637 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001638 bool probe,
1639 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001640{
Andy Hung116bc262023-06-20 18:56:17 -07001641 sp<IAfEffectModule> effect;
1642 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001643 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001644 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001645 bool chainCreated = false;
1646 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001647 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001648
1649 lStatus = initCheck();
1650 if (lStatus != NO_ERROR) {
1651 ALOGW("createEffect_l() Audio driver not initialized.");
1652 goto Exit;
1653 }
1654
Eric Laurent81784c32012-11-19 14:55:58 -08001655 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1656
Andy Hungb17d24b2023-08-29 14:26:09 -07001657 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07001658 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001659
Eric Laurent4c415062016-06-17 16:14:16 -07001660 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001661 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001662 goto Exit;
1663 }
1664
Eric Laurent81784c32012-11-19 14:55:58 -08001665 // check for existing effect chain with the requested audio session
1666 chain = getEffectChain_l(sessionId);
1667 if (chain == 0) {
1668 // create a new chain for this session
1669 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001670 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001671 addEffectChain_l(chain);
1672 chain->setStrategy(getStrategyForSession_l(sessionId));
1673 chainCreated = true;
1674 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001675 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001676 }
1677
1678 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1679
1680 if (effect == 0) {
Andy Hung7535ed92023-07-17 17:05:00 -07001681 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001682 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001683 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001684 if (lStatus != NO_ERROR) {
1685 goto Exit;
1686 }
1687 effectCreated = true;
1688
jiabinc52b1ff2019-10-31 17:20:42 -07001689 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001690 effect->setDevices(outDeviceTypeAddrs());
1691 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001692 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001693 effect->setAudioSource(mAudioSource);
1694 }
jiabin1319f5a2021-03-30 22:21:24 +00001695 if (effect->isHapticGenerator()) {
1696 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1697 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001698 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001699 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001700 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001701 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001702 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001703 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001704 }
1705 }
Eric Laurent81784c32012-11-19 14:55:58 -08001706 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001707 handle = IAfEffectHandle::create(
1708 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001709 lStatus = handle->initCheck();
1710 if (lStatus == OK) {
1711 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001712 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001713 }
Eric Laurent81784c32012-11-19 14:55:58 -08001714 if (enabled != NULL) {
1715 *enabled = (int)effect->isEnabled();
1716 }
1717 }
1718
1719Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001720 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hungf8635b62023-08-31 16:13:39 -07001721 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001722 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001723 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001724 }
Eric Laurent81784c32012-11-19 14:55:58 -08001725 if (chainCreated) {
1726 removeEffectChain_l(chain);
1727 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001728 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001729 }
1730
Glenn Kasten9156ef32013-08-06 15:39:08 -07001731 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001732 return handle;
1733}
1734
Andy Hung4b17e882023-07-07 13:47:37 -07001735void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001736 bool unpinIfLast)
1737{
1738 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001739 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001740 {
Andy Hungf8635b62023-08-31 16:13:39 -07001741 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001742 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001743 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001744 return;
1745 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001746 effect = effectBase->asEffectModule();
1747 if (effect == nullptr) {
1748 return;
1749 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 // restore suspended effects if the disconnected handle was enabled and the last one.
1751 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1752 if (remove) {
1753 removeEffect_l(effect, true);
1754 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001755 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001756 }
1757 if (remove) {
Andy Hung7535ed92023-07-17 17:05:00 -07001758 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001759 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001760 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001761 }
1762 }
1763}
1764
Andy Hung4b17e882023-07-07 13:47:37 -07001765void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001766 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001767 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001768 broadcast_l();
1769 }
1770 if (!effect->isOffloadable()) {
1771 if (mType == ThreadBase::OFFLOAD) {
1772 PlaybackThread *t = (PlaybackThread *)this;
1773 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1774 }
1775 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung7535ed92023-07-17 17:05:00 -07001776 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001777 }
1778 }
1779}
1780
Andy Hung4b17e882023-07-07 13:47:37 -07001781void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001782 if (isOffloadOrMmap()) {
Andy Hungf8635b62023-08-31 16:13:39 -07001783 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001784 broadcast_l();
1785 }
1786}
1787
Andy Hung4b17e882023-07-07 13:47:37 -07001788sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001789 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001790{
Andy Hungf8635b62023-08-31 16:13:39 -07001791 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001792 return getEffect_l(sessionId, effectId);
1793}
1794
Andy Hung4b17e882023-07-07 13:47:37 -07001795sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung3e4c8742023-06-29 21:19:25 -07001796 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001797{
Andy Hung116bc262023-06-20 18:56:17 -07001798 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001799 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1800}
1801
Andy Hung4b17e882023-07-07 13:47:37 -07001802std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001803{
Andy Hung116bc262023-06-20 18:56:17 -07001804 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001805 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001806}
1807
Andy Hungf8635b62023-08-31 16:13:39 -07001808// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1809// ThreadBase::mutex() held
1810status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001811{
1812 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001813 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001814 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001815 bool chainCreated = false;
1816
Eric Laurent5baf2af2013-09-12 17:37:00 -07001817 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hungf8635b62023-08-31 16:13:39 -07001818 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1819 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001820
Eric Laurent81784c32012-11-19 14:55:58 -08001821 if (chain == 0) {
1822 // create a new chain for this session
Andy Hungf8635b62023-08-31 16:13:39 -07001823 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001824 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001825 addEffectChain_l(chain);
1826 chain->setStrategy(getStrategyForSession_l(sessionId));
1827 chainCreated = true;
1828 }
Andy Hungf8635b62023-08-31 16:13:39 -07001829 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001830
1831 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hungf8635b62023-08-31 16:13:39 -07001832 ALOGW("%s: %p effect %s already present in chain %p",
1833 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001834 return BAD_VALUE;
1835 }
1836
Shunkai Yaod125e402024-01-20 03:19:06 +00001837 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001838
Shunkai Yao29d10572024-03-19 04:31:47 +00001839 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001840 if (status != NO_ERROR) {
1841 if (chainCreated) {
1842 removeEffectChain_l(chain);
1843 }
1844 return status;
1845 }
1846
jiabin8f278ee2019-11-11 12:16:27 -08001847 effect->setDevices(outDeviceTypeAddrs());
1848 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung7535ed92023-07-17 17:05:00 -07001849 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001850 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001851
Eric Laurent81784c32012-11-19 14:55:58 -08001852 return NO_ERROR;
1853}
1854
Andy Hung4b17e882023-07-07 13:47:37 -07001855void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001856
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001857 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001858 effect_descriptor_t desc = effect->desc();
1859 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1860 detachAuxEffect_l(effect->id());
1861 }
1862
Andy Hung116bc262023-06-20 18:56:17 -07001863 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001864 if (chain != 0) {
1865 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001866 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001867 removeEffectChain_l(chain);
1868 }
1869 } else {
1870 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1871 }
1872}
1873
Shunkai Yaof4847652024-01-12 00:25:20 +00001874void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1875 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001876{
1877 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001878 for (const auto& effectChain : effectChains) {
1879 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001880 }
1881}
1882
Shunkai Yaof4847652024-01-12 00:25:20 +00001883void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1884 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001885{
Shunkai Yaof4847652024-01-12 00:25:20 +00001886 for (const auto& effectChain : effectChains) {
1887 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001888 }
1889}
1890
Andy Hung4b17e882023-07-07 13:47:37 -07001891sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
Andy Hungf8635b62023-08-31 16:13:39 -07001893 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001894 return getEffectChain_l(sessionId);
1895}
1896
Andy Hung4b17e882023-07-07 13:47:37 -07001897sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001898 const
Eric Laurent81784c32012-11-19 14:55:58 -08001899{
1900 size_t size = mEffectChains.size();
1901 for (size_t i = 0; i < size; i++) {
1902 if (mEffectChains[i]->sessionId() == sessionId) {
1903 return mEffectChains[i];
1904 }
1905 }
1906 return 0;
1907}
1908
Andy Hung4b17e882023-07-07 13:47:37 -07001909void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001910{
Andy Hungf8635b62023-08-31 16:13:39 -07001911 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001912 size_t size = mEffectChains.size();
1913 for (size_t i = 0; i < size; i++) {
1914 mEffectChains[i]->setMode_l(mode);
1915 }
1916}
1917
Andy Hung4b17e882023-07-07 13:47:37 -07001918void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001919{
1920 config->type = AUDIO_PORT_TYPE_MIX;
1921 config->ext.mix.handle = mId;
1922 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001923 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001924 config->channel_mask = mChannelMask;
1925 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1926 AUDIO_PORT_CONFIG_FORMAT;
1927}
1928
Andy Hung4b17e882023-07-07 13:47:37 -07001929void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001930{
Andy Hungf8635b62023-08-31 16:13:39 -07001931 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001932 if (mSystemReady) {
1933 return;
1934 }
1935 mSystemReady = true;
1936
1937 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1938 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1939 }
1940 mPendingConfigEvents.clear();
1941}
1942
Andy Hungdae27702016-10-31 14:01:16 -07001943template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001944ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001945 ssize_t index = mActiveTracks.indexOf(track);
1946 if (index >= 0) {
1947 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1948 return index;
1949 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001950 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001951 mActiveTracksGeneration++;
1952 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001953 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001954 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001955 return mActiveTracks.add(track);
1956}
1957
1958template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001959ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001960 ssize_t index = mActiveTracks.remove(track);
1961 if (index < 0) {
1962 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1963 return index;
1964 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001965 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001966 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001967 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001968 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001969 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001970#ifdef TEE_SINK
1971 track->dumpTee(-1 /* fd */, "_REMOVE");
1972#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001973 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001974 return index;
1975}
1976
1977template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07001978void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001979 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001980 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001981 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001982 }
1983 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001984 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001985 mActiveTracks.clear();
1986 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001987}
1988
1989template <typename T>
Andy Hung94dfbb42023-09-06 19:41:47 -07001990void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001991 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001992 // Updates ActiveTracks client uids to the thread wakelock.
1993 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1994 thread->updateWakeLockUids_l(getWakeLockUids());
1995 mLastActiveTracksGeneration = mActiveTracksGeneration;
1996 }
Andy Hungdae27702016-10-31 14:01:16 -07001997}
Eric Laurent83b88082014-06-20 18:31:16 -07001998
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001999template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002000bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002001 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002002 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002003
2004 for (const sp<T> &track : mActiveTracks) {
2005 // Do not short-circuit as all hasChanged states must be reset
2006 // as all the metadata are going to be sent
2007 hasChanged |= track->readAndClearHasChanged();
2008 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002009 return hasChanged;
2010}
2011
2012template <typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002013void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002014 const char *funcName, const sp<T> &track) const {
2015 if (mLocalLog != nullptr) {
2016 String8 result;
2017 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002018 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002019 }
2020}
2021
Andy Hung4b17e882023-07-07 13:47:37 -07002022void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002023{
2024 // Thread could be blocked waiting for async
2025 // so signal it to handle state changes immediately
2026 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2027 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2028 mSignalPending = true;
Andy Hungb17d24b2023-08-29 14:26:09 -07002029 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002030}
2031
Andy Hungd0979812019-02-21 15:51:44 -08002032// Call only from threadLoop() or when it is idle.
2033// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung4b17e882023-07-07 13:47:37 -07002034void ThreadBase::sendStatistics(bool force)
Andy Hung94dfbb42023-09-06 19:41:47 -07002035NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002036{
2037 // Do not log if we have no stats.
2038 // We choose the timestamp verifier because it is the most likely item to be present.
2039 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2040 if (nstats == 0) {
2041 return;
2042 }
2043
2044 // Don't log more frequently than once per 12 hours.
2045 // We use BOOTTIME to include suspend time.
2046 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2047 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2048 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2049 return;
2050 }
2051
2052 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2053 mLastRecordedTimeNs = timeNs;
2054
Ray Essickf27e9872019-12-07 06:28:46 -08002055 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002056
2057#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2058
2059 // thread configuration
2060 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2061 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2062 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2063 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2064 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2065 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2066 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hung94dfbb42023-09-06 19:41:47 -07002067 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2068 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002069
2070 // thread statistics
2071 if (mIoJitterMs.getN() > 0) {
2072 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2073 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2074 }
2075 if (mProcessTimeMs.getN() > 0) {
2076 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2077 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2078 }
2079 const auto tsjitter = mTimestampVerifier.getJitterMs();
2080 if (tsjitter.getN() > 0) {
2081 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2082 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2083 }
2084 if (mLatencyMs.getN() > 0) {
2085 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2086 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2087 }
Robert Wu06db0a32021-08-10 19:05:34 +00002088 if (mMonopipePipeDepthStats.getN() > 0) {
2089 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2090 mMonopipePipeDepthStats.getMean());
2091 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2092 mMonopipePipeDepthStats.getStdDev());
2093 }
Andy Hungd0979812019-02-21 15:51:44 -08002094
2095 item->selfrecord();
2096}
2097
Andy Hung4b17e882023-07-07 13:47:37 -07002098product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002099{
Andy Hung7535ed92023-07-17 17:05:00 -07002100 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002101 return PRODUCT_STRATEGY_NONE;
2102 }
2103 return AudioSystem::getStrategyForStream(stream);
2104}
2105
Andy Hungb17d24b2023-08-29 14:26:09 -07002106// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002107void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002108 const sp<audio_utils::MelProcessor>& /*processor*/)
2109{
2110 // Do nothing
2111 ALOGW("%s: ThreadBase does not support CSD", __func__);
2112}
2113
Andy Hungb17d24b2023-08-29 14:26:09 -07002114// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002115void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002116{
2117 // Do nothing
2118 ALOGW("%s: ThreadBase does not support CSD", __func__);
2119}
2120
Eric Laurent81784c32012-11-19 14:55:58 -08002121// ----------------------------------------------------------------------------
2122// Playback
2123// ----------------------------------------------------------------------------
2124
Andy Hung7535ed92023-07-17 17:05:00 -07002125PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002126 AudioStreamOut* output,
2127 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002128 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002129 bool systemReady,
2130 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07002131 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002132 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002133 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002134 mMixerBuffer(NULL),
2135 mMixerBufferSize(0),
2136 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2137 mMixerBufferValid(false),
Andy Hungd21a2ab2023-07-20 21:44:14 -07002138 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002139 mEffectBuffer(NULL),
2140 mEffectBufferSize(0),
2141 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2142 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002143 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002144 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002145 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002146 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002147 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002148 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002149 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002150 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002151 mMixerStatus(MIXER_IDLE),
2152 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hungd58c4732023-07-20 21:31:38 -07002153 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002154 mBytesRemaining(0),
2155 mCurrentWriteLength(0),
2156 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002157 mWriteAckSequence(0),
2158 mDrainSequence(0),
Andy Hung1b6d46a2023-07-19 16:22:58 -07002159 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002160 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002161 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002162 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002163 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002164 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002165 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002166{
Glenn Kastend7dca052015-03-05 16:05:54 -08002167 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07002168 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002169
Andy Hungb17d24b2023-08-29 14:26:09 -07002170 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002171 // it would be safer to explicitly pass initial masterVolume/masterMute as
2172 // parameter.
2173 //
2174 // If the HAL we are using has support for master volume or master mute,
2175 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2176 // and the mute set to false).
Andy Hung7535ed92023-07-17 17:05:00 -07002177 mMasterVolume = afThreadCallback->masterVolume_l();
2178 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002179 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002180 if (mOutput->audioHwDev->canSetMasterVolume()) {
2181 mMasterVolume = 1.0;
2182 }
2183
2184 if (mOutput->audioHwDev->canSetMasterMute()) {
2185 mMasterMute = false;
2186 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002187 mIsMsdDevice = strcmp(
2188 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002189 }
2190
Eric Laurentf1f22e72021-07-13 14:04:14 +02002191 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2192 mMixerChannelMask = mixerConfig->channel_mask;
2193 }
2194
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002195 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002196
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002197 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002198 && mMixerChannelMask != mChannelMask) {
2199 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2200 mChannelMask, mMixerChannelMask);
2201 }
2202
Andy Hungc8fddf32018-08-08 18:32:37 -07002203 // TODO: We may also match on address as well as device type for
2204 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002205 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002206 // TODO: This property should be ensure that only contains one single device type.
2207 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2208 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002209 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2210 : AUDIO_DEVICE_NONE));
2211 }
2212
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002213 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2214 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002215 mStreamTypes[stream].volume = 0.0f;
Andy Hung7535ed92023-07-17 17:05:00 -07002216 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002217 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002218 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002219 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2220 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002221 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2222 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002223}
2224
Andy Hung4b17e882023-07-07 13:47:37 -07002225PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002226{
Andy Hung7535ed92023-07-17 17:05:00 -07002227 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002228 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002229 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002230 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002231 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002232}
2233
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002234// Thread virtuals
2235
Andy Hung4b17e882023-07-07 13:47:37 -07002236void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002237{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002238 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002239 ALOGE("The stream is not open yet"); // This should not happen.
2240 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002241 // Callbacks take strong or weak pointers as a parameter.
2242 // Since PlaybackThread passes itself as a callback handler, it can only
2243 // be done outside of the constructor. Creating weak and especially strong
2244 // pointers to a refcounted object in its own constructor is strongly
2245 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2246 // Even if a function takes a weak pointer, it is possible that it will
2247 // need to convert it to a strong pointer down the line.
2248 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2249 mOutput->stream->setCallback(this) == OK) {
2250 mUseAsyncWrite = true;
Andy Hung4b17e882023-07-07 13:47:37 -07002251 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002252 }
2253
jiabinf6eb4c32020-02-25 14:06:25 -08002254 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002255 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002256 }
2257 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002258 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002259 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002260}
2261
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002262// ThreadBase virtuals
Andy Hung4b17e882023-07-07 13:47:37 -07002263void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002264{
2265 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002266 status_t result = mOutput->stream->exit();
2267 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002268}
2269
Andy Hung4b17e882023-07-07 13:47:37 -07002270void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002271{
Eric Laurent81784c32012-11-19 14:55:58 -08002272 String8 result;
2273
Marco Nelissenb2208842014-02-07 14:00:50 -08002274 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002275 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2276 const stream_type_t *st = &mStreamTypes[i];
2277 if (i > 0) {
2278 result.appendFormat(", ");
2279 }
2280 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2281 if (st->mute) {
2282 result.append("M");
2283 }
2284 }
2285 result.append("\n");
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002286 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002287 result.clear();
2288
Eric Laurent81784c32012-11-19 14:55:58 -08002289 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2290 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002291 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002292 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002293
2294 size_t numtracks = mTracks.size();
2295 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002296 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002297 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002298 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002299 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002300 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002301 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002302 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002303 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002304 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002305 if (track != 0) {
2306 bool active = mActiveTracks.indexOf(track) >= 0;
2307 if (active) {
2308 numactiveseen++;
2309 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002310 result.append(prefix);
2311 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002312 }
2313 }
2314 } else {
2315 result.append("\n");
2316 }
2317 if (numactiveseen != numactive) {
2318 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002319 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002321 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002322 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002323 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002324 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002325 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002326 result.append(prefix);
2327 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002328 }
2329 }
2330 }
2331
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002332 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002333}
2334
Andy Hung4b17e882023-07-07 13:47:37 -07002335void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002336{
Andy Hung04cb8f72020-03-20 13:44:33 -07002337 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002338 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002339 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2340 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002341 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2342 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2343 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2344 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002345 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002346 dprintf(fd, " Total writes: %d\n", mNumWrites);
2347 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2348 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung160664b2023-09-15 18:19:28 -07002349 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002350 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002351 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002352 AudioStreamOut *output = mOutput;
2353 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002354 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002355 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002356 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2357 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2358 if (mPipeSink.get() != nullptr) {
2359 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2360 }
2361 if (output != nullptr) {
2362 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002363 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002364 }
Eric Laurent81784c32012-11-19 14:55:58 -08002365}
2366
Andy Hungb17d24b2023-08-29 14:26:09 -07002367// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002368sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002369 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002370 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002371 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002372 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002373 audio_format_t format,
2374 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002375 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002376 size_t *pNotificationFrameCount,
2377 uint32_t notificationsPerBuffer,
2378 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002379 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002380 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002381 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002382 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002383 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002384 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002385 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002386 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002387 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002388 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002389 bool isBitPerfect,
2390 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002391{
Glenn Kasten74935e42013-12-19 08:56:45 -08002392 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002393 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07002394 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002395 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002396 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002397 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002398 uint32_t sampleRate;
2399
2400 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2401 lStatus = BAD_VALUE;
2402 goto Exit;
2403 }
Eric Laurent21da6472017-11-09 16:29:26 -08002404
2405 if (*pSampleRate == 0) {
2406 *pSampleRate = mSampleRate;
2407 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002408 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002409
2410 // special case for FAST flag considered OK if fast mixer is present
2411 if (hasFastMixer()) {
2412 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2413 }
2414
2415 // Check if requested flags are compatible with output stream flags
2416 if ((*flags & outputFlags) != *flags) {
2417 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2418 *flags, outputFlags);
2419 *flags = (audio_output_flags_t)(*flags & outputFlags);
2420 }
Eric Laurent81784c32012-11-19 14:55:58 -08002421
jiabinc658e452022-10-21 20:52:21 +00002422 if (isBitPerfect) {
Andy Hung160664b2023-09-15 18:19:28 -07002423 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002424 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002425 if (chain.get() != nullptr) {
2426 // Bit-perfect is required according to the configuration and preferred mixer
2427 // attributes, but it is not in the output flag from the client's request. Explicitly
2428 // adding bit-perfect flag to check the compatibility
2429 audio_output_flags_t flagsToCheck =
2430 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2431 chain->checkOutputFlagCompatibility(&flagsToCheck);
2432 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2433 ALOGE("%s cannot create track as there is data-processing effect attached to "
2434 "given session id(%d)", __func__, sessionId);
2435 lStatus = BAD_VALUE;
2436 goto Exit;
2437 }
2438 *flags = flagsToCheck;
2439 }
2440 }
2441
Eric Laurent81784c32012-11-19 14:55:58 -08002442 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002443 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002444 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // PCM data
2446 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002447 // TODO: extract as a data library function that checks that a computationally
2448 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002449 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002450 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2451 (channelMask == AUDIO_CHANNEL_OUT_MONO
2452 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002453 // hardware sample rate
2454 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002455 // normal mixer has an associated fast mixer
2456 hasFastMixer() &&
2457 // there are sufficient fast track slots available
2458 (mFastTrackAvailMask != 0)
2459 // FIXME test that MixerThread for this fast track has a capable output HAL
2460 // FIXME add a permission test also?
2461 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002462 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2463 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002464 // read the fast track multiplier property the first time it is needed
2465 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2466 if (ok != 0) {
2467 ALOGE("%s pthread_once failed: %d", __func__, ok);
2468 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002469 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002470 }
Eric Laurent4c415062016-06-17 16:14:16 -07002471
2472 // check compatibility with audio effects.
Andy Hungb17d24b2023-08-29 14:26:09 -07002473 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002474 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002475 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002476 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002477 AUDIO_SESSION_OUTPUT_STAGE,
2478 AUDIO_SESSION_OUTPUT_MIX,
2479 sessionId,
2480 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002481 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002482 if (chain.get() != nullptr) {
2483 audio_output_flags_t old = *flags;
2484 chain->checkOutputFlagCompatibility(flags);
2485 if (old != *flags) {
2486 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2487 (int)session, (int)old, (int)*flags);
2488 }
Eric Laurent4c415062016-06-17 16:14:16 -07002489 }
2490 }
2491 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002492 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002493 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2494 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002495 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002496 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002497 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002498 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002499 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002500 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002501 audio_is_linear_pcm(format), channelMask, sampleRate,
2502 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002503 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002504 }
2505 }
Eric Laurent21da6472017-11-09 16:29:26 -08002506
2507 if (!audio_has_proportional_frames(format)) {
2508 if (sharedBuffer != 0) {
2509 // Same comment as below about ignoring frameCount parameter for set()
2510 frameCount = sharedBuffer->size();
2511 } else if (frameCount == 0) {
2512 frameCount = mNormalFrameCount;
2513 }
2514 if (notificationFrameCount != frameCount) {
2515 notificationFrameCount = frameCount;
2516 }
2517 } else if (sharedBuffer != 0) {
2518 // FIXME: Ensure client side memory buffers need
2519 // not have additional alignment beyond sample
2520 // (e.g. 16 bit stereo accessed as 32 bit frame).
2521 size_t alignment = audio_bytes_per_sample(format);
2522 if (alignment & 1) {
2523 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2524 alignment = 1;
2525 }
2526 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2527 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2528 if (channelCount > 1) {
2529 // More than 2 channels does not require stronger alignment than stereo
2530 alignment <<= 1;
2531 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002532 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002533 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002534 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002535 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002536 goto Exit;
2537 }
Eric Laurent21da6472017-11-09 16:29:26 -08002538
2539 // When initializing a shared buffer AudioTrack via constructors,
2540 // there's no frameCount parameter.
2541 // But when initializing a shared buffer AudioTrack via set(),
2542 // there _is_ a frameCount parameter. We silently ignore it.
2543 frameCount = sharedBuffer->size() / frameSize;
2544 } else {
2545 size_t minFrameCount = 0;
2546 // For fast tracks we try to respect the application's request for notifications per buffer.
2547 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2548 if (notificationsPerBuffer > 0) {
2549 // Avoid possible arithmetic overflow during multiplication.
2550 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2551 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2552 notificationsPerBuffer, mFrameCount);
2553 } else {
2554 minFrameCount = mFrameCount * notificationsPerBuffer;
2555 }
2556 }
2557 } else {
2558 // For normal PCM streaming tracks, update minimum frame count.
2559 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2560 // cover audio hardware latency.
2561 // This is probably too conservative, but legacy application code may depend on it.
2562 // If you change this calculation, also review the start threshold which is related.
2563 uint32_t latencyMs = latency_l();
2564 if (latencyMs == 0) {
2565 ALOGE("Error when retrieving output stream latency");
2566 lStatus = UNKNOWN_ERROR;
2567 goto Exit;
2568 }
2569
2570 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2571 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2572
Eric Laurent81784c32012-11-19 14:55:58 -08002573 }
Eric Laurent21da6472017-11-09 16:29:26 -08002574 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002575 frameCount = minFrameCount;
2576 }
Eric Laurent81784c32012-11-19 14:55:58 -08002577 }
Eric Laurent21da6472017-11-09 16:29:26 -08002578
2579 // Make sure that application is notified with sufficient margin before underrun.
2580 // The client can divide the AudioTrack buffer into sub-buffers,
2581 // and expresses its desire to server as the notification frame count.
2582 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2583 size_t maxNotificationFrames;
2584 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2585 // notify every HAL buffer, regardless of the size of the track buffer
2586 maxNotificationFrames = mFrameCount;
2587 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002588 // Triple buffer the notification period for a triple buffered mixer period;
2589 // otherwise, double buffering for the notification period is fine.
2590 //
2591 // TODO: This should be moved to AudioTrack to modify the notification period
2592 // on AudioTrack::setBufferSizeInFrames() changes.
2593 const int nBuffering =
2594 (uint64_t{frameCount} * mSampleRate)
2595 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2596
Eric Laurent21da6472017-11-09 16:29:26 -08002597 maxNotificationFrames = frameCount / nBuffering;
2598 // If client requested a fast track but this was denied, then use the smaller maximum.
2599 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2600 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2601 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2602 maxNotificationFrames = maxNotificationFramesFastDenied;
2603 }
2604 }
2605 }
2606 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2607 if (notificationFrameCount == 0) {
2608 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2609 maxNotificationFrames, frameCount);
2610 } else {
2611 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2612 notificationFrameCount, maxNotificationFrames, frameCount);
2613 }
2614 notificationFrameCount = maxNotificationFrames;
2615 }
2616 }
2617
Glenn Kasten74935e42013-12-19 08:56:45 -08002618 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002619 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002620
Glenn Kastenc3df8382014-03-13 15:05:25 -07002621 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002622 case BIT_PERFECT:
2623 if (isBitPerfect) {
2624 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2625 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2626 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2627 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2628 mChannelMask);
2629 lStatus = BAD_VALUE;
2630 goto Exit;
2631 }
2632 }
2633 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002634
2635 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002636 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002637 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002638 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2639 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002640 sampleRate, format, channelMask, mOutput, mFormat);
2641 lStatus = BAD_VALUE;
2642 goto Exit;
2643 }
2644 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002645 break;
2646
2647 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002649 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2650 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 sampleRate, format, channelMask, mOutput, mFormat);
2652 lStatus = BAD_VALUE;
2653 goto Exit;
2654 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002655 break;
2656
2657 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002658 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002659 ALOGE("createTrack_l() Bad parameter: format %#x \""
2660 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661 format, mOutput, mFormat);
2662 lStatus = BAD_VALUE;
2663 goto Exit;
2664 }
Andy Hungcd044842014-08-07 11:04:34 -07002665 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002666 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2667 lStatus = BAD_VALUE;
2668 goto Exit;
2669 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002670 break;
2671
Eric Laurent81784c32012-11-19 14:55:58 -08002672 }
2673
2674 lStatus = initCheck();
2675 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002676 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002677 goto Exit;
2678 }
2679
Andy Hungb17d24b2023-08-29 14:26:09 -07002680 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07002681 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002682
2683 // all tracks in same audio session must share the same routing strategy otherwise
2684 // conflicts will happen when tracks are moved from one output to another by audio policy
2685 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002686 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002687 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07002688 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002689 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002690 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002691 if (sessionId == t->sessionId() && strategy != actual) {
2692 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2693 strategy, actual);
2694 lStatus = BAD_VALUE;
2695 goto Exit;
2696 }
2697 }
2698 }
2699
Deeraj Soman2b515232024-05-14 12:58:24 +05302700 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2701 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002702 // dynamic audio policy.
2703 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302704 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002705 audio_output_flags_t trackFlags = *flags;
2706 if (mType == DIRECT) {
2707 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302708 } else if (mType == OFFLOAD) {
2709 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2710 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002711 }
jiabin94ed47c2023-07-27 23:34:20 +00002712 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002713
Andy Hung11e74242023-06-26 19:20:57 -07002714 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002715 channelMask, frameCount,
2716 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002717 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung11e74242023-06-26 19:20:57 -07002718 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002719 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002720
Glenn Kasten03003332013-08-06 15:40:54 -07002721 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2722 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002723 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002724 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002725 goto Exit;
2726 }
2727 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002728 {
Andy Hungf8635b62023-08-31 16:13:39 -07002729 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002730 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002731 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002732 }
2733 }
Eric Laurent81784c32012-11-19 14:55:58 -08002734
Andy Hung116bc262023-06-20 18:56:17 -07002735 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002736 if (chain != 0) {
2737 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2738 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002739 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002740 chain->incTrackCnt();
2741 }
2742
Eric Laurent05067782016-06-01 18:27:28 -07002743 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002744 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2745 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2746 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002747 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002748 }
2749 }
2750
2751 lStatus = NO_ERROR;
2752
2753Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002754 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002755 return track;
2756}
2757
Andy Hung1bc088a2018-02-09 15:57:31 -08002758template<typename T>
Andy Hung4b17e882023-07-07 13:47:37 -07002759ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002760{
Andy Hungc0691382018-09-12 18:01:57 -07002761 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002762 const ssize_t index = mTracks.remove(track);
2763 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002764 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002765 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002766 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002767 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002768 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002769 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002770 }
2771 return index;
2772}
2773
Andy Hung4b17e882023-07-07 13:47:37 -07002774uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002775{
2776 return latency;
2777}
2778
Andy Hung4b17e882023-07-07 13:47:37 -07002779uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002780{
Andy Hungf8635b62023-08-31 16:13:39 -07002781 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002782 return latency_l();
2783}
Andy Hung4b17e882023-07-07 13:47:37 -07002784uint32_t PlaybackThread::latency_l() const
Andy Hung94dfbb42023-09-06 19:41:47 -07002785NO_THREAD_SAFETY_ANALYSIS
2786// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002787{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002788 uint32_t latency;
2789 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2790 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002791 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002792 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002793}
2794
Andy Hung4b17e882023-07-07 13:47:37 -07002795void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002796{
Andy Hungf8635b62023-08-31 16:13:39 -07002797 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002798 // Don't apply master volume in SW if our HAL can do it for us.
2799 if (mOutput && mOutput->audioHwDev &&
2800 mOutput->audioHwDev->canSetMasterVolume()) {
2801 mMasterVolume = 1.0;
2802 } else {
2803 mMasterVolume = value;
2804 }
2805}
2806
Andy Hung4b17e882023-07-07 13:47:37 -07002807void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002808{
2809 mMasterBalance.store(balance);
2810}
2811
Andy Hung4b17e882023-07-07 13:47:37 -07002812void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002813{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002814 if (isDuplicating()) {
2815 return;
2816 }
Andy Hungf8635b62023-08-31 16:13:39 -07002817 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002818 // Don't apply master mute in SW if our HAL can do it for us.
2819 if (mOutput && mOutput->audioHwDev &&
2820 mOutput->audioHwDev->canSetMasterMute()) {
2821 mMasterMute = false;
2822 } else {
2823 mMasterMute = muted;
2824 }
2825}
2826
Andy Hung4b17e882023-07-07 13:47:37 -07002827void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002828{
Andy Hungf8635b62023-08-31 16:13:39 -07002829 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002830 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002831 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002832}
2833
Andy Hung4b17e882023-07-07 13:47:37 -07002834void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002835{
Andy Hungf8635b62023-08-31 16:13:39 -07002836 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002837 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002838 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002839}
2840
Andy Hung4b17e882023-07-07 13:47:37 -07002841float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002842{
Andy Hungf8635b62023-08-31 16:13:39 -07002843 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002844 return mStreamTypes[stream].volume;
2845}
2846
Andy Hung4b17e882023-07-07 13:47:37 -07002847void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002848{
2849 mOutput->stream->setVolume(left, right);
2850}
2851
Andy Hungb17d24b2023-08-29 14:26:09 -07002852// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07002853status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002854{
2855 status_t status = ALREADY_EXISTS;
2856
Eric Laurent81784c32012-11-19 14:55:58 -08002857 if (mActiveTracks.indexOf(track) < 0) {
2858 // the track is newly added, make sure it fills up all its
2859 // buffers before playing. This is to ensure the client will
2860 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002861 if (track->isExternalTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002862 IAfTrackBase::track_state state = track->state();
Andy Hunga7187712023-12-05 17:28:17 -08002863 // Because the track is not on the ActiveTracks,
2864 // at this point, only the TrackHandle will be adding the track.
Andy Hungb17d24b2023-08-29 14:26:09 -07002865 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002866 status = AudioSystem::startOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002867 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002868 // abort track was stopped/paused while we released the lock
Andy Hung11e74242023-06-26 19:20:57 -07002869 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 if (status == NO_ERROR) {
Andy Hungb17d24b2023-08-29 14:26:09 -07002871 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002872 AudioSystem::stopOutput(track->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07002873 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 }
2875 return INVALID_OPERATION;
2876 }
2877 // abort if start is rejected by audio policy manager
2878 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002879 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2880 // current playback thread is reopened, which may happen when clients set preferred
2881 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2882 // immediately.
2883 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 }
2885#ifdef ADD_BATTERY_DATA
2886 // to track the speaker usage
2887 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2888#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002889 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 }
2891
Eric Laurent51716182016-02-29 18:00:56 -08002892 // set retry count for buffer fill
2893 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002894 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07002895 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002896 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002897 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002898 }
Andy Hung11e74242023-06-26 19:20:57 -07002899 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002900 } else {
Andy Hung11e74242023-06-26 19:20:57 -07002901 track->retryCount() = kMaxTrackStartupRetries;
2902 track->fillingStatus() =
2903 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002904 }
2905
Andy Hung116bc262023-06-20 18:56:17 -07002906 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002907 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2908 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002909 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002910 // Unlock due to VibratorService will lock for this call and will
2911 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungb17d24b2023-08-29 14:26:09 -07002912 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002913 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002914 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002915 std::optional<media::AudioVibratorInfo> vibratorInfo;
2916 {
2917 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2918 // used to play this track.
Andy Hungf8635b62023-08-31 16:13:39 -07002919 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002920 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002921 }
Andy Hungb17d24b2023-08-29 14:26:09 -07002922 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002923 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002924 if (vibratorInfo) {
2925 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2926 }
2927
jiabin57303cc2018-12-18 15:45:57 -08002928 // Haptic playback should be enabled by vibrator service.
2929 if (track->getHapticPlaybackEnabled()) {
2930 // Disable haptic playback of all active track to ensure only
2931 // one track playing haptic if current track should play haptic.
2932 for (const auto &t : mActiveTracks) {
2933 t->setHapticPlaybackEnabled(false);
2934 }
jiabin245cdd92018-12-07 17:55:15 -08002935 }
jiabine70bc7f2020-06-30 22:07:55 -07002936
2937 // Set haptic intensity for effect
2938 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002939 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002940 }
jiabin245cdd92018-12-07 17:55:15 -08002941 }
2942
Andy Hung11e74242023-06-26 19:20:57 -07002943 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002944 track->resetPresentationComplete();
Andy Hunga7187712023-12-05 17:28:17 -08002945
2946 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2947 // all key changes are complete. It is possible that the threadLoop will begin
2948 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002949 mActiveTracks.add(track);
Andy Hunga7187712023-12-05 17:28:17 -08002950
Eric Laurentd0107bc2013-06-11 14:38:48 -07002951 if (chain != 0) {
2952 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2953 track->sessionId());
2954 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002955 }
2956
Andy Hungc2b11cb2020-04-22 09:04:01 -07002957 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002958 status = NO_ERROR;
2959 }
2960
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002961 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002962 return status;
2963}
2964
Andy Hung4b17e882023-07-07 13:47:37 -07002965bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002966{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002967 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002968 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002969 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung11e74242023-06-26 19:20:57 -07002970 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002971 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002972 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002973 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002974 if (track->isPausePending()) {
2975 track->pauseAck();
2976 }
Andy Hung11e74242023-06-26 19:20:57 -07002977 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002978 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979
2980 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002981}
2982
Andy Hung4b17e882023-07-07 13:47:37 -07002983void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002984{
2985 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002986
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002987 String8 result;
2988 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002989 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002990
Eric Laurent81784c32012-11-19 14:55:58 -08002991 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002992 {
Andy Hungf8635b62023-08-31 16:13:39 -07002993 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002994 mAudioTrackCallbacks.erase(track);
2995 }
Eric Laurent81784c32012-11-19 14:55:58 -08002996 if (track->isFastTrack()) {
Andy Hung11e74242023-06-26 19:20:57 -07002997 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002998 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002999 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3000 mFastTrackAvailMask |= 1 << index;
3001 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung11e74242023-06-26 19:20:57 -07003002 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003003 }
Andy Hung116bc262023-06-20 18:56:17 -07003004 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003005 if (chain != 0) {
3006 chain->decTrackCnt();
3007 }
3008}
3009
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003010std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3011{
3012 std::set<int32_t> result;
3013 for (const auto& t : mTracks) {
3014 if (t->isExternalTrack()) {
3015 result.insert(t->portId());
3016 }
3017 }
3018 return result;
3019}
3020
3021std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3022{
3023 audio_utils::lock_guard _l(mutex());
3024 return getTrackPortIds_l();
3025}
3026
Andy Hung4b17e882023-07-07 13:47:37 -07003027String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003028{
Andy Hungf8635b62023-08-31 16:13:39 -07003029 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003030 String8 out_s8;
3031 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3032 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003033 }
Andy Hung920f6572022-10-06 12:09:49 -07003034 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003035}
3036
Andy Hung4b17e882023-07-07 13:47:37 -07003037status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hungf8635b62023-08-31 16:13:39 -07003038 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003039 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003040 return NO_INIT;
3041 }
3042 return mOutput->stream->selectPresentation(presentationId, programId);
3043}
3044
Andy Hung94dfbb42023-09-06 19:41:47 -07003045void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003046 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003047 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003048 sp<AudioIoDescriptor> desc;
3049 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003050 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003051 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003052 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003053 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003054 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3055 mSampleRate, mFormat, mChannelMask,
3056 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3057 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003058 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003059 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003060 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003061 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003062 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003063 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003064 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003065 break;
3066 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003067 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003068}
3069
Andy Hung4b17e882023-07-07 13:47:37 -07003070void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003071{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003072 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003073}
3074
Andy Hung4b17e882023-07-07 13:47:37 -07003075void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003076{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003077 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003078}
3079
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003080void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003081{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00003082 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003083}
3084
Andy Hung4b17e882023-07-07 13:47:37 -07003085void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003086 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003087{
Andy Hung4b17e882023-07-07 13:47:37 -07003088 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003089 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung4b17e882023-07-07 13:47:37 -07003090 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003091 if (playbackThread == nullptr) {
3092 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3093 return;
3094 }
3095
jiabinf6eb4c32020-02-25 14:06:25 -08003096 audio_utils::metadata::Data metadata =
3097 audio_utils::metadata::dataFromByteString(metadataBs);
3098 if (metadata.empty()) {
3099 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3100 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3101 (int)metadataBs.size());
3102 return;
3103 }
3104
3105 audio_utils::metadata::ByteString metaDataStr =
3106 audio_utils::metadata::byteStringFromData(metadata);
3107 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hungf8635b62023-08-31 16:13:39 -07003108 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003109 for (const auto& callbackPair : mAudioTrackCallbacks) {
3110 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003111 }
3112 }).detach();
3113}
3114
Andy Hung4b17e882023-07-07 13:47:37 -07003115void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116{
Andy Hungf8635b62023-08-31 16:13:39 -07003117 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003118 // reject out of sequence requests
3119 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3120 mWriteAckSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003121 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003122 }
3123}
3124
Andy Hung4b17e882023-07-07 13:47:37 -07003125void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003126{
Andy Hungf8635b62023-08-31 16:13:39 -07003127 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003128 // reject out of sequence requests
3129 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003130 // Register discontinuity when HW drain is completed because that can cause
3131 // the timestamp frame position to reset to 0 for direct and offload threads.
3132 // (Out of sequence requests are ignored, since the discontinuity would be handled
3133 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003134 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003135 mDrainSequence &= ~1;
Andy Hungb17d24b2023-08-29 14:26:09 -07003136 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003137 }
3138}
3139
Andy Hung4b17e882023-07-07 13:47:37 -07003140void PlaybackThread::readOutputParameters_l()
Andy Hungf8635b62023-08-31 16:13:39 -07003141NO_THREAD_SAFETY_ANALYSIS
3142// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003143{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003144 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003145 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3146 mSampleRate = audioConfig.sample_rate;
3147 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003148 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003149 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003150 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003151 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003152 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3153 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003154 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003155
3156 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3157 mMixerChannelMask = mChannelMask;
3158 }
3159
Andy Hunge5412692014-05-16 11:25:07 -07003160 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003161 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003162
Eric Laurentf1f22e72021-07-13 14:04:14 +02003163 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3164
Phil Burkca5e6142015-07-14 09:42:29 -07003165 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003166 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003167 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003168 // Get format from the shim, which will be different than the HAL format
3169 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003170 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003171 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003172 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003173 }
Andy Hungd21a2ab2023-07-20 21:44:14 -07003174 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003175 LOG_FATAL("HAL format %#x not supported for mixed output",
3176 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003177 }
Phil Burk062e67a2015-02-11 13:40:50 -08003178 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003179 result = mOutput->stream->getBufferSize(&mBufferSize);
3180 LOG_ALWAYS_FATAL_IF(result != OK,
3181 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003182 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003183 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003184 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003185 mFrameCount);
3186 }
3187
Eric Laurentd1f69b02014-12-15 14:33:13 -08003188 mHwSupportsPause = false;
3189 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003190 bool supportsPause = false, supportsResume = false;
3191 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3192 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003193 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003194 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003195 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003196 } else if (supportsResume) {
3197 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003198 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003199 }
3200 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003201 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3202 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3203 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003204
Andy Hungfbfc3952015-01-15 13:33:51 -08003205 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3206 // For best precision, we use float instead of the associated output
3207 // device format (typically PCM 16 bit).
3208
3209 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3210 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3211 mBufferSize = mFrameSize * mFrameCount;
3212
3213 // TODO: We currently use the associated output device channel mask and sample rate.
3214 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3215 // (if a valid mask) to avoid premature downmix.
3216 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3217 // instead of the output device sample rate to avoid loss of high frequency information.
3218 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3219 }
3220
Andy Hung09a50072014-02-27 14:30:47 -08003221 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003222 double multiplier = 1.0;
Henrik Tillman470b3992024-10-08 12:49:28 +02003223 // Note: mType == SPATIALIZER does not support FastMixer and DEEP is by definition not "fast"
3224 if ((mType == MIXER && !(mOutput->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) &&
3225 (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003226 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3227 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003228
Eric Laurent81784c32012-11-19 14:55:58 -08003229 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3230 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3231 maxNormalFrameCount = maxNormalFrameCount & ~15;
3232 if (maxNormalFrameCount < minNormalFrameCount) {
3233 maxNormalFrameCount = minNormalFrameCount;
3234 }
3235 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3236 if (multiplier <= 1.0) {
3237 multiplier = 1.0;
3238 } else if (multiplier <= 2.0) {
3239 if (2 * mFrameCount <= maxNormalFrameCount) {
3240 multiplier = 2.0;
3241 } else {
3242 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3243 }
3244 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003245 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003246 }
3247 }
3248 mNormalFrameCount = multiplier * mFrameCount;
3249 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003250 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003251 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3252 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003253 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3254 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003255
Andy Hung08fb1742015-05-31 23:22:10 -07003256 // Check if we want to throttle the processing to no more than 2x normal rate
3257 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003258 mThreadThrottleTimeMs = 0;
3259 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003260 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3261
Andy Hung010a1a12014-03-13 13:57:33 -07003262 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3263 // Originally this was int16_t[] array, need to remove legacy implications.
3264 free(mSinkBuffer);
3265 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003266
Andy Hung5b10a202014-03-13 13:59:29 -07003267 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3268 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3269 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003270 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003271
Andy Hung69aed5f2014-02-25 17:24:40 -08003272 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3273 // drives the output.
3274 free(mMixerBuffer);
3275 mMixerBuffer = NULL;
3276 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003277 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003278 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003279 * audio_bytes_per_sample(mMixerBufferFormat);
3280 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3281 }
Andy Hung98ef9782014-03-04 14:46:50 -08003282 free(mEffectBuffer);
3283 mEffectBuffer = NULL;
3284 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003285 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003286 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003287 * audio_bytes_per_sample(mEffectBufferFormat);
3288 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3289 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003290
Eric Laurentb62d0362021-10-26 17:40:18 +02003291 if (mType == SPATIALIZER) {
3292 free(mPostSpatializerBuffer);
3293 mPostSpatializerBuffer = nullptr;
3294 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3295 * audio_bytes_per_sample(mEffectBufferFormat);
3296 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3297 }
3298
Mikhail Naganov55773032020-10-01 15:08:13 -07003299 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3300 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003301 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3302 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003303 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003304
Eric Laurent81784c32012-11-19 14:55:58 -08003305 // force reconfiguration of effect chains and engines to take new buffer size and audio
3306 // parameters into account
Andy Hungb17d24b2023-08-29 14:26:09 -07003307 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003308 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3309 // matter.
Andy Hungf8635b62023-08-31 16:13:39 -07003310 // create a copy of mEffectChains as calling moveEffectChain_ll()
3311 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003312 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003313 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hungf8635b62023-08-31 16:13:39 -07003314 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003315 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003316 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003317
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003318 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003319 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003320 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07003321 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003322 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3323 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3324 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3325 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3326 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3327 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3328 (int32_t)mHapticChannelMask)
3329 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3330 (int32_t)mHapticChannelCount)
3331 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -07003332 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003333 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3334 (int32_t)mFrameCount) // sic - added HAL
3335 ;
3336 uint32_t latencyMs;
3337 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3338 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3339 }
3340 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003341}
3342
Andy Hung4b17e882023-07-07 13:47:37 -07003343ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003344{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003345 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003346 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003347 }
3348 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003349 static const bool stereo_spatialization_property =
3350 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3351 const bool stereo_spatialization_enabled =
3352 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3353 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003354 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3355 for (const sp<IAfTrack>& track : mActiveTracks) {
3356 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3357 allSessionsMetadata[track->sessionId()];
3358 auto backInserter = std::back_inserter(sessionMetadata);
3359 // No track is invalid as this is called after prepareTrack_l in the same
3360 // critical section
3361 track->copyMetadataTo(backInserter);
3362 }
3363 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3364 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3365 metadata.tracks.insert(metadata.tracks.end(),
3366 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3367 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3368 chain->sendMetadata_l(sessionTrackMetadata, {});
3369 }
3370 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3371 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3372 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3373 }
3374 }
3375 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3376 chain->sendMetadata_l(metadata.tracks, {});
3377 }
3378 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3379 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3380 }
3381 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3382 chain->sendMetadata_l(metadata.tracks, {});
3383 }
3384 } else {
3385 auto backInserter = std::back_inserter(metadata.tracks);
3386 for (const sp<IAfTrack>& track : mActiveTracks) {
3387 // No track is invalid as this is called after prepareTrack_l in the same
3388 // critical section
3389 track->copyMetadataTo(backInserter);
3390 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003391 }
Kevin Rocard12381092018-04-11 09:19:59 -07003392 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003393 MetadataUpdate change;
3394 change.playbackMetadataUpdate = metadata.tracks;
3395 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003396}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003397
Andy Hung4b17e882023-07-07 13:47:37 -07003398void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003399 const StreamOutHalInterface::SourceMetadata& metadata)
3400{
3401 mOutput->stream->updateSourceMetadata(metadata);
3402};
3403
Andy Hung4b17e882023-07-07 13:47:37 -07003404status_t PlaybackThread::getRenderPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -07003405 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003406{
3407 if (halFrames == NULL || dspFrames == NULL) {
3408 return BAD_VALUE;
3409 }
Andy Hungf8635b62023-08-31 16:13:39 -07003410 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003411 if (initCheck() != NO_ERROR) {
3412 return INVALID_OPERATION;
3413 }
Andy Hung818e7a32016-02-16 18:08:07 -08003414 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003415 *halFrames = framesWritten;
3416
3417 if (isSuspended()) {
3418 // return an estimation of rendered frames when the output is suspended
3419 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003420 *dspFrames = (uint32_t)
3421 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003422 return NO_ERROR;
3423 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003424 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003425 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003426 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003427 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003428 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003429 }
3430}
3431
Andy Hung4b17e882023-07-07 13:47:37 -07003432product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003433{
3434 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3435 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3436 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003437 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003438 }
3439 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003440 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003441 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003442 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003443 }
3444 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003445 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003446}
3447
3448
Andy Hung4b17e882023-07-07 13:47:37 -07003449AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003450{
Andy Hungf8635b62023-08-31 16:13:39 -07003451 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003452 return mOutput;
3453}
3454
Andy Hung4b17e882023-07-07 13:47:37 -07003455AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003456{
Andy Hungf8635b62023-08-31 16:13:39 -07003457 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003458 AudioStreamOut *output = mOutput;
3459 mOutput = NULL;
3460 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3461 // must push a NULL and wait for ack
3462 mOutputSink.clear();
3463 mPipeSink.clear();
3464 mNormalSink.clear();
3465 return output;
3466}
3467
Andy Hungb17d24b2023-08-29 14:26:09 -07003468// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07003469sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003470{
3471 if (mOutput == NULL) {
3472 return NULL;
3473 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003474 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003475}
3476
Andy Hung4b17e882023-07-07 13:47:37 -07003477uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003478{
3479 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3480}
3481
Andy Hung4b17e882023-07-07 13:47:37 -07003482status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003483{
3484 if (!isValidSyncEvent(event)) {
3485 return BAD_VALUE;
3486 }
3487
Andy Hungf8635b62023-08-31 16:13:39 -07003488 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003489
3490 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003491 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003492 if (event->triggerSession() == track->sessionId()) {
3493 (void) track->setSyncEvent(event);
3494 return NO_ERROR;
3495 }
3496 }
3497
3498 return NAME_NOT_FOUND;
3499}
3500
Andy Hung4b17e882023-07-07 13:47:37 -07003501bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003502{
3503 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3504}
3505
Andy Hung4b17e882023-07-07 13:47:37 -07003506void PlaybackThread::threadLoop_removeTracks(
Andy Hung11e74242023-06-26 19:20:57 -07003507 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003508{
Andy Hungfe726a62018-09-27 15:17:25 -07003509 // Miscellaneous track cleanup when removed from the active list,
3510 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003511#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003512 for (const auto& track : tracksToRemove) {
3513 if (track->isExternalTrack()) {
3514 // to track the speaker usage
3515 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003516 }
3517 }
Andy Hungfe726a62018-09-27 15:17:25 -07003518#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003519}
3520
Andy Hung4b17e882023-07-07 13:47:37 -07003521void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003522{
3523 if (!mMasterMute) {
3524 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003525 if (mOutDeviceTypeAddrs.empty()) {
3526 ALOGD("ro.audio.silent is ignored since no output device is set");
3527 return;
3528 }
Andy Hung94dfbb42023-09-06 19:41:47 -07003529 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003530 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3531 return;
3532 }
Eric Laurent81784c32012-11-19 14:55:58 -08003533 if (property_get("ro.audio.silent", value, "0") > 0) {
3534 char *endptr;
3535 unsigned long ul = strtoul(value, &endptr, 0);
3536 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003537 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003538 // The setprop command will not allow a property to be changed after
3539 // the first time it is set, so we don't have to worry about un-muting.
3540 setMasterMute_l(true);
3541 }
3542 }
3543 }
3544}
3545
3546// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07003547ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003548{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003549 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003550 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003551 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003552 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003553
3554 // If an NBAIO sink is present, use it to write the normal mixer's submix
3555 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003556
Andy Hung010a1a12014-03-13 13:57:33 -07003557 const size_t count = mBytesRemaining / mFrameSize;
3558
Simon Wilson2d590962012-11-29 15:18:50 -08003559 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003560 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1b6d46a2023-07-19 16:22:58 -07003561 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003562 if (screenState != mScreenState) {
3563 mScreenState = screenState;
3564 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3565 if (pipe != NULL) {
3566 pipe->setAvgFrames((mScreenState & 1) ?
3567 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3568 }
3569 }
Andy Hung010a1a12014-03-13 13:57:33 -07003570 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003571 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003572
Eric Laurent81784c32012-11-19 14:55:58 -08003573 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003574 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003575
Andy Hung8946a282018-04-19 20:04:56 -07003576#ifdef TEE_SINK
3577 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3578#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003579 } else {
3580 bytesWritten = framesWritten;
3581 }
3582 // otherwise use the HAL / AudioStreamOut directly
3583 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003585
Eric Laurentbfb1b832013-01-07 09:53:42 -08003586 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003587 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3588 mWriteAckSequence += 2;
3589 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003590 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003591 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003592 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003593 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003594 // FIXME We should have an implementation of timestamps for direct output threads.
3595 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003596 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003597 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003598
Eric Laurentbfb1b832013-01-07 09:53:42 -08003599 if (mUseAsyncWrite &&
3600 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3601 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003602 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003603 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003604 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003605 }
Eric Laurent81784c32012-11-19 14:55:58 -08003606 }
3607
Eric Laurent81784c32012-11-19 14:55:58 -08003608 mNumWrites++;
3609 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003610 if (mStandby) {
3611 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003612 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003613 mStandby = false;
3614 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615 return bytesWritten;
3616}
3617
Andy Hungb17d24b2023-08-29 14:26:09 -07003618// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003619void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003620 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003621{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003622 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003623 if (outputSink != nullptr) {
3624 outputSink->startMelComputation(processor);
3625 }
Vlad Popab042ee62022-10-20 18:05:00 +02003626}
3627
Andy Hungb17d24b2023-08-29 14:26:09 -07003628// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07003629void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003630{
3631 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003632 if (outputSink != nullptr) {
3633 outputSink->stopMelComputation();
3634 }
Vlad Popab042ee62022-10-20 18:05:00 +02003635}
3636
Andy Hung4b17e882023-07-07 13:47:37 -07003637void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003638{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003639 bool supportsDrain = false;
3640 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003641 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3642 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003643 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3644 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003645 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003646 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003647 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003648 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003649 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003650 }
3651}
3652
Andy Hung4b17e882023-07-07 13:47:37 -07003653void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003654{
Eric Laurent275e8e92014-11-30 15:14:47 -08003655 {
Andy Hungf8635b62023-08-31 16:13:39 -07003656 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003657 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003658 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003659 track->invalidate();
3660 }
Andy Hungdae27702016-10-31 14:01:16 -07003661 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3662 // After we exit there are no more track changes sent to BatteryNotifier
3663 // because that requires an active threadLoop.
3664 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3665 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003666 }
Eric Laurent81784c32012-11-19 14:55:58 -08003667}
3668
3669/*
3670The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003671 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003672 - mActiveSleepTimeUs from activeSleepTimeUs()
3673 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003674 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3675 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003676 - maxPeriod from frame count and sample rate (MIXER only)
3677
3678The parameters that affect these derived values are:
3679 - frame count
3680 - frame size
3681 - sample rate
3682 - device type: A2DP or not
3683 - device latency
3684 - format: PCM or not
3685 - active sleep time
3686 - idle sleep time
3687*/
3688
Andy Hung4b17e882023-07-07 13:47:37 -07003689void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003690{
Andy Hung25c2dac2014-02-27 14:56:00 -08003691 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003692 mActiveSleepTimeUs = activeSleepTimeUs();
3693 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003694
Andy Hungd58c4732023-07-20 21:31:38 -07003695 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003696
Eric Laurent42537be2016-01-08 17:16:42 -08003697 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3698 // truncating audio when going to standby.
Andy Hung94dfbb42023-09-06 19:41:47 -07003699 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003700 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3701 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3702 }
3703 }
Eric Laurent81784c32012-11-19 14:55:58 -08003704}
3705
Andy Hung4b17e882023-07-07 13:47:37 -07003706bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003707{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003708 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003709 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003710 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003711 size_t size = mTracks.size();
3712 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003713 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003714 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003715 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003716 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003717 }
3718 }
Eric Laurent13084622016-05-17 10:51:49 -07003719 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003720}
3721
Andy Hung4b17e882023-07-07 13:47:37 -07003722void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003723{
Andy Hungf8635b62023-08-31 16:13:39 -07003724 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003725 invalidateTracks_l(streamType);
3726}
3727
Andy Hung4b17e882023-07-07 13:47:37 -07003728void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07003729 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003730 invalidateTracks_l(portIds);
3731}
3732
Andy Hung4b17e882023-07-07 13:47:37 -07003733bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003734 bool trackMatch = false;
3735 const size_t size = mTracks.size();
3736 for (size_t i = 0; i < size; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07003737 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003738 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3739 t->invalidate();
3740 portIds.erase(t->portId());
3741 trackMatch = true;
3742 }
3743 if (portIds.empty()) {
3744 break;
3745 }
3746 }
3747 return trackMatch;
3748}
3749
jiabinf042b9b2021-05-07 23:46:28 +00003750// getTrackById_l must be called with holding thread lock
Andy Hung4b17e882023-07-07 13:47:37 -07003751IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003752 audio_port_handle_t trackPortId) {
3753 for (size_t i = 0; i < mTracks.size(); i++) {
3754 if (mTracks[i]->portId() == trackPortId) {
3755 return mTracks[i].get();
3756 }
3757 }
3758 return nullptr;
3759}
3760
Andy Hung4b17e882023-07-07 13:47:37 -07003761status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003762{
Glenn Kastend848eb42016-03-08 13:42:11 -08003763 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003764 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003765 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003766
Andy Hungd3639922022-04-28 18:00:49 -07003767 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003768 if (!audio_is_global_session(session)) {
3769 // player sessions on a spatializer output will use a dedicated input buffer and
3770 // will either output multi channel to mEffectBuffer if the track is spatilaized
3771 // or stereo to mPostSpatializerBuffer if not spatialized.
3772 uint32_t channelMask;
3773 bool isSessionSpatialized =
3774 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3775 if (isSessionSpatialized) {
3776 channelMask = mMixerChannelMask;
3777 } else {
3778 channelMask = mChannelMask;
3779 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003780 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003781 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003782 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003783 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003784 &halInBuffer);
3785 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003786
Andy Hung7535ed92023-07-17 17:05:00 -07003787 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003788 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3789 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3790 &halOutBuffer);
3791 if (result != OK) return result;
3792
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003793 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003794
Mikhail Naganov022b9952017-01-04 16:36:51 -08003795 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3796 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003797 } else {
3798 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3799 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3800 // mPostSpatializerBuffer as output buffer
3801 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung7535ed92023-07-17 17:05:00 -07003802 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003803 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3804 if (result != OK) return result;
Andy Hung7535ed92023-07-17 17:05:00 -07003805 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003806 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3807 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003808
Eric Laurentb62d0362021-10-26 17:40:18 +02003809 if (session == AUDIO_SESSION_DEVICE) {
3810 halInBuffer = halOutBuffer;
3811 }
3812 }
3813 } else {
Andy Hung7535ed92023-07-17 17:05:00 -07003814 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003815 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3816 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3817 &halInBuffer);
3818 if (result != OK) return result;
3819 halOutBuffer = halInBuffer;
3820 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3821 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003822 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003823 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003824 // Only one effect chain can be present in direct output thread and it uses
3825 // the sink buffer as input
3826 if (mType != DIRECT) {
3827 size_t numSamples = mNormalFrameCount
3828 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3829 + mHapticChannelCount);
Andy Hung7535ed92023-07-17 17:05:00 -07003830 const status_t allocateStatus =
3831 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003832 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003833 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003834 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003835
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003836 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003837 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3838 buffer, session);
3839 }
3840 }
3841 }
3842
3843 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003844 // Attach all tracks with same session ID to this chain.
3845 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003846 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003847 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003848 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3849 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003850 track->setMainBuffer(buffer);
3851 chain->incTrackCnt();
3852 }
3853 }
3854
3855 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -07003856 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003857 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003858 ALOGV("addEffectChain_l() activating track %p on session %d",
3859 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003860 chain->incActiveTrackCnt();
3861 }
3862 }
3863 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003864
Eric Laurentaaa44472014-09-12 17:41:50 -07003865 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003866 chain->setInBuffer(halInBuffer);
3867 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003868 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3869 // chains list in order to be processed last as it contains output device effects.
3870 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3871 // processing effects specific to an output stream before effects applied to all streams
3872 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003873 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3874 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003875 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003876 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003877 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003878 // Effect chain for other sessions are inserted at beginning of effect
3879 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003880 // sessions is not important.
3881 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003882 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3883 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003884 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003885 size_t size = mEffectChains.size();
3886 size_t i = 0;
3887 for (i = 0; i < size; i++) {
3888 if (mEffectChains[i]->sessionId() < session) {
3889 break;
3890 }
3891 }
3892 mEffectChains.insertAt(chain, i);
3893 checkSuspendOnAddEffectChain_l(chain);
3894
3895 return NO_ERROR;
3896}
3897
Andy Hung4b17e882023-07-07 13:47:37 -07003898size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003899{
Glenn Kastend848eb42016-03-08 13:42:11 -08003900 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003901
3902 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3903
3904 for (size_t i = 0; i < mEffectChains.size(); i++) {
3905 if (chain == mEffectChains[i]) {
3906 mEffectChains.removeAt(i);
3907 // detach all active tracks from the chain
Andy Hung11e74242023-06-26 19:20:57 -07003908 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003909 if (session == track->sessionId()) {
3910 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3911 chain.get(), session);
3912 chain->decActiveTrackCnt();
3913 }
3914 }
3915
3916 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003917 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07003918 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003919 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003920 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003921 chain->decTrackCnt();
3922 }
3923 }
3924 break;
3925 }
3926 }
3927 return mEffectChains.size();
3928}
3929
Andy Hung4b17e882023-07-07 13:47:37 -07003930status_t PlaybackThread::attachAuxEffect(
Andy Hung11e74242023-06-26 19:20:57 -07003931 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003932{
Andy Hungf8635b62023-08-31 16:13:39 -07003933 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003934 return attachAuxEffect_l(track, EffectId);
3935}
3936
Andy Hung4b17e882023-07-07 13:47:37 -07003937status_t PlaybackThread::attachAuxEffect_l(
Andy Hung11e74242023-06-26 19:20:57 -07003938 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003939{
3940 status_t status = NO_ERROR;
3941
3942 if (EffectId == 0) {
3943 track->setAuxBuffer(0, NULL);
3944 } else {
3945 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003946 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003947 if (effect != 0) {
3948 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3949 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3950 } else {
3951 status = INVALID_OPERATION;
3952 }
3953 } else {
3954 status = BAD_VALUE;
3955 }
3956 }
3957 return status;
3958}
3959
Andy Hung4b17e882023-07-07 13:47:37 -07003960void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003961{
3962 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07003963 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003964 if (track->auxEffectId() == effectId) {
3965 attachAuxEffect_l(track, 0);
3966 }
3967 }
3968}
3969
Andy Hung4b17e882023-07-07 13:47:37 -07003970bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003971NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003972{
Andy Hung78d8d952023-05-30 18:10:23 -07003973 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003974
Andy Hung45a38f22023-10-03 10:49:34 -07003975 if (mType == SPATIALIZER) {
3976 const pid_t tid = getTid();
3977 if (tid == -1) { // odd: we are here, we must be a running thread.
3978 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3979 } else {
3980 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3981 if (priorityBoost > 0) {
3982 stream()->setHalThreadPriority(priorityBoost);
3983 }
3984 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003985 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3986 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3987 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3988 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3989 // only on ARC.
3990 const pid_t tid = getTid();
3991 if (tid == -1) {
3992 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3993 } else {
3994 const status_t status = requestPriority(getpid(),
3995 tid,
3996 kPriorityPlaybackThreadArc,
3997 false /* isForApp */,
3998 true /* asynchronous */);
3999 if (status != OK) {
4000 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4001 status);
4002 } else {
4003 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4004 }
4005 }
Andy Hung45a38f22023-10-03 10:49:34 -07004006 }
4007
Andy Hung11e74242023-06-26 19:20:57 -07004008 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004009
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004010 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004011 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004012
4013 // MIXER
4014 nsecs_t lastWarning = 0;
4015
4016 // DUPLICATING
4017 // FIXME could this be made local to while loop?
4018 writeFrames = 0;
4019
Andy Hungefea6c52024-09-17 14:17:15 -07004020 {
4021 audio_utils::lock_guard l(mutex());
4022
4023 cacheParameters_l();
4024 checkSilentMode_l();
4025 }
4026
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004027 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004028
Andy Hungd3639922022-04-28 18:00:49 -07004029 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004030 sleepTimeShift = 0;
4031 }
4032
4033 CpuStats cpuStats;
4034 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4035
4036 acquireWakeLock();
4037
Glenn Kasteneef598c2017-04-03 14:41:13 -07004038 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4039 // thread associated with this PlaybackThread.
4040 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4041 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004042 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4043 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004044 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004045 const char *logString = NULL;
4046
rago1bb90822017-05-02 18:31:48 -07004047 // Estimated time for next buffer to be written to hal. This is used only on
4048 // suspended mode (for now) to help schedule the wait time until next iteration.
4049 nsecs_t timeLoopNextNs = 0;
4050
Andy Hung2dbffc22018-08-08 18:50:41 -07004051 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004052
Eric Laurentb3f315a2021-07-13 15:09:05 +02004053 sendCheckOutputStageEffectsEvent();
4054
Andy Hung446f4df2019-02-21 12:26:41 -08004055 // loopCount is used for statistics and diagnostics.
4056 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004057 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004058 // Log merge requests are performed during AudioFlinger binder transactions, but
4059 // that does not cover audio playback. It's requested here for that reason.
Andy Hung7535ed92023-07-17 17:05:00 -07004060 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004061
Eric Laurent81784c32012-11-19 14:55:58 -08004062 cpuStats.sample(myName);
4063
Andy Hung116bc262023-06-20 18:56:17 -07004064 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004065 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004066 bool isHapticSessionSpatialized = false;
Andy Hung11e74242023-06-26 19:20:57 -07004067 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004068
Andy Hung2dbffc22018-08-08 18:50:41 -07004069 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4070 //
Andy Hungb17d24b2023-08-29 14:26:09 -07004071 // Note: we access outDeviceTypes() outside of mutex().
Andy Hung94dfbb42023-09-06 19:41:47 -07004072 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004073 // Here, we try for the AF lock, but do not block on it as the latency
4074 // is more informational.
Andy Hung85a07452023-08-28 18:36:53 -07004075 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd25fe392023-07-13 16:52:46 -07004076 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004077 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004078 status_t status = INVALID_OPERATION;
4079 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung7535ed92023-07-17 17:05:00 -07004080 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd25fe392023-07-13 16:52:46 -07004081 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004082 && swPatches.size() > 0) {
4083 status = swPatches[0].getLatencyMs_l(&latencyMs);
4084 downstreamPatchHandle = swPatches[0].getPatchHandle();
4085 }
4086 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004087 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004088 lastDownstreamPatchHandle = downstreamPatchHandle;
4089 }
4090 if (status == OK) {
4091 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004092 // latency of 5 seconds).
4093 const double minLatency = 0., maxLatency = 5000.;
4094 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004095 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004096 } else {
4097 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004098 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004099 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004100 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004101 }
Andy Hung7535ed92023-07-17 17:05:00 -07004102 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004103 }
4104 } else {
4105 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4106 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004107 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004108 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4109 }
4110 }
4111
Eric Laurentb3f315a2021-07-13 15:09:05 +02004112 if (mCheckOutputStageEffects.exchange(false)) {
4113 checkOutputStageEffects();
4114 }
4115
Vlad Popa7e81cea2023-01-19 16:34:16 +01004116 MetadataUpdate metadataUpdate;
Andy Hungb17d24b2023-08-29 14:26:09 -07004117 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004118
Andy Hungb17d24b2023-08-29 14:26:09 -07004119 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004120
Eric Laurent021cf962014-05-13 10:18:14 -07004121 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004122 if (mCheckOutputStageEffects.load()) {
4123 continue;
4124 }
Eric Laurent10351942014-05-08 18:49:52 -07004125
Andy Hungb17d24b2023-08-29 14:26:09 -07004126 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004127 if (logString != NULL) {
4128 mNBLogWriter->logTimestamp();
4129 mNBLogWriter->log(logString);
4130 logString = NULL;
4131 }
4132
Dean Wheatley12473e92021-03-18 23:00:55 +11004133 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004134
Eric Laurent81784c32012-11-19 14:55:58 -08004135 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004136 if (mSignalPending) {
4137 // A signal was raised while we were unlocked
4138 mSignalPending = false;
4139 } else if (waitingAsyncCallback_l()) {
4140 if (exitPending()) {
4141 break;
4142 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004143 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004144 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004145 releaseWakeLock_l();
4146 released = true;
4147 }
Andy Hung10cbff12017-02-21 17:30:14 -08004148
4149 const int64_t waitNs = computeWaitTimeNs_l();
4150 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungb17d24b2023-08-29 14:26:09 -07004151 std::cv_status cvstatus =
4152 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4153 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004154 mSignalPending = true; // if timeout recheck everything
4155 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004157 if (released) {
4158 acquireWakeLock_l();
4159 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004160 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4161 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004162
4163 continue;
4164 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004165 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004166 isSuspended()) {
4167 // put audio hardware into standby after short delay
4168 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004169
4170 threadLoop_standby();
4171
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004172 // This is where we go into standby
4173 if (!mStandby) {
4174 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004175 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004176 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004177 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004178 }
Andy Hungd0979812019-02-21 15:51:44 -08004179 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004180 }
4181
Eric Tan39ec8d62018-07-24 09:49:29 -07004182 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004183 // we're about to wait, flush the binder command buffer
4184 IPCThreadState::self()->flushCommands();
4185
4186 clearOutputTracks();
4187
4188 if (exitPending()) {
4189 break;
4190 }
4191
4192 releaseWakeLock_l();
4193 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004194 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -07004195 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004196 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004197 acquireWakeLock_l();
4198
4199 mMixerStatus = MIXER_IDLE;
4200 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4201 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004202 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004203 checkSilentMode_l();
4204
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004205 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4206 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004207 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004208 sleepTimeShift = 0;
4209 }
4210
4211 continue;
4212 }
4213 }
Eric Laurent81784c32012-11-19 14:55:58 -08004214 // mMixerStatusIgnoringFastTracks is also updated internally
4215 mMixerStatus = prepareTracks_l(&tracksToRemove);
4216
Andy Hung94dfbb42023-09-06 19:41:47 -07004217 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004218
Vlad Popa7e81cea2023-01-19 16:34:16 +01004219 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004220
Andy Hungf302e812024-01-26 11:55:15 -08004221 // Acquire a local copy of active tracks with lock (release w/o lock).
4222 //
4223 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4224 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4225 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4226 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4227
4228 setHalLatencyMode_l();
4229
4230 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4231 // so this is done before we lock our effect chains.
4232 for (const auto& track : mActiveTracks) {
4233 track->updateTeePatches_l();
4234 }
4235
4236 // signal actual start of output stream when the render position reported by
4237 // the kernel starts moving.
4238 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4239 && (mKernelPositionOnStandby
4240 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4241 mHalStarted = true;
4242 mWaitHalStartCV.notify_all();
4243 }
4244
Eric Laurent81784c32012-11-19 14:55:58 -08004245 // prevent any changes in effect chain list and in each effect chain
4246 // during mixing and effect process as the audio buffers could be deleted
4247 // or modified if an effect is created or deleted
4248 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004249
4250 // Determine which session to pick up haptic data.
4251 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004252 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004253 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004254 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004255 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004256 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004257 if (effectChain != nullptr
4258 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004259 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004260 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004261 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004262 break;
4263 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004264 if (activeHapticSessionId == AUDIO_SESSION_NONE
4265 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004266 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004267 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004268 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004269 }
4270 }
4271 }
Andy Hungb17d24b2023-08-29 14:26:09 -07004272 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004273
Eric Laurentbfb1b832013-01-07 09:53:42 -08004274 if (mBytesRemaining == 0) {
4275 mCurrentWriteLength = 0;
4276 if (mMixerStatus == MIXER_TRACKS_READY) {
4277 // threadLoop_mix() sets mCurrentWriteLength
4278 threadLoop_mix();
4279 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4280 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004281 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004282 // must be written to HAL
4283 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004284 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004285 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004286
4287 // Tally underrun frames as we are inserting 0s here.
4288 for (const auto& track : activeTracks) {
Andy Hung11e74242023-06-26 19:20:57 -07004289 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004290 && !track->isStopped()
4291 && !track->isPaused()
4292 && !track->isTerminated()) {
4293 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4294 __func__, track->id(), track->getTrackStateAsString(),
4295 mNormalFrameCount);
Andy Hung11e74242023-06-26 19:20:57 -07004296 track->audioTrackServerProxy()->tallyUnderrunFrames(
4297 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004298 }
4299 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004300 }
4301 }
Andy Hung98ef9782014-03-04 14:46:50 -08004302 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004303 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004304 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004305 // or mSinkBuffer (if there are no effects and there is no data already copied to
4306 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004307 //
4308 // This is done pre-effects computation; if effects change to
4309 // support higher precision, this needs to move.
4310 //
4311 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004312 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004313 uint32_t mixerChannelCount = mEffectBufferValid ?
4314 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004315 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004316 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4317 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4318
David Li88ee0902022-06-22 10:01:21 +08004319 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4320 // do these processes after effects are applied.
4321 if (!mEffectBufferValid) {
4322 // mono blend occurs for mixer threads only (not direct or offloaded)
4323 // and is handled here if we're going directly to the sink.
4324 if (requireMonoBlend()) {
4325 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4326 mNormalFrameCount, true /*limit*/);
4327 }
Andy Hung2ddee192015-12-18 17:34:44 -08004328
David Li88ee0902022-06-22 10:01:21 +08004329 if (!hasFastMixer()) {
4330 // Balance must take effect after mono conversion.
4331 // We do it here if there is no FastMixer.
4332 // mBalance detects zero balance within the class for speed
4333 // (not needed here).
4334 mBalance.setBalance(mMasterBalance.load());
4335 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4336 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004337 }
4338
Andy Hung98ef9782014-03-04 14:46:50 -08004339 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004340 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004341
4342 // If we're going directly to the sink and there are haptic channels,
4343 // we should adjust channels as the sample data is partially interleaved
4344 // in this case.
4345 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4346 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4347 mChannelCount + mHapticChannelCount,
4348 audio_bytes_per_sample(format),
4349 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4350 }
Andy Hung98ef9782014-03-04 14:46:50 -08004351 }
4352
Eric Laurentbfb1b832013-01-07 09:53:42 -08004353 mBytesRemaining = mCurrentWriteLength;
4354 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004355 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4356 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4357 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4358 mBytesWritten += mBytesRemaining;
4359 mFramesWritten += framesRemaining;
4360 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004361 mBytesRemaining = 0;
4362 }
Eric Laurent81784c32012-11-19 14:55:58 -08004363
Eric Laurentbfb1b832013-01-07 09:53:42 -08004364 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004365 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004366 for (size_t i = 0; i < effectChains.size(); i ++) {
4367 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004368 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004369 if (activeHapticSessionId != AUDIO_SESSION_NONE
4370 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004371 // Haptic data is active in this case, copy it directly from
4372 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004373 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4374 audio_channel_count_from_out_mask(mMixerChannelMask) :
4375 mChannelCount;
4376 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4377 hapticSessionChannelCount = mChannelCount;
4378 }
4379
jiabin47affe52019-04-04 18:02:07 -07004380 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004381 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004382 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004383 memcpy_by_audio_format(
4384 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004385 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004386 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004387 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004388 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004389 }
Eric Laurent81784c32012-11-19 14:55:58 -08004390 }
4391 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004392 // Process effect chains for offloaded thread even if no audio
4393 // was read from audio track: process only updates effect state
4394 // and thus does have to be synchronized with audio writes but may have
4395 // to be called while waiting for async write callback
4396 if (mType == OFFLOAD) {
4397 for (size_t i = 0; i < effectChains.size(); i ++) {
4398 effectChains[i]->process_l();
4399 }
4400 }
Eric Laurent81784c32012-11-19 14:55:58 -08004401
Andy Hung98ef9782014-03-04 14:46:50 -08004402 // Only if the Effects buffer is enabled and there is data in the
4403 // Effects buffer (buffer valid), we need to
4404 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004405 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004406 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004407 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004408 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004409 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004410 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004411 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004412 }
4413
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004414 if (!hasFastMixer()) {
4415 // Balance must take effect after mono conversion.
4416 // We do it here if there is no FastMixer.
4417 // mBalance detects zero balance within the class for speed (not needed here).
4418 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004419 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004420 }
4421
Eric Laurentb62d0362021-10-26 17:40:18 +02004422 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4423 // mPostSpatializerBuffer if the haptics track is spatialized.
4424 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4425 // For other thread types, the haptics channels are already in mEffectBuffer.
4426 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4427 const size_t srcBufferSize = mNormalFrameCount *
4428 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4429 mEffectBufferFormat);
4430 const size_t dstBufferSize = mNormalFrameCount
4431 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4432
4433 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4434 mEffectBufferFormat,
4435 (uint8_t*)mEffectBuffer + srcBufferSize,
4436 mEffectBufferFormat,
4437 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004438 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004439 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4440 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4441 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4442 // Clamp PCM float values more than this distance from 0 to insulate
4443 // a HAL which doesn't handle NaN correctly.
4444 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4445 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4446 static_cast<const float*>(effectBuffer),
4447 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4448 } else {
4449 memcpy_by_audio_format(mSinkBuffer, mFormat,
4450 effectBuffer, mEffectBufferFormat, framesToCopy);
4451 }
jiabin245cdd92018-12-07 17:55:15 -08004452 // The sample data is partially interleaved when haptic channels exist,
4453 // we need to adjust channels here.
4454 if (mHapticChannelCount > 0) {
4455 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4456 mChannelCount + mHapticChannelCount,
4457 audio_bytes_per_sample(mFormat),
4458 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4459 }
Andy Hung98ef9782014-03-04 14:46:50 -08004460 }
4461
Eric Laurent81784c32012-11-19 14:55:58 -08004462 // enable changes in effect chain
4463 unlockEffectChains(effectChains);
4464
Vlad Popafce10862023-02-03 10:37:07 +01004465 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung7535ed92023-07-17 17:05:00 -07004466 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004467 metadataUpdate.playbackMetadataUpdate);
4468 }
4469
Eric Laurentbfb1b832013-01-07 09:53:42 -08004470 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004471 // mSleepTimeUs == 0 means we must write to audio hardware
4472 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004473 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004474 // writePeriodNs is updated >= 0 when ret > 0.
4475 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004476 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004477 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004478 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004479 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004480 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004481 if (ret < 0) {
4482 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004483 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004484 mBytesWritten += ret;
4485 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004486 const int64_t frames = ret / mFrameSize;
4487 mFramesWritten += frames;
4488
4489 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4490 // process information relating to write time.
4491 if (audio_has_proportional_frames(mFormat)) {
4492 // we are in a continuous mixing cycle
4493 if (mMixerStatus == MIXER_TRACKS_READY &&
4494 loopCount == lastLoopCountWritten + 1) {
4495
4496 const double jitterMs =
4497 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4498 {frames, writePeriodNs},
4499 {0, 0} /* lastTimestamp */, mSampleRate);
4500 const double processMs =
4501 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4502
Andy Hungf8635b62023-08-31 16:13:39 -07004503 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004504 mIoJitterMs.add(jitterMs);
4505 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004506
4507 if (mPipeSink.get() != nullptr) {
4508 // Using the Monopipe availableToWrite, we estimate the current
4509 // buffer size.
4510 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4511 const ssize_t
4512 availableToWrite = mPipeSink->availableToWrite();
4513 const size_t pipeFrames = monoPipe->maxFrames();
4514 const size_t
4515 remainingFrames = pipeFrames - max(availableToWrite, 0);
4516 mMonopipePipeDepthStats.add(remainingFrames);
4517 }
Andy Hung446f4df2019-02-21 12:26:41 -08004518 }
4519
4520 // write blocked detection
4521 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004522 if ((mType == MIXER || mType == SPATIALIZER)
4523 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004524 mNumDelayedWrites++;
4525 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4526 ATRACE_NAME("underrun");
4527 ALOGW("write blocked for %lld msecs, "
4528 "%d delayed writes, thread %d",
4529 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4530 mNumDelayedWrites, mId);
4531 lastWarning = lastIoEndNs;
4532 }
4533 }
4534 }
4535 // update timing info.
4536 mLastIoBeginNs = lastIoBeginNs;
4537 mLastIoEndNs = lastIoEndNs;
4538 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004539 }
4540 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4541 (mMixerStatus == MIXER_DRAIN_ALL)) {
4542 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004543 }
Andy Hungd3639922022-04-28 18:00:49 -07004544 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004545
4546 if (mThreadThrottle
4547 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004548 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004549 // Limit MixerThread data processing to no more than twice the
4550 // expected processing rate.
4551 //
4552 // This helps prevent underruns with NuPlayer and other applications
4553 // which may set up buffers that are close to the minimum size, or use
4554 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4555 //
4556 // The throttle smooths out sudden large data drains from the device,
4557 // e.g. when it comes out of standby, which often causes problems with
4558 // (1) mixer threads without a fast mixer (which has its own warm-up)
4559 // (2) minimum buffer sized tracks (even if the track is full,
4560 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004561 //
4562 // Total time spent in last processing cycle equals time spent in
4563 // 1. threadLoop_write, as well as time spent in
4564 // 2. threadLoop_mix (significant for heavy mixing, especially
4565 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004566
Andy Hung446f4df2019-02-21 12:26:41 -08004567 // it's OK if deltaMs is an overestimate.
4568
4569 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004570
Ivan Lozanoea04d392017-11-07 14:37:07 -08004571 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004572 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004573 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004574
Andy Hung08fb1742015-05-31 23:22:10 -07004575 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004576 // notify of throttle start on verbose log
4577 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4578 "mixer(%p) throttle begin:"
4579 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004580 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004581 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004582 // Throttle must be attributed to the previous mixer loop's write time
4583 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004584 // This also ensures proper timing statistics.
4585 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004586 } else {
4587 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4588 if (diff > 0) {
4589 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004590 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004591 ALOGD_IF(!isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004592 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004593 !isSingleDeviceType(
Andy Hung94dfbb42023-09-06 19:41:47 -07004594 outDeviceTypes_l(),
4595 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004596 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004597 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4598 }
Andy Hung08fb1742015-05-31 23:22:10 -07004599 }
4600 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004601 }
Eric Laurent81784c32012-11-19 14:55:58 -08004602
Eric Laurentbfb1b832013-01-07 09:53:42 -08004603 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004604 ATRACE_BEGIN("sleep");
Andy Hungb17d24b2023-08-29 14:26:09 -07004605 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004606 // suspended requires accurate metering of sleep time.
4607 if (isSuspended()) {
4608 // advance by expected sleepTime
4609 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4610 const nsecs_t nowNs = systemTime();
4611
4612 // compute expected next time vs current time.
4613 // (negative deltas are treated as delays).
4614 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4615 if (deltaNs < -kMaxNextBufferDelayNs) {
4616 // Delays longer than the max allowed trigger a reset.
4617 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4618 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4619 timeLoopNextNs = nowNs + deltaNs;
4620 } else if (deltaNs < 0) {
4621 // Delays within the max delay allowed: zero the delta/sleepTime
4622 // to help the system catch up in the next iteration(s)
4623 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4624 deltaNs = 0;
4625 }
4626 // update sleep time (which is >= 0)
4627 mSleepTimeUs = deltaNs / 1000;
4628 }
Eric Laurente93cc032016-05-05 10:15:10 -07004629 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004630 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004631 }
Glenn Kastene7754022014-10-31 12:11:26 -07004632 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004633 }
Eric Laurent81784c32012-11-19 14:55:58 -08004634 }
4635
4636 // Finally let go of removed track(s), without the lock held
4637 // since we can't guarantee the destructors won't acquire that
4638 // same lock. This will also mutate and push a new fast mixer state.
4639 threadLoop_removeTracks(tracksToRemove);
4640 tracksToRemove.clear();
4641
4642 // FIXME I don't understand the need for this here;
4643 // it was in the original code but maybe the
4644 // assignment in saveOutputTracks() makes this unnecessary?
4645 clearOutputTracks();
4646
4647 // Effect chains will be actually deleted here if they were removed from
4648 // mEffectChains list during mixing or effects processing
4649 effectChains.clear();
4650
4651 // FIXME Note that the above .clear() is no longer necessary since effectChains
4652 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004653
4654 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004655 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004656 mThreadloopExecutor.process(); // process any remaining deferred actions.
4657 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004658
Eric Laurentbfb1b832013-01-07 09:53:42 -08004659 threadLoop_exit();
4660
Eric Laurentcf817a22014-08-04 20:36:31 -07004661 if (!mStandby) {
4662 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004663 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004664 }
4665
4666 releaseWakeLock();
4667
4668 ALOGV("Thread %p type %d exiting", this, mType);
4669 return false;
4670}
4671
Andy Hung4b17e882023-07-07 13:47:37 -07004672void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004673{
Dean Wheatley12473e92021-03-18 23:00:55 +11004674 if (mStandby) {
4675 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4676 return;
4677 } else if (mHwPaused) {
4678 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4679 return;
4680 }
4681
4682 // Gather the framesReleased counters for all active tracks,
4683 // and associate with the sink frames written out. We need
4684 // this to convert the sink timestamp to the track timestamp.
4685 bool kernelLocationUpdate = false;
4686 ExtendedTimestamp timestamp; // use private copy to fetch
4687
4688 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4689 // HAL may be draining some small duration buffered data for fade out.
4690 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4691 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4692 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4693 mSampleRate);
4694
Andy Hung94dfbb42023-09-06 19:41:47 -07004695 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004696 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4697 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4698 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4699 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4700 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4701 = correctedTimestamp.mFrames;
4702 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4703 = correctedTimestamp.mTimeNs;
4704 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4705 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4706 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4707
4708 // Note: Downstream latency only added if timestamp correction enabled.
4709 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4710 const int64_t newPosition =
4711 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4712 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4713 // prevent retrograde
4714 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4715 newPosition,
4716 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4717 - mSuspendedFrames));
4718 }
4719 }
4720
4721 // We always fetch the timestamp here because often the downstream
4722 // sink will block while writing.
4723
4724 // We keep track of the last valid kernel position in case we are in underrun
4725 // and the normal mixer period is the same as the fast mixer period, or there
4726 // is some error from the HAL.
4727 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4728 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4729 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4730 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4731 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4732
4733 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4734 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4735 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4736 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4737 }
4738
4739 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4740 kernelLocationUpdate = true;
4741 } else {
4742 ALOGVV("getTimestamp error - no valid kernel position");
4743 }
4744
4745 // copy over kernel info
4746 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4747 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4748 + mSuspendedFrames; // add frames discarded when suspended
4749 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4750 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4751 } else {
4752 mTimestampVerifier.error();
4753 }
4754
4755 // mFramesWritten for non-offloaded tracks are contiguous
4756 // even after standby() is called. This is useful for the track frame
4757 // to sink frame mapping.
4758 bool serverLocationUpdate = false;
4759 if (mFramesWritten != mLastFramesWritten) {
4760 serverLocationUpdate = true;
4761 mLastFramesWritten = mFramesWritten;
4762 }
4763 // Only update timestamps if there is a meaningful change.
4764 // Either the kernel timestamp must be valid or we have written something.
4765 if (kernelLocationUpdate || serverLocationUpdate) {
4766 if (serverLocationUpdate) {
4767 // use the time before we called the HAL write - it is a bit more accurate
4768 // to when the server last read data than the current time here.
4769 //
4770 // If we haven't written anything, mLastIoBeginNs will be -1
4771 // and we use systemTime().
4772 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4773 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung160664b2023-09-15 18:19:28 -07004774 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004775 }
4776
Andy Hung11e74242023-06-26 19:20:57 -07004777 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004778 if (!t->isFastTrack()) {
4779 t->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07004780 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004781 mFramesWritten,
4782 mSampleRate,
4783 mTimestamp);
4784 }
4785 }
4786 }
4787
4788 if (audio_has_proportional_frames(mFormat)) {
4789 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4790 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4791 mLatencyMs.add(latencyMs);
4792 }
4793 }
4794#if 0
4795 // logFormat example
4796 if (z % 100 == 0) {
4797 timespec ts;
4798 clock_gettime(CLOCK_MONOTONIC, &ts);
4799 LOGT("This is an integer %d, this is a float %f, this is my "
4800 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4801 LOGT("A deceptive null-terminated string %\0");
4802 }
4803 ++z;
4804#endif
4805}
4806
Andy Hungb17d24b2023-08-29 14:26:09 -07004807// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07004808void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungb17d24b2023-08-29 14:26:09 -07004809NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004810{
Andy Hunga7187712023-12-05 17:28:17 -08004811 if (tracksToRemove.empty()) return;
4812
4813 // Block all incoming TrackHandle requests until we are finished with the release.
4814 setThreadBusy_l(true);
4815
Andy Hungfe726a62018-09-27 15:17:25 -07004816 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004817 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004818 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004819 if (chain != 0) {
4820 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4821 __func__, track->id(), chain.get(), track->sessionId());
4822 chain->decActiveTrackCnt();
4823 }
Andy Hunga7187712023-12-05 17:28:17 -08004824
Andy Hungfe726a62018-09-27 15:17:25 -07004825 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hunga7187712023-12-05 17:28:17 -08004826 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004827 if (track->isExternalTrack()) {
Andy Hunga7187712023-12-05 17:28:17 -08004828 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004829 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004830 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004831 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004832 }
Andy Hunga7187712023-12-05 17:28:17 -08004833 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004834 }
jiabineb3bda02020-06-30 14:07:03 -07004835 if (mHapticChannelCount > 0 &&
4836 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004837 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungb17d24b2023-08-29 14:26:09 -07004838 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004839 // Unlock due to VibratorService will lock for this call and will
4840 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung76cb9152023-07-20 21:23:42 -07004841 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungb17d24b2023-08-29 14:26:09 -07004842 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004843
4844 // When the track is stop, set the haptic intensity as MUTE
4845 // for the HapticGenerator effect.
4846 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004847 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004848 }
jiabin245cdd92018-12-07 17:55:15 -08004849 }
Andy Hunga7187712023-12-05 17:28:17 -08004850
4851 // Under lock, the track is removed from the active tracks list.
4852 //
4853 // Once the track is no longer active, the TrackHandle may directly
4854 // modify it as the threadLoop() is no longer responsible for its maintenance.
4855 // Do not modify the track from threadLoop after the mutex is unlocked
4856 // if it is not active.
4857 mActiveTracks.remove(track);
4858
4859 if (track->isTerminated()) {
4860 // remove from our tracks vector
4861 removeTrack_l(track);
4862 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004863 }
Andy Hunga7187712023-12-05 17:28:17 -08004864
4865 // Allow incoming TrackHandle requests. We still hold the mutex,
4866 // so pending TrackHandle requests will occur after we unlock it.
4867 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004868}
Eric Laurent81784c32012-11-19 14:55:58 -08004869
Andy Hung4b17e882023-07-07 13:47:37 -07004870status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004871{
4872 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004873 ExtendedTimestamp ets;
4874 status_t status = mNormalSink->getTimestamp(ets);
4875 if (status == NO_ERROR) {
4876 status = ets.getBestTimestamp(&timestamp);
4877 }
4878 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004879 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004880 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004881 collectTimestamps_l();
4882 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4883 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004884 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004885 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4886 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4887 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4888 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4889 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004890 }
4891 return INVALID_OPERATION;
4892}
Eric Laurent1c333e22014-05-20 10:48:17 -07004893
Eric Laurenteab90452019-06-24 15:17:46 -07004894// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4895// still applied by the mixer.
4896// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4897// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4898// if more than one track are active
Andy Hung4b17e882023-07-07 13:47:37 -07004899status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004900{
4901 status_t result = NO_ERROR;
4902 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4903 if (*volume != mLeftVolFloat) {
4904 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004905 // HAL can return INVALID_OPERATION if operation is not supported.
4906 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004907 "Error when setting output stream volume: %d", result);
4908 if (result == NO_ERROR) {
4909 mLeftVolFloat = *volume;
4910 }
4911 }
4912 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4913 // remove stream volume contribution from software volume.
4914 if (mLeftVolFloat == *volume) {
4915 *volume = 1.0f;
4916 }
4917 }
4918 return result;
4919}
4920
Andy Hung4b17e882023-07-07 13:47:37 -07004921status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004922 audio_patch_handle_t *handle)
4923{
Andy Hungf60abce2016-08-26 11:37:54 -07004924 status_t status;
4925 if (property_get_bool("af.patch_park", false /* default_value */)) {
4926 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4927 // or if HAL does not properly lock against access.
4928 AutoPark<FastMixer> park(mFastMixer);
4929 status = PlaybackThread::createAudioPatch_l(patch, handle);
4930 } else {
4931 status = PlaybackThread::createAudioPatch_l(patch, handle);
4932 }
Eric Laurentb0463942022-12-20 16:31:10 +01004933
4934 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004935 return status;
4936}
4937
Andy Hung4b17e882023-07-07 13:47:37 -07004938status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004939 audio_patch_handle_t *handle)
4940{
4941 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004942
4943 // store new device and send to effects
4944 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004945 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004946 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004947 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4948 && !mOutput->audioHwDev->supportsAudioPatches(),
4949 "Enumerated device type(%#x) must not be used "
4950 "as it does not support audio patches",
4951 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004952 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004953 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4954 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004955 }
4956
François Gaffie0c280aa2018-07-25 10:02:15 +02004957 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004958#ifdef ADD_BATTERY_DATA
4959 // when changing the audio output device, call addBatteryData to notify
4960 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004961 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004962 uint32_t params = 0;
4963 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004964 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004965 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 }
4967
Eric Laurent054d9d32015-04-24 08:48:48 -07004968 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004969 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004970 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4971 }
4972
4973 if (params != 0) {
4974 addBatteryData(params);
4975 }
4976 }
4977#endif
4978
4979 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004980 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004981 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004982
jiabinc52b1ff2019-10-31 17:20:42 -07004983 // mPatch.num_sinks is not set when the thread is created so that
4984 // the first patch creation triggers an ioConfigChanged callback
4985 bool configChanged = (mPatch.num_sinks == 0) ||
4986 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004987 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004988 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004989 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004990
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004991 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004992 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4993 status = hwDevice->createAudioPatch(patch->num_sources,
4994 patch->sources,
4995 patch->num_sinks,
4996 patch->sinks,
4997 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004998 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004999 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005000 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005001 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005002 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005003
5004 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005005 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005006 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005007 // also dispatch to active AudioTracks for MediaMetrics
5008 for (const auto &track : mActiveTracks) {
5009 track->logEndInterval();
5010 track->logBeginInterval(patchSinksAsString);
5011 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005012
Eric Laurente8726fe2015-06-26 09:39:24 -07005013 if (configChanged) {
5014 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5015 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005016 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005017 mActiveTracks.setHasChanged();
5018
Eric Laurent1c333e22014-05-20 10:48:17 -07005019 return status;
5020}
5021
Andy Hung4b17e882023-07-07 13:47:37 -07005022status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005023{
Andy Hungf60abce2016-08-26 11:37:54 -07005024 status_t status;
5025 if (property_get_bool("af.patch_park", false /* default_value */)) {
5026 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5027 // or if HAL does not properly lock against access.
5028 AutoPark<FastMixer> park(mFastMixer);
5029 status = PlaybackThread::releaseAudioPatch_l(handle);
5030 } else {
5031 status = PlaybackThread::releaseAudioPatch_l(handle);
5032 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005033 return status;
5034}
5035
Andy Hung4b17e882023-07-07 13:47:37 -07005036status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005037{
5038 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005039
jiabinc52b1ff2019-10-31 17:20:42 -07005040 mPatch = audio_patch{};
5041 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005042
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005043 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005044 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5045 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005046 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005047 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005048 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005049 // Force meteadata update after a route change
5050 mActiveTracks.setHasChanged();
5051
Eric Laurent1c333e22014-05-20 10:48:17 -07005052 return status;
5053}
5054
Andy Hung4b17e882023-07-07 13:47:37 -07005055void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005056{
Andy Hungf8635b62023-08-31 16:13:39 -07005057 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005058 mTracks.add(track);
5059}
5060
Andy Hung4b17e882023-07-07 13:47:37 -07005061void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005062{
Andy Hungf8635b62023-08-31 16:13:39 -07005063 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005064 destroyTrack_l(track);
5065}
5066
Andy Hung4b17e882023-07-07 13:47:37 -07005067void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005068{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005069 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005070 config->role = AUDIO_PORT_ROLE_SOURCE;
5071 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5072 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005073 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5074 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5075 config->flags.output = mOutput->flags;
5076 }
Eric Laurent83b88082014-06-20 18:31:16 -07005077}
5078
Eric Laurent81784c32012-11-19 14:55:58 -08005079// ----------------------------------------------------------------------------
5080
Andy Hung4b17e882023-07-07 13:47:37 -07005081/* static */
5082sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07005083 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung4b17e882023-07-07 13:47:37 -07005084 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07005085 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07005086}
5087
Andy Hung7535ed92023-07-17 17:05:00 -07005088MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005089 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07005090 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005091 // mAudioMixer below
5092 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005093 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005094 mFastMixerFutex(0),
5095 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005096 // mOutputSink below
5097 // mPipeSink below
5098 // mNormalSink below
5099{
jiabinc52b1ff2019-10-31 17:20:42 -07005100 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005101 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005102 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005103 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5104 mNormalFrameCount);
5105 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5106
Andy Hungfbfc3952015-01-15 13:33:51 -08005107 if (type == DUPLICATING) {
5108 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5109 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5110 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung7de02c92024-06-25 17:07:58 -07005111 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5112 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005113 return;
5114 }
Eric Laurent81784c32012-11-19 14:55:58 -08005115 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005116 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005117 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005118 const NBAIO_Format offers[1] = {Format_from_SR_C(
5119 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005120#if !LOG_NDEBUG
5121 ssize_t index =
5122#else
5123 (void)
5124#endif
5125 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005126 ALOG_ASSERT(index == 0);
5127
5128 // initialize fast mixer depending on configuration
5129 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005130 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005131 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005132 } else {
5133 switch (kUseFastMixer) {
5134 case FastMixer_Never:
5135 initFastMixer = false;
5136 break;
5137 case FastMixer_Always:
5138 initFastMixer = true;
5139 break;
5140 case FastMixer_Static:
5141 case FastMixer_Dynamic:
Henrik Tillman470b3992024-10-08 12:49:28 +02005142 if (mType == MIXER && (output->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) {
5143 /* Do not init fast mixer on deep buffer, warn if buffers are confed too small */
5144 initFastMixer = false;
5145 ALOGW_IF(mFrameCount * 1000 / mSampleRate < kMinNormalSinkBufferSizeMs,
5146 "HAL DEEP BUFFER Buffer (%zu ms) is smaller than set minimal buffer "
5147 "(%u ms), seems like a configuration error",
5148 mFrameCount * 1000 / mSampleRate, kMinNormalSinkBufferSizeMs);
5149 } else {
5150 initFastMixer = mFrameCount < mNormalFrameCount;
5151 }
Eric Laurentb62d0362021-10-26 17:40:18 +02005152 break;
5153 }
5154 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5155 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5156 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005157 }
5158 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005159 audio_format_t fastMixerFormat;
5160 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5161 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5162 } else {
5163 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5164 }
5165 if (mFormat != fastMixerFormat) {
5166 // change our Sink format to accept our intermediate precision
5167 mFormat = fastMixerFormat;
5168 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005169 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005170 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5171 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5172 }
Eric Laurent81784c32012-11-19 14:55:58 -08005173
5174 // create a MonoPipe to connect our submix to FastMixer
5175 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005176
Andy Hung1258c1a2014-05-23 21:22:17 -07005177 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005178 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005179 format.mFormat = fastMixerFormat;
5180 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5181
Eric Laurent81784c32012-11-19 14:55:58 -08005182 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5183 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5184 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5185 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005186 const NBAIO_Format offersFast[1] = {format};
5187 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005188#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005189 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005190#else
5191 (void)
5192#endif
Andy Hung920f6572022-10-06 12:09:49 -07005193 monoPipe->negotiate(offersFast, std::size(offersFast),
5194 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005195 ALOG_ASSERT(index == 0);
5196 monoPipe->setAvgFrames((mScreenState & 1) ?
5197 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5198 mPipeSink = monoPipe;
5199
Eric Laurent81784c32012-11-19 14:55:58 -08005200 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005201 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005202 FastMixerStateQueue *sq = mFastMixer->sq();
5203#ifdef STATE_QUEUE_DUMP
5204 sq->setObserverDump(&mStateQueueObserverDump);
5205 sq->setMutatorDump(&mStateQueueMutatorDump);
5206#endif
5207 FastMixerState *state = sq->begin();
5208 FastTrack *fastTrack = &state->mFastTracks[0];
5209 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5210 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5211 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005212 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5213 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5214 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005215 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005216 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005217 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005218 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005219 fastTrack->mGeneration++;
5220 state->mFastTracksGen++;
5221 state->mTrackMask = 1;
5222 // fast mixer will use the HAL output sink
5223 state->mOutputSink = mOutputSink.get();
5224 state->mOutputSinkGen++;
5225 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005226 // specify sink channel mask when haptic channel mask present as it can not
5227 // be calculated directly from channel count
5228 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005229 ? AUDIO_CHANNEL_NONE
5230 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005231 state->mCommand = FastMixerState::COLD_IDLE;
5232 // already done in constructor initialization list
5233 //mFastMixerFutex = 0;
5234 state->mColdFutexAddr = &mFastMixerFutex;
5235 state->mColdGen++;
5236 state->mDumpState = &mFastMixerDumpState;
Andy Hung7535ed92023-07-17 17:05:00 -07005237 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005238 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005239 sq->end();
5240 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5241
Eric Tan0513b5d2018-09-17 10:32:48 -07005242 NBLog::thread_info_t info;
5243 info.id = mId;
5244 info.type = NBLog::FASTMIXER;
5245 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5246
Eric Laurent81784c32012-11-19 14:55:58 -08005247 // start the fast mixer
5248 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5249 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005250 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005251 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005252
5253#ifdef AUDIO_WATCHDOG
5254 // create and start the watchdog
5255 mAudioWatchdog = new AudioWatchdog();
5256 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5257 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5258 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005259 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005260#endif
Andy Hung8946a282018-04-19 20:04:56 -07005261 } else {
5262#ifdef TEE_SINK
5263 // Only use the MixerThread tee if there is no FastMixer.
5264 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5265 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5266#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005267 }
5268
5269 switch (kUseFastMixer) {
5270 case FastMixer_Never:
5271 case FastMixer_Dynamic:
5272 mNormalSink = mOutputSink;
5273 break;
5274 case FastMixer_Always:
5275 mNormalSink = mPipeSink;
5276 break;
5277 case FastMixer_Static:
5278 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5279 break;
5280 }
Andy Hung7de02c92024-06-25 17:07:58 -07005281 // setMasterBalance needs to be called after the FastMixer
5282 // (if any) is set up, in order to deliver the balance settings to it.
5283 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005284}
5285
Andy Hung4b17e882023-07-07 13:47:37 -07005286MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005287{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005288 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005289 FastMixerStateQueue *sq = mFastMixer->sq();
5290 FastMixerState *state = sq->begin();
5291 if (state->mCommand == FastMixerState::COLD_IDLE) {
5292 int32_t old = android_atomic_inc(&mFastMixerFutex);
5293 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005294 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005295 }
5296 }
5297 state->mCommand = FastMixerState::EXIT;
5298 sq->end();
5299 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5300 mFastMixer->join();
5301 // Though the fast mixer thread has exited, it's state queue is still valid.
5302 // We'll use that extract the final state which contains one remaining fast track
5303 // corresponding to our sub-mix.
5304 state = sq->begin();
5305 ALOG_ASSERT(state->mTrackMask == 1);
5306 FastTrack *fastTrack = &state->mFastTracks[0];
5307 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5308 delete fastTrack->mBufferProvider;
5309 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005310 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005311#ifdef AUDIO_WATCHDOG
5312 if (mAudioWatchdog != 0) {
5313 mAudioWatchdog->requestExit();
5314 mAudioWatchdog->requestExitAndWait();
5315 mAudioWatchdog.clear();
5316 }
5317#endif
5318 }
Andy Hung7535ed92023-07-17 17:05:00 -07005319 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005320 delete mAudioMixer;
5321}
5322
Andy Hung4b17e882023-07-07 13:47:37 -07005323void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005324 PlaybackThread::onFirstRef();
5325
Andy Hungf8635b62023-08-31 16:13:39 -07005326 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005327 if (mOutput != nullptr && mOutput->stream != nullptr) {
5328 status_t status = mOutput->stream->setLatencyModeCallback(this);
5329 if (status != INVALID_OPERATION) {
5330 updateHalSupportedLatencyModes_l();
5331 }
5332 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5333 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5334 mBluetoothLatencyModesEnabled.store(
5335 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5336 }
5337}
Eric Laurent81784c32012-11-19 14:55:58 -08005338
Andy Hung4b17e882023-07-07 13:47:37 -07005339uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005340{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005341 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005342 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5343 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5344 }
5345 return latency;
5346}
5347
Andy Hung4b17e882023-07-07 13:47:37 -07005348ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005349{
5350 // FIXME we should only do one push per cycle; confirm this is true
5351 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005352 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005353 FastMixerStateQueue *sq = mFastMixer->sq();
5354 FastMixerState *state = sq->begin();
5355 if (state->mCommand != FastMixerState::MIX_WRITE &&
5356 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5357 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005358
5359 // FIXME workaround for first HAL write being CPU bound on some devices
5360 ATRACE_BEGIN("write");
5361 mOutput->write((char *)mSinkBuffer, 0);
5362 ATRACE_END();
5363
Eric Laurent81784c32012-11-19 14:55:58 -08005364 int32_t old = android_atomic_inc(&mFastMixerFutex);
5365 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005366 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005367 }
5368#ifdef AUDIO_WATCHDOG
5369 if (mAudioWatchdog != 0) {
5370 mAudioWatchdog->resume();
5371 }
5372#endif
5373 }
5374 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005375#ifdef FAST_THREAD_STATISTICS
Andy Hung7535ed92023-07-17 17:05:00 -07005376 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005377 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005378#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005379 sq->end();
5380 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5381 if (kUseFastMixer == FastMixer_Dynamic) {
5382 mNormalSink = mPipeSink;
5383 }
5384 } else {
5385 sq->end(false /*didModify*/);
5386 }
5387 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005389}
5390
Andy Hung4b17e882023-07-07 13:47:37 -07005391void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005392{
5393 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005394 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005395 FastMixerStateQueue *sq = mFastMixer->sq();
5396 FastMixerState *state = sq->begin();
5397 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005398 // Report any frames trapped in the Monopipe
5399 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5400 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5401 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5402 "monoPipeWritten:%lld monoPipeLeft:%lld",
5403 (long long)mFramesWritten, (long long)mSuspendedFrames,
5404 (long long)mPipeSink->framesWritten(), pipeFrames);
5405 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5406
Eric Laurent81784c32012-11-19 14:55:58 -08005407 state->mCommand = FastMixerState::COLD_IDLE;
5408 state->mColdFutexAddr = &mFastMixerFutex;
5409 state->mColdGen++;
5410 mFastMixerFutex = 0;
5411 sq->end();
5412 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5413 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5414 if (kUseFastMixer == FastMixer_Dynamic) {
5415 mNormalSink = mOutputSink;
5416 }
5417#ifdef AUDIO_WATCHDOG
5418 if (mAudioWatchdog != 0) {
5419 mAudioWatchdog->pause();
5420 }
5421#endif
5422 } else {
5423 sq->end(false /*didModify*/);
5424 }
5425 }
5426 PlaybackThread::threadLoop_standby();
5427}
5428
Andy Hung4b17e882023-07-07 13:47:37 -07005429bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430{
5431 return false;
5432}
5433
Andy Hung4b17e882023-07-07 13:47:37 -07005434bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005435{
5436 return !mStandby;
5437}
5438
Andy Hung4b17e882023-07-07 13:47:37 -07005439bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005440{
Andy Hungf8635b62023-08-31 16:13:39 -07005441 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442 return waitingAsyncCallback_l();
5443}
5444
Eric Laurent81784c32012-11-19 14:55:58 -08005445// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung4b17e882023-07-07 13:47:37 -07005446void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005447{
Andy Hung160664b2023-09-15 18:19:28 -07005448 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5449 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005450 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005451 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005452 // discard any pending drain or write ack by incrementing sequence
5453 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5454 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005455 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005456 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5457 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005459 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005460 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005461}
5462
Andy Hung4b17e882023-07-07 13:47:37 -07005463void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005464{
5465 ALOGV("signal playback thread");
5466 broadcast_l();
5467}
5468
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005469void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005470{
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005471 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005472 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5473 invalidateTracks((audio_stream_type_t)i);
5474 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00005475 if (isHardError) {
5476 mAfThreadCallback->onHardError(allTrackPortIds);
5477 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005478}
5479
Andy Hung4b17e882023-07-07 13:47:37 -07005480void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005481{
Eric Laurent81784c32012-11-19 14:55:58 -08005482 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005483 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005484 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005485 // increase sleep time progressively when application underrun condition clears.
5486 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5487 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5488 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005489 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005490 sleepTimeShift--;
5491 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005492 mSleepTimeUs = 0;
5493 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005494 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005495
Eric Laurent81784c32012-11-19 14:55:58 -08005496}
5497
Andy Hung4b17e882023-07-07 13:47:37 -07005498void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005499{
5500 // If no tracks are ready, sleep once for the duration of an output
5501 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005502 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005503 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005504 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5505 // Using the Monopipe availableToWrite, we estimate the
5506 // sleep time to retry for more data (before we underrun).
5507 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5508 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5509 const size_t pipeFrames = monoPipe->maxFrames();
5510 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5511 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5512 const size_t framesDelay = std::min(
5513 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5514 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5515 pipeFrames, framesLeft, framesDelay);
5516 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5517 } else {
5518 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5519 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5520 mSleepTimeUs = kMinThreadSleepTimeUs;
5521 }
5522 // reduce sleep time in case of consecutive application underruns to avoid
5523 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5524 // duration we would end up writing less data than needed by the audio HAL if
5525 // the condition persists.
5526 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5527 sleepTimeShift++;
5528 }
Eric Laurent81784c32012-11-19 14:55:58 -08005529 }
5530 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005531 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005532 }
5533 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005534 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5535 // before effects processing or output.
5536 if (mMixerBufferValid) {
5537 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005538 if (mType == SPATIALIZER) {
5539 memset(mSinkBuffer, 0, mSinkBufferSize);
5540 }
Andy Hung98ef9782014-03-04 14:46:50 -08005541 } else {
5542 memset(mSinkBuffer, 0, mSinkBufferSize);
5543 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005544 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005545 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5546 "anticipated start");
5547 }
5548 // TODO add standby time extension fct of effect tail
5549}
5550
Andy Hungb17d24b2023-08-29 14:26:09 -07005551// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07005552PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07005553 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005554{
Andy Hungc0691382018-09-12 18:01:57 -07005555 // clean up deleted track ids in AudioMixer before allocating new tracks
5556 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5557 // for each trackId, destroy it in the AudioMixer
5558 if (mAudioMixer->exists(trackId)) {
5559 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005560 }
5561 });
Andy Hungc0691382018-09-12 18:01:57 -07005562 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005563
5564 mixer_state mixerStatus = MIXER_IDLE;
5565 // find out which tracks need to be processed
5566 size_t count = mActiveTracks.size();
5567 size_t mixedTracks = 0;
5568 size_t tracksWithEffect = 0;
5569 // counts only _active_ fast tracks
5570 size_t fastTracks = 0;
5571 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5572
5573 float masterVolume = mMasterVolume;
5574 bool masterMute = mMasterMute;
5575
5576 if (masterMute) {
5577 masterVolume = 0;
5578 }
5579 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005580 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005581 if (chain != 0) {
5582 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005583 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005584 masterVolume = (float)((v + (1 << 23)) >> 24);
5585 chain.clear();
5586 }
5587
5588 // prepare a new state to push
5589 FastMixerStateQueue *sq = NULL;
5590 FastMixerState *state = NULL;
5591 bool didModify = false;
5592 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005593 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005594 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005595 sq = mFastMixer->sq();
5596 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005597 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005598 }
5599
Andy Hung69aed5f2014-02-25 17:24:40 -08005600 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005601 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005602
Andy Hungbd3b2b02018-05-21 10:53:11 -07005603 // DeferredOperations handles statistics after setting mixerStatus.
5604 class DeferredOperations {
5605 public:
Andy Hungea840382020-05-05 21:50:17 -07005606 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5607 : mMixerStatus(mixerStatus)
5608 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005609
5610 // when leaving scope, tally frames properly.
5611 ~DeferredOperations() {
5612 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5613 // because that is when the underrun occurs.
5614 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005615 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005616 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005617 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005618 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005619 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005620 }
5621 }
Andy Hungea840382020-05-05 21:50:17 -07005622 // send the max underrun frames for this mixer period
5623 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005624 }
5625
5626 // tallyUnderrunFrames() is called to update the track counters
5627 // with the number of underrun frames for a particular mixer period.
5628 // We defer tallying until we know the final mixer status.
Andy Hung11e74242023-06-26 19:20:57 -07005629 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005630 mUnderrunFrames.emplace_back(track, underrunFrames);
5631 }
5632
5633 private:
5634 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005635 ThreadMetrics * const mThreadMetrics;
Andy Hung11e74242023-06-26 19:20:57 -07005636 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005637 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005638 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005639
jiabin245cdd92018-12-07 17:55:15 -08005640 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005641 for (size_t i=0 ; i<count ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07005642 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005643
5644 // this const just means the local variable doesn't change
Andy Hung11e74242023-06-26 19:20:57 -07005645 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005646
5647 // process fast tracks
5648 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005649 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5650 "%s(%d): FastTrack(%d) present without FastMixer",
5651 __func__, id(), track->id());
5652
jiabin245cdd92018-12-07 17:55:15 -08005653 if (track->getHapticPlaybackEnabled()) {
5654 noFastHapticTrack = false;
5655 }
Eric Laurent81784c32012-11-19 14:55:58 -08005656
5657 // It's theoretically possible (though unlikely) for a fast track to be created
5658 // and then removed within the same normal mix cycle. This is not a problem, as
5659 // the track never becomes active so it's fast mixer slot is never touched.
5660 // The converse, of removing an (active) track and then creating a new track
5661 // at the identical fast mixer slot within the same normal mix cycle,
5662 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung11e74242023-06-26 19:20:57 -07005663 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005664 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005665 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5666 FastTrack *fastTrack = &state->mFastTracks[j];
5667
5668 // Determine whether the track is currently in underrun condition,
5669 // and whether it had a recent underrun.
5670 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5671 FastTrackUnderruns underruns = ftDump->mUnderruns;
5672 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung11e74242023-06-26 19:20:57 -07005673 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005674 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung11e74242023-06-26 19:20:57 -07005675 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005676 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung11e74242023-06-26 19:20:57 -07005677 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005678 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung11e74242023-06-26 19:20:57 -07005679 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005680 // don't count underruns that occur while stopping or pausing
5681 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005682 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005683 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5684 recentUnderruns > 0) {
5685 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005686 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005687 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005688 // Immediately account for FastTrack underruns.
Andy Hung11e74242023-06-26 19:20:57 -07005689 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005690
5691 // This is similar to the state machine for normal tracks,
5692 // with a few modifications for fast tracks.
5693 bool isActive = true;
Andy Hung11e74242023-06-26 19:20:57 -07005694 switch (track->state()) {
5695 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005696 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005697 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung11e74242023-06-26 19:20:57 -07005698 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
5700 break;
Andy Hung11e74242023-06-26 19:20:57 -07005701 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005702 // ramp down is not yet implemented
5703 track->setPaused();
5704 break;
Andy Hung11e74242023-06-26 19:20:57 -07005705 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005706 // ramp up is not yet implemented
Andy Hung11e74242023-06-26 19:20:57 -07005707 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005708 break;
Andy Hung11e74242023-06-26 19:20:57 -07005709 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005710 if (recentFull > 0 || recentPartial > 0) {
5711 // track has provided at least some frames recently: reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07005712 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005713 }
5714 if (recentUnderruns == 0) {
5715 // no recent underruns: stay active
5716 break;
5717 }
5718 // there has recently been an underrun of some kind
5719 if (track->sharedBuffer() == 0) {
5720 // were any of the recent underruns "empty" (no frames available)?
5721 if (recentEmpty == 0) {
5722 // no, then ignore the partial underruns as they are allowed indefinitely
5723 break;
5724 }
5725 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung11e74242023-06-26 19:20:57 -07005726 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005727 break;
5728 }
5729 // indicate to client process that the track was disabled because of underrun;
5730 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005731 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005732 // remove from active list, but state remains ACTIVE [confusing but true]
5733 isActive = false;
5734 break;
5735 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005736 FALLTHROUGH_INTENDED;
Andy Hung11e74242023-06-26 19:20:57 -07005737 case IAfTrackBase::STOPPING_2:
5738 case IAfTrackBase::PAUSED:
5739 case IAfTrackBase::STOPPED:
5740 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005741 // Check for presentation complete if track is inactive
5742 // We have consumed all the buffers of this track.
5743 // This would be incomplete if we auto-paused on underrun
5744 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005745 uint32_t latency = 0;
5746 status_t result = mOutput->stream->getLatency(&latency);
5747 ALOGE_IF(result != OK,
5748 "Error when retrieving output stream latency: %d", result);
5749 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005750 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005751 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5752 // track stays in active list until presentation is complete
5753 break;
5754 }
5755 }
5756 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07005757 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005758 }
5759 if (track->isStopped()) {
5760 // Can't reset directly, as fast mixer is still polling this track
5761 // track->reset();
5762 // So instead mark this track as needing to be reset after push with ack
5763 resetMask |= 1 << i;
5764 }
5765 isActive = false;
5766 break;
Andy Hung11e74242023-06-26 19:20:57 -07005767 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005768 default:
Andy Hung11e74242023-06-26 19:20:57 -07005769 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005770 }
5771
5772 if (isActive) {
5773 // was it previously inactive?
5774 if (!(state->mTrackMask & (1 << j))) {
Andy Hung11e74242023-06-26 19:20:57 -07005775 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5776 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005777 fastTrack->mBufferProvider = eabp;
5778 fastTrack->mVolumeProvider = vp;
Andy Hung11e74242023-06-26 19:20:57 -07005779 fastTrack->mChannelMask = track->channelMask();
5780 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005781 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005782 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005783 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005784 fastTrack->mGeneration++;
5785 state->mTrackMask |= 1 << j;
5786 didModify = true;
5787 // no acknowledgement required for newly active tracks
5788 }
Andy Hung11e74242023-06-26 19:20:57 -07005789 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005790 float volume;
5791 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5792 volume = 0.f;
5793 } else {
5794 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5795 }
5796
5797 handleVoipVolume_l(&volume);
5798
Eric Laurent81784c32012-11-19 14:55:58 -08005799 // cache the combined master volume and stream type volume for fast mixer; this
5800 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005801 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005802 proxy->framesReleased()).first;
5803 volume *= vh;
Andy Hung11e74242023-06-26 19:20:57 -07005804 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005805 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005806 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5807 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5808
Andy Hung7535ed92023-07-17 17:05:00 -07005809 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005810 /*muteState=*/{masterVolume == 0.f,
5811 mStreamTypes[track->streamType()].volume == 0.f,
5812 mStreamTypes[track->streamType()].mute,
5813 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005814 vlf == 0.f && vrf == 0.f,
5815 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005816
5817 vlf *= volume;
5818 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005819
jiabin220eea12024-05-17 17:55:20 +00005820 if (track->getInternalMute()) {
5821 vlf = 0.f;
5822 vrf = 0.f;
5823 }
5824
jiabin76d94692022-12-15 21:51:21 +00005825 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005826 ++fastTracks;
5827 } else {
5828 // was it previously active?
5829 if (state->mTrackMask & (1 << j)) {
5830 fastTrack->mBufferProvider = NULL;
5831 fastTrack->mGeneration++;
5832 state->mTrackMask &= ~(1 << j);
5833 didModify = true;
5834 // If any fast tracks were removed, we must wait for acknowledgement
5835 // because we're about to decrement the last sp<> on those tracks.
5836 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5837 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005838 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5839 // AudioTrack may start (which may not be with a start() but with a write()
5840 // after underrun) and immediately paused or released. In that case the
5841 // FastTrack state hasn't had time to update.
5842 // TODO Remove the ALOGW when this theory is confirmed.
5843 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005844 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung11e74242023-06-26 19:20:57 -07005845 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005846 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005847 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005848 }
5849 tracksToRemove->add(track);
5850 // Avoids a misleading display in dumpsys
Andy Hung11e74242023-06-26 19:20:57 -07005851 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005852 }
jiabin245cdd92018-12-07 17:55:15 -08005853 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5854 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5855 didModify = true;
5856 }
Eric Laurent81784c32012-11-19 14:55:58 -08005857 continue;
5858 }
5859
5860 { // local variable scope to avoid goto warning
5861
5862 audio_track_cblk_t* cblk = track->cblk();
5863
5864 // The first time a track is added we wait
5865 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005866 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005867
5868 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005869 // use the trackId as the AudioMixer name.
5870 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005871 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005872 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005873 track->channelMask(),
5874 track->format(),
5875 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005876 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005877 ALOGW("%s(): AudioMixer cannot create track(%d)"
5878 " mask %#x, format %#x, sessionId %d",
5879 __func__, trackId,
Andy Hung11e74242023-06-26 19:20:57 -07005880 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005881 tracksToRemove->add(track);
5882 track->invalidate(); // consider it dead.
5883 continue;
5884 }
5885 }
5886
Eric Laurent81784c32012-11-19 14:55:58 -08005887 // make sure that we have enough frames to mix one full buffer.
5888 // enforce this condition only once to enable draining the buffer in case the client
5889 // app does not call stop() and relies on underrun to stop:
5890 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5891 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005892 size_t desiredFrames;
Andy Hung11e74242023-06-26 19:20:57 -07005893 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5894 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005895
5896 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005897 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005898 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5899 // add frames already consumed but not yet released by the resampler
5900 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005901 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005902
Eric Laurent81784c32012-11-19 14:55:58 -08005903 uint32_t minFrames = 1;
5904 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5905 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005906 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005907 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005908
5909 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005910 if (ATRACE_ENABLED()) {
5911 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005912 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005913 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005914 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005915 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005916 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005917 !track->isPaused() && !track->isTerminated())
5918 {
Andy Hungc0691382018-09-12 18:01:57 -07005919 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005920
5921 mixedTracks++;
5922
Shunkai Yaof4847652024-01-12 00:25:20 +00005923 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005924 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005925 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005926 if (track->mainBuffer() != mSinkBuffer &&
5927 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005928 if (mEffectBufferEnabled) {
5929 mEffectBufferValid = true; // Later can set directly.
5930 }
Eric Laurent81784c32012-11-19 14:55:58 -08005931 chain = getEffectChain_l(track->sessionId());
5932 // Delegate volume control to effect in track effect chain if needed
5933 if (chain != 0) {
5934 tracksWithEffect++;
5935 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005936 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005937 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005938 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005939 }
5940 }
5941
5942
5943 int param = AudioMixer::VOLUME;
Andy Hung11e74242023-06-26 19:20:57 -07005944 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005945 // no ramp for the first volume setting
Andy Hung11e74242023-06-26 19:20:57 -07005946 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5947 if (track->state() == IAfTrackBase::RESUMING) {
5948 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005949 // If a new track is paused immediately after start, do not ramp on resume.
5950 if (cblk->mServer != 0) {
5951 param = AudioMixer::RAMP_VOLUME;
5952 }
Eric Laurent81784c32012-11-19 14:55:58 -08005953 }
Andy Hungc0691382018-09-12 18:01:57 -07005954 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005955 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005956 // FIXME should not make a decision based on mServer
5957 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005958 // If the track is stopped before the first frame was mixed,
5959 // do not apply ramp
5960 param = AudioMixer::RAMP_VOLUME;
5961 }
5962
5963 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005964 uint32_t vl, vr; // in U8.24 integer format
5965 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005966 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005967 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005968 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung11e74242023-06-26 19:20:57 -07005969 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005970 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung11e74242023-06-26 19:20:57 -07005971 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005972
Eric Laurenteab90452019-06-24 15:17:46 -07005973 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5974 v = 0;
5975 }
5976
5977 handleVoipVolume_l(&v);
5978
5979 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005980 vl = vr = 0;
5981 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005982 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005983 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005984 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005985 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5986 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005987 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005988 if (vlf > GAIN_FLOAT_UNITY) {
5989 ALOGV("Track left volume out of range: %.3g", vlf);
5990 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005991 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005992 if (vrf > GAIN_FLOAT_UNITY) {
5993 ALOGV("Track right volume out of range: %.3g", vrf);
5994 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005995 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005996
Andy Hung7535ed92023-07-17 17:05:00 -07005997 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005998 /*muteState=*/{masterVolume == 0.f,
5999 mStreamTypes[track->streamType()].volume == 0.f,
6000 mStreamTypes[track->streamType()].mute,
6001 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006002 vlf == 0.f && vrf == 0.f,
6003 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02006004
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006005 // now apply the master volume and stream type volume and shaper volume
6006 vlf *= v * vh;
6007 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006008 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006009 // then derive vl and vr as U8.24 versions for the effect chain
6010 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6011 vl = (uint32_t) (scaleto8_24 * vlf);
6012 vr = (uint32_t) (scaleto8_24 * vrf);
6013 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006014 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006015 // send level comes from shared memory and so may be corrupt
6016 if (sendLevel > MAX_GAIN_INT) {
6017 ALOGV("Track send level out of range: %04X", sendLevel);
6018 sendLevel = MAX_GAIN_INT;
6019 }
Andy Hung6be49402014-05-30 10:42:03 -07006020 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6021 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006022 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006023
jiabin220eea12024-05-17 17:55:20 +00006024 if (track->getInternalMute()) {
6025 vrf = 0.f;
6026 vlf = 0.f;
6027 }
6028
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006029 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006030
Eric Laurent81784c32012-11-19 14:55:58 -08006031 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006032 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006033 // Do not ramp volume if volume is controlled by effect
6034 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006035 // Update remaining floating point volume levels
6036 vlf = (float)vl / (1 << 24);
6037 vrf = (float)vr / (1 << 24);
Andy Hung11e74242023-06-26 19:20:57 -07006038 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006039 } else {
6040 // force no volume ramp when volume controller was just disabled or removed
6041 // from effect chain to avoid volume spike
Andy Hung11e74242023-06-26 19:20:57 -07006042 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006043 param = AudioMixer::VOLUME;
6044 }
Andy Hung11e74242023-06-26 19:20:57 -07006045 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006046 }
6047
Eric Laurent81784c32012-11-19 14:55:58 -08006048 // XXX: these things DON'T need to be done each time
Andy Hung11e74242023-06-26 19:20:57 -07006049 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006050 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006051
Andy Hungc0691382018-09-12 18:01:57 -07006052 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6053 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6054 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006055 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006056 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006057 AudioMixer::TRACK,
6058 AudioMixer::FORMAT, (void *)track->format());
6059 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006060 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006061 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006062 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006063
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006064 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006065 mAudioMixer->setParameter(
6066 trackId,
6067 AudioMixer::TRACK,
6068 AudioMixer::MIXER_CHANNEL_MASK,
6069 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6070 } else {
6071 mAudioMixer->setParameter(
6072 trackId,
6073 AudioMixer::TRACK,
6074 AudioMixer::MIXER_CHANNEL_MASK,
6075 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6076 }
6077
Glenn Kastene3aa6592012-12-04 12:22:46 -08006078 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006079 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006080 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006081 if (reqSampleRate == 0) {
6082 reqSampleRate = mSampleRate;
6083 } else if (reqSampleRate > maxSampleRate) {
6084 reqSampleRate = maxSampleRate;
6085 }
Eric Laurent81784c32012-11-19 14:55:58 -08006086 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006087 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006088 AudioMixer::RESAMPLE,
6089 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006090 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006091
Andy Hung8edb8dc2015-03-26 19:13:55 -07006092 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006093 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006094 AudioMixer::TIMESTRETCH,
6095 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006096 // cast away constness for this generic API.
6097 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006098
Andy Hung69aed5f2014-02-25 17:24:40 -08006099 /*
6100 * Select the appropriate output buffer for the track.
6101 *
Andy Hung98ef9782014-03-04 14:46:50 -08006102 * Tracks with effects go into their own effects chain buffer
6103 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006104 *
6105 * Other tracks can use mMixerBuffer for higher precision
6106 * channel accumulation. If this buffer is enabled
6107 * (mMixerBufferEnabled true), then selected tracks will accumulate
6108 * into it.
6109 *
6110 */
6111 if (mMixerBufferEnabled
6112 && (track->mainBuffer() == mSinkBuffer
6113 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006114 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006115 mAudioMixer->setParameter(
6116 trackId,
6117 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006118 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006119 mAudioMixer->setParameter(
6120 trackId,
6121 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006122 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006123 } else {
6124 mAudioMixer->setParameter(
6125 trackId,
6126 AudioMixer::TRACK,
6127 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6128 mAudioMixer->setParameter(
6129 trackId,
6130 AudioMixer::TRACK,
6131 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6132 // TODO: override track->mainBuffer()?
6133 mMixerBufferValid = true;
6134 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006135 } else {
6136 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006137 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006138 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006139 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006140 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006141 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006142 AudioMixer::TRACK,
6143 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6144 }
Eric Laurent81784c32012-11-19 14:55:58 -08006145 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006146 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006147 AudioMixer::TRACK,
6148 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006149 mAudioMixer->setParameter(
6150 trackId,
6151 AudioMixer::TRACK,
6152 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006153 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006154 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006155 trackId,
6156 AudioMixer::TRACK,
6157 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung11e74242023-06-26 19:20:57 -07006158 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006159 mAudioMixer->setParameter(
6160 trackId,
6161 AudioMixer::TRACK,
Andy Hung11e74242023-06-26 19:20:57 -07006162 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006163
6164 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006165 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006166
6167 // If one track is ready, set the mixer ready if:
6168 // - the mixer was not ready during previous round OR
6169 // - no other track is not ready
6170 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6171 mixerStatus != MIXER_TRACKS_ENABLED) {
6172 mixerStatus = MIXER_TRACKS_READY;
6173 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006174
6175 // Enable the next few lines to instrument a test for underrun log handling.
6176 // TODO: Remove when we have a better way of testing the underrun log.
6177#if 0
6178 static int i;
6179 if ((++i & 0xf) == 0) {
6180 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6181 }
6182#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006183 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006184 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006185 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006186 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6187 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006188 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006189 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006190 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006191
Eric Laurent81784c32012-11-19 14:55:58 -08006192 // clear effect chain input buffer if an active track underruns to avoid sending
6193 // previous audio buffer again to effects
6194 chain = getEffectChain_l(track->sessionId());
6195 if (chain != 0) {
6196 chain->clearInputBuffer();
6197 }
6198
Andy Hungc0691382018-09-12 18:01:57 -07006199 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006200 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6201 track->isStopped() || track->isPaused()) {
6202 // We have consumed all the buffers of this track.
6203 // Remove it from the list of active tracks.
6204 // TODO: use actual buffer filling status instead of latency when available from
6205 // audio HAL
6206 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006207 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006208 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6209 if (track->isStopped()) {
6210 track->reset();
6211 }
6212 tracksToRemove->add(track);
6213 }
6214 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006215 // No buffers for this track. Give it a few chances to
6216 // fill a buffer, then remove it from active list.
Andy Hung11e74242023-06-26 19:20:57 -07006217 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006218 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6219 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006220 tracksToRemove->add(track);
6221 // indicate to client process that the track was disabled because of underrun;
6222 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006223 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006224 // If one track is not ready, mark the mixer also not ready if:
6225 // - the mixer was ready during previous round OR
6226 // - no other track is ready
6227 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6228 mixerStatus != MIXER_TRACKS_READY) {
6229 mixerStatus = MIXER_TRACKS_ENABLED;
6230 }
6231 }
Andy Hungc0691382018-09-12 18:01:57 -07006232 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006233 }
6234
6235 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006236
6237 }
6238
jiabin245cdd92018-12-07 17:55:15 -08006239 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6240 // When there is no fast track playing haptic and FastMixer exists,
6241 // enabling the first FastTrack, which provides mixed data from normal
6242 // tracks, to play haptic data.
6243 FastTrack *fastTrack = &state->mFastTracks[0];
6244 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6245 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6246 didModify = true;
6247 }
6248 }
6249
Eric Laurent81784c32012-11-19 14:55:58 -08006250 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006251 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006252 if (didModify) {
6253 state->mFastTracksGen++;
6254 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6255 if (kUseFastMixer == FastMixer_Dynamic &&
6256 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6257 state->mCommand = FastMixerState::COLD_IDLE;
6258 state->mColdFutexAddr = &mFastMixerFutex;
6259 state->mColdGen++;
6260 mFastMixerFutex = 0;
6261 if (kUseFastMixer == FastMixer_Dynamic) {
6262 mNormalSink = mOutputSink;
6263 }
6264 // If we go into cold idle, need to wait for acknowledgement
6265 // so that fast mixer stops doing I/O.
6266 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6267 pauseAudioWatchdog = true;
6268 }
Eric Laurent81784c32012-11-19 14:55:58 -08006269 }
6270 if (sq != NULL) {
6271 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006272 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6273 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6274 // when bringing the output sink into standby.)
6275 //
6276 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6277 //
6278 // This occurs with BT suspend when we idle the FastMixer with
6279 // active tracks, which may be added or removed.
6280 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006281 }
6282#ifdef AUDIO_WATCHDOG
6283 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6284 mAudioWatchdog->pause();
6285 }
6286#endif
6287
6288 // Now perform the deferred reset on fast tracks that have stopped
6289 while (resetMask != 0) {
6290 size_t i = __builtin_ctz(resetMask);
6291 ALOG_ASSERT(i < count);
6292 resetMask &= ~(1 << i);
Andy Hung11e74242023-06-26 19:20:57 -07006293 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006294 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6295 track->reset();
6296 }
6297
Andy Hung80d03d22018-04-10 10:32:11 -07006298 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6299 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6300 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6301 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6302 // See also the implementation of destroyTrack_l().
6303 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006304 const int trackId = track->id();
6305 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6306 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006307 }
6308 }
6309
Eric Laurent81784c32012-11-19 14:55:58 -08006310 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006311 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006312
Eric Laurentb3f315a2021-07-13 15:09:05 +02006313 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6314 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006315 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006316 }
6317
6318 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006319 // as long as there are effects we should clear the effects buffer, to avoid
6320 // passing a non-clean buffer to the effect chain
6321 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006322 if (mType == SPATIALIZER) {
6323 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6324 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006325 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006326 // sink or mix buffer must be cleared if all tracks are connected to an
6327 // effect chain as in this case the mixer will not write to the sink or mix buffer
6328 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006329 // always clear sink buffer for spatializer output as the output of the spatializer
6330 // effect will be accumulated into it
6331 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6332 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006333 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006334 if (mMixerBufferValid) {
6335 memset(mMixerBuffer, 0, mMixerBufferSize);
6336 // TODO: In testing, mSinkBuffer below need not be cleared because
6337 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6338 // after mixing.
6339 //
6340 // To enforce this guarantee:
6341 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6342 // (mixedTracks == 0 && fastTracks > 0))
6343 // must imply MIXER_TRACKS_READY.
6344 // Later, we may clear buffers regardless, and skip much of this logic.
6345 }
Andy Hung98ef9782014-03-04 14:46:50 -08006346 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006347 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006348 }
6349
6350 // if any fast tracks, then status is ready
6351 mMixerStatusIgnoringFastTracks = mixerStatus;
6352 if (fastTracks > 0) {
6353 mixerStatus = MIXER_TRACKS_READY;
6354 }
6355 return mixerStatus;
6356}
6357
Andy Hungb17d24b2023-08-29 14:26:09 -07006358// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006359uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006360{
6361 uint32_t trackCount = 0;
6362 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006363 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006364 trackCount++;
6365 }
6366 }
6367 return trackCount;
6368}
6369
Andy Hung4b17e882023-07-07 13:47:37 -07006370bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006371{
Brian Lindahl65e90012022-07-27 18:01:07 +02006372 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6373 // could falsely detect that the frame position has stalled due to underrun because we haven't
6374 // given the Audio HAL enough time to update.
6375 const nsecs_t nowNs = systemTime();
6376 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6377 return mLatchedValue;
6378 }
6379 mPreviousNs = nowNs;
6380 mLatchedValue = false;
6381 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006382 uint64_t position = 0;
6383 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006384 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006385 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006386 if (position != mPreviousPosition) {
6387 mPreviousPosition = position;
6388 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006389 }
6390 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006391 return mLatchedValue;
6392}
6393
Andy Hung4b17e882023-07-07 13:47:37 -07006394void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006395{
6396 mLatchedValue = true;
6397 mPreviousPosition = 0;
6398 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006399}
6400
Andy Hungb17d24b2023-08-29 14:26:09 -07006401// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006402bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006403 audio_channel_mask_t channelMask, audio_format_t format,
6404 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006405{
Andy Hung1bc088a2018-02-09 15:57:31 -08006406 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6407 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006408 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006409 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006410 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006411 ALOGW("%s: invalid format: %#x", __func__, format);
6412 return false;
6413 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006414 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006415 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6416 return false;
6417 }
6418 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006419}
6420
Andy Hungb17d24b2023-08-29 14:26:09 -07006421// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07006422bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006423 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006424{
Eric Laurent81784c32012-11-19 14:55:58 -08006425 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006426 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006427
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006428 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006429
Eric Laurent10351942014-05-08 18:49:52 -07006430 AudioParameter param = AudioParameter(keyValuePair);
6431 int value;
6432 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6433 reconfig = true;
6434 }
6435 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006436 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006437 status = BAD_VALUE;
6438 } else {
6439 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006440 reconfig = true;
6441 }
Eric Laurent10351942014-05-08 18:49:52 -07006442 }
6443 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungd21a2ab2023-07-20 21:44:14 -07006444 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006445 status = BAD_VALUE;
6446 } else {
6447 // no need to save value, since it's constant
6448 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006449 }
Eric Laurent10351942014-05-08 18:49:52 -07006450 }
6451 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6452 // do not accept frame count changes if tracks are open as the track buffer
6453 // size depends on frame count and correct behavior would not be guaranteed
6454 // if frame count is changed after track creation
6455 if (!mTracks.isEmpty()) {
6456 status = INVALID_OPERATION;
6457 } else {
6458 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006459 }
Eric Laurent10351942014-05-08 18:49:52 -07006460 }
6461 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006462 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006463 }
Eric Laurent81784c32012-11-19 14:55:58 -08006464
Eric Laurent10351942014-05-08 18:49:52 -07006465 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006466 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006467 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006468 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6469 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006470 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006471 mThreadMetrics.logEndInterval();
6472 mThreadSnapshot.onEnd();
6473 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006474 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006475 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006476 }
Eric Laurent10351942014-05-08 18:49:52 -07006477 if (status == NO_ERROR && reconfig) {
6478 readOutputParameters_l();
6479 delete mAudioMixer;
6480 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006481 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006482 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006483 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006484 trackId,
Andy Hung11e74242023-06-26 19:20:57 -07006485 track->channelMask(),
6486 track->format(),
6487 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006488 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006489 "%s(): AudioMixer cannot create track(%d)"
6490 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006491 __func__,
Andy Hung11e74242023-06-26 19:20:57 -07006492 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006493 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006494 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006495 }
Eric Laurent81784c32012-11-19 14:55:58 -08006496 }
6497
Dean Wheatley68918102021-03-19 22:09:19 +11006498 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006499}
6500
6501
Andy Hung4b17e882023-07-07 13:47:37 -07006502void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006503{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006504 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung160664b2023-09-15 18:19:28 -07006505 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006506 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006507 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006508 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6509 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6510 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006511 if (hasFastMixer()) {
6512 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6513
6514 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6515 // while we are dumping it. It may be inconsistent, but it won't mutate!
6516 // This is a large object so we place it on the heap.
6517 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006518 const std::unique_ptr<FastMixerDumpState> copy =
6519 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006520 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006521
6522#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006523 // Similar for state queue
6524 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6525 observerCopy.dump(fd);
6526 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6527 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006528#endif
6529
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006530#ifdef AUDIO_WATCHDOG
6531 if (mAudioWatchdog != 0) {
6532 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6533 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6534 wdCopy.dump(fd);
6535 }
6536#endif
6537
6538 } else {
6539 dprintf(fd, " No FastMixer\n");
6540 }
Eric Laurent90cea102023-05-15 15:08:27 +02006541
6542 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6543 mBluetoothLatencyModesEnabled ? "" : "not ");
6544 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6545 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6546 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006547}
6548
Andy Hung4b17e882023-07-07 13:47:37 -07006549uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006550{
6551 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6552}
6553
Andy Hung4b17e882023-07-07 13:47:37 -07006554uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006555{
6556 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6557}
6558
Andy Hung4b17e882023-07-07 13:47:37 -07006559void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006560{
6561 PlaybackThread::cacheParameters_l();
6562
6563 // FIXME: Relaxed timing because of a certain device that can't meet latency
6564 // Should be reduced to 2x after the vendor fixes the driver issue
6565 // increase threshold again due to low power audio mode. The way this warning
6566 // threshold is calculated and its usefulness should be reconsidered anyway.
6567 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6568}
6569
Andy Hung4b17e882023-07-07 13:47:37 -07006570void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung7535ed92023-07-17 17:05:00 -07006571 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006572}
6573
Andy Hung4b17e882023-07-07 13:47:37 -07006574void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006575 // Only handle latency mode if:
6576 // - mBluetoothLatencyModesEnabled is true
6577 // - the HAL supports latency modes
6578 // - the selected device is Bluetooth LE or A2DP
6579 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6580 return;
6581 }
6582 if (mOutDeviceTypeAddrs.size() != 1
6583 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6584 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6585 return;
6586 }
6587
6588 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6589 if (mSupportedLatencyModes.size() == 1) {
6590 // If the HAL only support one latency mode currently, confirm the choice
6591 latencyMode = mSupportedLatencyModes[0];
6592 } else if (mSupportedLatencyModes.size() > 1) {
6593 // Request low latency if:
6594 // - At least one active track is either:
6595 // - a fast track with gaming usage or
6596 // - a track with acessibility usage
6597 for (const auto& track : mActiveTracks) {
6598 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6599 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6600 latencyMode = AUDIO_LATENCY_MODE_LOW;
6601 break;
6602 }
6603 }
6604 }
6605
6606 if (latencyMode != mSetLatencyMode) {
6607 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6608 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6609 __func__, mId, toString(latencyMode).c_str(), status);
6610 if (status == NO_ERROR) {
6611 mSetLatencyMode = latencyMode;
6612 }
6613 }
6614}
6615
Andy Hung4b17e882023-07-07 13:47:37 -07006616void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006617
6618 if (mOutput == nullptr || mOutput->stream == nullptr) {
6619 return;
6620 }
6621 std::vector<audio_latency_mode_t> latencyModes;
6622 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6623 if (status != NO_ERROR) {
6624 latencyModes.clear();
6625 }
6626 if (latencyModes != mSupportedLatencyModes) {
6627 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6628 __func__, mId, status, toString(latencyModes).c_str());
6629 mSupportedLatencyModes.swap(latencyModes);
6630 sendHalLatencyModesChangedEvent_l();
6631 }
6632}
6633
Andy Hung4b17e882023-07-07 13:47:37 -07006634status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006635 std::vector<audio_latency_mode_t>* modes) {
6636 if (modes == nullptr) {
6637 return BAD_VALUE;
6638 }
Andy Hungf8635b62023-08-31 16:13:39 -07006639 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006640 *modes = mSupportedLatencyModes;
6641 return NO_ERROR;
6642}
6643
Andy Hung4b17e882023-07-07 13:47:37 -07006644void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006645 std::vector<audio_latency_mode_t> modes) {
Andy Hungf8635b62023-08-31 16:13:39 -07006646 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006647 if (modes != mSupportedLatencyModes) {
6648 ALOGD("%s: thread(%d) supported latency modes: %s",
6649 __func__, mId, toString(modes).c_str());
6650 mSupportedLatencyModes.swap(modes);
6651 sendHalLatencyModesChangedEvent_l();
6652 }
6653}
6654
Andy Hung4b17e882023-07-07 13:47:37 -07006655status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006656 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6657 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6658 return INVALID_OPERATION;
6659 }
6660 mBluetoothLatencyModesEnabled.store(enabled);
6661 return NO_ERROR;
6662}
6663
Eric Laurent81784c32012-11-19 14:55:58 -08006664// ----------------------------------------------------------------------------
6665
Andy Hung4b17e882023-07-07 13:47:37 -07006666/* static */
6667sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung7535ed92023-07-17 17:05:00 -07006668 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07006669 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6670 const audio_offload_info_t& offloadInfo) {
6671 return sp<DirectOutputThread>::make(
Andy Hung7535ed92023-07-17 17:05:00 -07006672 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07006673}
6674
Andy Hung7535ed92023-07-17 17:05:00 -07006675DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006676 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6677 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07006678 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006679 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006680{
Andy Hung7535ed92023-07-17 17:05:00 -07006681 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006682}
6683
Andy Hung4b17e882023-07-07 13:47:37 -07006684DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006685{
6686}
6687
Andy Hung4b17e882023-07-07 13:47:37 -07006688void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006689{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006690 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006691 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6692 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6693}
6694
Andy Hung4b17e882023-07-07 13:47:37 -07006695void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006696{
Andy Hungf8635b62023-08-31 16:13:39 -07006697 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006698 if (mMasterBalance != balance) {
6699 mMasterBalance.store(balance);
6700 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6701 broadcast_l();
6702 }
6703}
6704
Andy Hung4b17e882023-07-07 13:47:37 -07006705void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006706{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006707 float left, right;
6708
Andy Hung333ab962019-05-28 20:23:35 -07006709 // Ensure volumeshaper state always advances even when muted.
Andy Hung11e74242023-06-26 19:20:57 -07006710 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006711
Andy Hung398ffa22022-12-13 19:19:53 -08006712 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6713 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6714
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006715 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6716 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006717
6718 const int64_t volumeShaperFrames =
6719 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6720 const auto [shaperVolume, shaperActive] =
6721 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006722 mVolumeShaperActive = shaperActive;
6723
Vlad Popae2f5aef2022-07-25 16:00:20 +02006724 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6725 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6726 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6727
6728 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6729
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006730 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006731 left = right = 0;
6732 } else {
6733 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006734 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006735
Glenn Kastenc56f3422014-03-21 17:53:17 -07006736 if (left > GAIN_FLOAT_UNITY) {
6737 left = GAIN_FLOAT_UNITY;
6738 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006739 if (right > GAIN_FLOAT_UNITY) {
6740 right = GAIN_FLOAT_UNITY;
6741 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006742 left *= v;
6743 right *= v;
Andy Hung7535ed92023-07-17 17:05:00 -07006744 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006745 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6746 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6747 right *= mMasterBalanceRight;
6748 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006749 }
6750
Andy Hung7535ed92023-07-17 17:05:00 -07006751 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006752 /*muteState=*/{mMasterMute,
6753 mStreamTypes[track->streamType()].volume == 0.f,
6754 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006755 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006756 clientVolumeMute,
6757 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006758
Eric Laurentbfb1b832013-01-07 09:53:42 -08006759 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006760 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006761 if (left != mLeftVolFloat || right != mRightVolFloat) {
6762 mLeftVolFloat = left;
6763 mRightVolFloat = right;
6764
Eric Laurentbfb1b832013-01-07 09:53:42 -08006765 // Delegate volume control to effect in track effect chain if needed
6766 // only one effect chain can be present on DirectOutputThread, so if
6767 // there is one, the track is connected to it
6768 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006769 // if effect chain exists, volume is handled by it.
6770 // Convert volumes from float to 8.24
6771 uint32_t vl = (uint32_t)(left * (1 << 24));
6772 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006773 // Direct/Offload effect chains set output volume in setVolume().
6774 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006775 } else {
6776 // otherwise we directly set the volume.
6777 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006778 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006779 }
6780 }
6781}
6782
Andy Hung4b17e882023-07-07 13:47:37 -07006783void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006784{
Andy Hung11e74242023-06-26 19:20:57 -07006785 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6786 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006787
Eric Laurent0f0631e2015-07-06 18:01:25 -07006788 if (previousTrack != 0 && latestTrack != 0) {
6789 if (mType == DIRECT) {
6790 if (previousTrack.get() != latestTrack.get()) {
6791 mFlushPending = true;
6792 }
6793 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006794 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6795 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006796 mFlushPending = true;
6797 }
6798 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006799 } else if (previousTrack == 0) {
6800 // there could be an old track added back during track transition for direct
6801 // output, so always issues flush to flush data of the previous track if it
6802 // was already destroyed with HAL paused, then flush can resume the playback
6803 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006804 }
6805 PlaybackThread::onAddNewTrack_l();
6806}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006807
Andy Hung4b17e882023-07-07 13:47:37 -07006808PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07006809 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006810)
6811{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006812 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006813 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006814 bool doHwPause = false;
6815 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006816
6817 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07006818 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006819 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006820 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006821 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006822 continue;
6823 }
6824
Andy Hung11e74242023-06-26 19:20:57 -07006825 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006826#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006827 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006828#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006829 // Only consider last track started for volume and mixer state control.
6830 // In theory an older track could underrun and restart after the new one starts
6831 // but as we only care about the transition phase between two tracks on a
6832 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07006833 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006834 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006835
Kuowei Li23666472021-01-20 10:23:25 +08006836 if (track->isPausePending()) {
6837 track->pauseAck();
6838 // It is possible a track might have been flushed or stopped.
6839 // Other operations such as flush pending might occur on the next prepare.
6840 if (track->isPausing()) {
6841 track->setPaused();
6842 }
6843 // Always perform pause, as an immediate flush will change
6844 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006845 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006846 doHwPause = true;
6847 mHwPaused = true;
6848 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006849 } else if (track->isFlushPending()) {
6850 track->flushAck();
6851 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006852 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006853 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006854 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006855 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006856 if (last) {
6857 mLeftVolFloat = mRightVolFloat = -1.0;
6858 if (mHwPaused) {
6859 doHwResume = true;
6860 mHwPaused = false;
6861 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006862 }
6863 }
6864
Eric Laurent81784c32012-11-19 14:55:58 -08006865 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006866 // for all its buffers to be filled before processing it.
6867 // Allow draining the buffer in case the client
6868 // app does not call stop() and relies on underrun to stop:
Andy Hung11e74242023-06-26 19:20:57 -07006869 // hence the test on (track->retryCount() > 1).
6870 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006871 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6872 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006873 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006874
6875 // target retry count that we will use is based on the time we wait for retries.
6876 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6877 // the retry threshold is when we accept any size for PCM data. This is slightly
6878 // smaller than the retry count so we can push small bits of data without a glitch.
6879 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006880 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006881 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung11e74242023-06-26 19:20:57 -07006882 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006883 minFrames = mNormalFrameCount;
6884 } else {
6885 minFrames = 1;
6886 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006887
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006888 const size_t framesReady = track->framesReady();
6889 const int trackId = track->id();
6890 if (ATRACE_ENABLED()) {
6891 std::string traceName("nRdy");
6892 traceName += std::to_string(trackId);
6893 ATRACE_INT(traceName.c_str(), framesReady);
6894 }
6895 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006896 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006897 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006898 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006899
Andy Hung11e74242023-06-26 19:20:57 -07006900 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6901 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006902 if (last) {
6903 // make sure processVolume_l() will apply new volume even if 0
6904 mLeftVolFloat = mRightVolFloat = -1.0;
6905 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006906 if (!mHwSupportsPause) {
6907 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006908 }
6909 }
6910
6911 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006912 processVolume_l(track, last);
6913 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07006914 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006915 if (previousTrack != 0) {
6916 if (track != previousTrack.get()) {
6917 // Flush any data still being written from last track
6918 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006919 // Invalidate previous track to force a seek when resuming.
6920 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006921 }
6922 }
6923 mPreviousTrack = track;
6924
Eric Laurentd595b7c2013-04-03 17:27:56 -07006925 // reset retry count
Andy Hung11e74242023-06-26 19:20:57 -07006926 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006927 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006928 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006929 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006930 doHwResume = true;
6931 mHwPaused = false;
6932 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006933 }
Eric Laurent81784c32012-11-19 14:55:58 -08006934 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006935 // clear effect chain input buffer if the last active track started underruns
6936 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006937 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006938 mEffectChains[0]->clearInputBuffer();
6939 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006940 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07006941 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006942 if (last && mHwPaused) {
6943 doHwResume = true;
6944 mHwPaused = false;
6945 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006946 }
6947 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6948 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006949 // We have consumed all the buffers of this track.
6950 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006951 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006952 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006953 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006954 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006955 if (presComplete) {
6956 mOutput->presentationComplete();
6957 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006958 if (track->isStopping_2()) {
Andy Hung11e74242023-06-26 19:20:57 -07006959 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006960 }
Eric Laurent81784c32012-11-19 14:55:58 -08006961 if (track->isStopped()) {
6962 track->reset();
6963 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006964 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006965 }
6966 } else {
6967 // No buffers for this track. Give it a few chances to
6968 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006969 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006970 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006971 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07006972 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006973 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07006974 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006975 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00006976 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
6977 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08006978 tracksToRemove->add(track);
6979 // indicate to client process that the track was disabled because of
6980 // underrun; it will then automatically call start() when data is available
6981 track->disable();
6982 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6983 // unlike mixerthread, HAL can be paused for direct output
6984 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6985 "minFrames = %u, mFormat = %#x",
6986 framesReady, minFrames, mFormat);
6987 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6988 doHwPause = true;
6989 mHwPaused = true;
6990 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006991 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006992 } else if (last) {
6993 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006994 }
6995 }
6996 }
6997 }
6998
Eric Laurentd1f69b02014-12-15 14:33:13 -08006999 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007000 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007001 for (size_t i = 0; i < mTracks.size(); i++) {
7002 if (mTracks[i]->isFlushPending()) {
7003 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007004 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007005 }
7006 }
7007 }
7008
7009 // make sure the pause/flush/resume sequence is executed in the right order.
7010 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7011 // before flush and then resume HW. This can happen in case of pause/flush/resume
7012 // if resume is received before pause is executed.
7013 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007014 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007015 status_t result = mOutput->stream->pause();
7016 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007017 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007018 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007019 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007020 flushHw_l();
7021 }
7022 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007023 status_t result = mOutput->stream->resume();
7024 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007025 }
Eric Laurent81784c32012-11-19 14:55:58 -08007026 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007027 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007028
7029 return mixerStatus;
7030}
7031
Andy Hung4b17e882023-07-07 13:47:37 -07007032void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007033{
Eric Laurent81784c32012-11-19 14:55:58 -08007034 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007035 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007036 // output audio to hardware
7037 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007038 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007039 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007040 status_t status = mActiveTrack->getNextBuffer(&buffer);
7041 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007042 // no need to pad with 0 for compressed audio
7043 if (audio_has_proportional_frames(mFormat)) {
7044 memset(curBuf, 0, frameCount * mFrameSize);
7045 }
Eric Laurent81784c32012-11-19 14:55:58 -08007046 break;
7047 }
7048 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7049 frameCount -= buffer.frameCount;
7050 curBuf += buffer.frameCount * mFrameSize;
7051 mActiveTrack->releaseBuffer(&buffer);
7052 }
Andy Hung2098f272014-02-27 14:00:06 -08007053 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007054 mSleepTimeUs = 0;
7055 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007056 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007057}
7058
Andy Hung4b17e882023-07-07 13:47:37 -07007059void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007060{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007061 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007062 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007063 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007064 return;
7065 }
Andy Hung85ba3332021-04-27 17:40:26 -07007066 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7067 mSleepTimeUs = mActiveSleepTimeUs;
7068 } else {
7069 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007070 }
Andy Hung85ba3332021-04-27 17:40:26 -07007071 // Note: In S or later, we do not write zeroes for
7072 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007073}
7074
Andy Hung4b17e882023-07-07 13:47:37 -07007075void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007076{
7077 {
Andy Hungf8635b62023-08-31 16:13:39 -07007078 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007079 for (size_t i = 0; i < mTracks.size(); i++) {
7080 if (mTracks[i]->isFlushPending()) {
7081 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007082 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007083 }
7084 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007085 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007086 flushHw_l();
7087 }
7088 }
7089 PlaybackThread::threadLoop_exit();
7090}
7091
7092// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007093bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007094{
7095 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007096 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007097 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007098
Eric Laurent022a5132024-04-12 17:02:51 +00007099 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007100 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007101 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007102 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007103 const auto& mainTrack = mTracks[mTracks.size() - 1];
7104
7105 trackPaused = mainTrack->isPaused();
7106 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7107 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007108 }
7109
Eric Laurent022a5132024-04-12 17:02:51 +00007110 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007111}
7112
Andy Hungb17d24b2023-08-29 14:26:09 -07007113// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07007114bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007115 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007116{
7117 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007118 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007119
Eric Laurent10351942014-05-08 18:49:52 -07007120 AudioParameter param = AudioParameter(keyValuePair);
7121 int value;
7122 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007123 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007124 }
Eric Laurent10351942014-05-08 18:49:52 -07007125 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7126 // do not accept frame count changes if tracks are open as the track buffer
7127 // size depends on frame count and correct behavior would not be garantied
7128 // if frame count is changed after track creation
7129 if (!mTracks.isEmpty()) {
7130 status = INVALID_OPERATION;
7131 } else {
7132 reconfig = true;
7133 }
7134 }
7135 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007136 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007137 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007138 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007139 if (!mStandby) {
7140 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007141 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007142 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007143 }
Eric Laurent10351942014-05-08 18:49:52 -07007144 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007145 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007146 }
7147 if (status == NO_ERROR && reconfig) {
7148 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007149 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007150 }
7151 }
7152
Dean Wheatley68918102021-03-19 22:09:19 +11007153 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007154}
7155
Andy Hung4b17e882023-07-07 13:47:37 -07007156uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007157{
7158 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007159 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007160 time = PlaybackThread::activeSleepTimeUs();
7161 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007162 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007163 }
7164 return time;
7165}
7166
Andy Hung4b17e882023-07-07 13:47:37 -07007167uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007168{
7169 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007170 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007171 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7172 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007173 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007174 }
7175 return time;
7176}
7177
Andy Hung4b17e882023-07-07 13:47:37 -07007178uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007179{
7180 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007181 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007182 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7183 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007184 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007185 }
7186 return time;
7187}
7188
Andy Hung4b17e882023-07-07 13:47:37 -07007189void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007190{
7191 PlaybackThread::cacheParameters_l();
7192
7193 // use shorter standby delay as on normal output to release
7194 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007195 // no delay on outputs with HW A/V sync
7196 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007197 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007198 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007199 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007200 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007201 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007202 }
Eric Laurent81784c32012-11-19 14:55:58 -08007203}
7204
Andy Hung4b17e882023-07-07 13:47:37 -07007205void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007206{
ziyangch8f194f12021-12-01 13:48:04 -08007207 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007208 mOutput->flush();
Haofan Wang3987e9d2024-06-17 21:22:00 +00007209 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007210 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007211 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007212 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007213 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007214}
7215
Andy Hung4b17e882023-07-07 13:47:37 -07007216int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007217 // If a VolumeShaper is active, we must wake up periodically to update volume.
7218 const int64_t NS_PER_MS = 1000000;
7219 return mVolumeShaperActive ?
7220 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7221}
7222
Eric Laurent81784c32012-11-19 14:55:58 -08007223// ----------------------------------------------------------------------------
7224
Andy Hung4b17e882023-07-07 13:47:37 -07007225AsyncCallbackThread::AsyncCallbackThread(
7226 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007227 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007228 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007229 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007230 mDrainSequence(0),
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007231 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007232{
7233}
7234
Andy Hung4b17e882023-07-07 13:47:37 -07007235void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007236{
7237 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7238}
7239
Andy Hung4b17e882023-07-07 13:47:37 -07007240bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007241{
7242 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007243 uint32_t writeAckSequence;
7244 uint32_t drainSequence;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007245 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007246
7247 {
Andy Hungb17d24b2023-08-29 14:26:09 -07007248 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007249 while (!((mWriteAckSequence & 1) ||
7250 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007251 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007252 exitPending())) {
Andy Hungb17d24b2023-08-29 14:26:09 -07007253 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007254 }
7255
Eric Laurentbfb1b832013-01-07 09:53:42 -08007256 if (exitPending()) {
7257 break;
7258 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007259 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7260 mWriteAckSequence, mDrainSequence);
7261 writeAckSequence = mWriteAckSequence;
7262 mWriteAckSequence &= ~1;
7263 drainSequence = mDrainSequence;
7264 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007265 asyncError = mAsyncError;
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007266 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007267 }
7268 {
Andy Hung4b17e882023-07-07 13:47:37 -07007269 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007270 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007271 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007272 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007273 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007274 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007275 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007276 }
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007277 if (asyncError != ASYNC_ERROR_NONE) {
7278 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007279 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007280 }
7281 }
7282 }
7283 return false;
7284}
7285
Andy Hung4b17e882023-07-07 13:47:37 -07007286void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007287{
7288 ALOGV("AsyncCallbackThread::exit");
Andy Hungf8635b62023-08-31 16:13:39 -07007289 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007290 requestExit();
Andy Hungb17d24b2023-08-29 14:26:09 -07007291 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007292}
7293
Andy Hung4b17e882023-07-07 13:47:37 -07007294void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007295{
Andy Hungf8635b62023-08-31 16:13:39 -07007296 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007297 // bit 0 is cleared
7298 mWriteAckSequence = sequence << 1;
7299}
7300
Andy Hung4b17e882023-07-07 13:47:37 -07007301void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007302{
Andy Hungf8635b62023-08-31 16:13:39 -07007303 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007304 // ignore unexpected callbacks
7305 if (mWriteAckSequence & 2) {
7306 mWriteAckSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007307 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007308 }
7309}
7310
Andy Hung4b17e882023-07-07 13:47:37 -07007311void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007312{
Andy Hungf8635b62023-08-31 16:13:39 -07007313 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007314 // bit 0 is cleared
7315 mDrainSequence = sequence << 1;
7316}
7317
Andy Hung4b17e882023-07-07 13:47:37 -07007318void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007319{
Andy Hungf8635b62023-08-31 16:13:39 -07007320 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007321 // ignore unexpected callbacks
7322 if (mDrainSequence & 2) {
7323 mDrainSequence |= 1;
Andy Hungb17d24b2023-08-29 14:26:09 -07007324 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007325 }
7326}
7327
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007328void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007329{
Andy Hungf8635b62023-08-31 16:13:39 -07007330 audio_utils::lock_guard _l(mutex());
Mikhail Naganovf548cd32024-05-29 17:06:46 +00007331 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungb17d24b2023-08-29 14:26:09 -07007332 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007333}
7334
Eric Laurentbfb1b832013-01-07 09:53:42 -08007335
7336// ----------------------------------------------------------------------------
Andy Hung4b17e882023-07-07 13:47:37 -07007337
7338/* static */
7339sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007340 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007341 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7342 const audio_offload_info_t& offloadInfo) {
Andy Hung7535ed92023-07-17 17:05:00 -07007343 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung4b17e882023-07-07 13:47:37 -07007344}
7345
Andy Hung7535ed92023-07-17 17:05:00 -07007346OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007347 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7348 const audio_offload_info_t& offloadInfo)
Andy Hung7535ed92023-07-17 17:05:00 -07007349 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007350 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007351{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007352 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007353 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007354 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007355}
7356
Andy Hung4b17e882023-07-07 13:47:37 -07007357void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007358{
7359 if (mFlushPending || mHwPaused) {
7360 // If a flush is pending or track was paused, just discard buffered data
Andy Hung94dfbb42023-09-06 19:41:47 -07007361 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007362 flushHw_l();
7363 } else {
7364 mMixerStatus = MIXER_DRAIN_ALL;
7365 threadLoop_drain();
7366 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007367 if (mUseAsyncWrite) {
7368 ALOG_ASSERT(mCallbackThread != 0);
7369 mCallbackThread->exit();
7370 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007371 PlaybackThread::threadLoop_exit();
7372}
7373
Andy Hung4b17e882023-07-07 13:47:37 -07007374PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -07007375 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007376)
7377{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007378 size_t count = mActiveTracks.size();
7379
7380 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007381 bool doHwPause = false;
7382 bool doHwResume = false;
7383
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007384 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007385
Eric Laurentbfb1b832013-01-07 09:53:42 -08007386 // find out which tracks need to be processed
Andy Hung11e74242023-06-26 19:20:57 -07007387 for (const sp<IAfTrack>& t : mActiveTracks) {
7388 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007389#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007390 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007391#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007392 // Only consider last track started for volume and mixer state control.
7393 // In theory an older track could underrun and restart after the new one starts
7394 // but as we only care about the transition phase between two tracks on a
7395 // direct output, it is not a problem to ignore the underrun case.
Andy Hung11e74242023-06-26 19:20:57 -07007396 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007397 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007398
Haynes Mathew George7844f672014-01-15 12:32:55 -08007399 if (track->isInvalid()) {
7400 ALOGW("An invalidated track shouldn't be in active list");
7401 tracksToRemove->add(track);
7402 continue;
7403 }
7404
Andy Hung11e74242023-06-26 19:20:57 -07007405 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007406 ALOGW("An idle track shouldn't be in active list");
7407 continue;
7408 }
7409
Kuowei Li23666472021-01-20 10:23:25 +08007410 if (track->isPausePending()) {
7411 track->pauseAck();
7412 // It is possible a track might have been flushed or stopped.
7413 // Other operations such as flush pending might occur on the next prepare.
7414 if (track->isPausing()) {
7415 track->setPaused();
7416 }
7417 // Always perform pause if last, as an immediate flush will change
7418 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007419 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007420 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007421 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007422 mHwPaused = true;
7423 }
7424 // If we were part way through writing the mixbuffer to
7425 // the HAL we must save this until we resume
7426 // BUG - this will be wrong if a different track is made active,
7427 // in that case we want to discard the pending data in the
7428 // mixbuffer and tell the client to present it again when the
7429 // track is resumed
7430 mPausedWriteLength = mCurrentWriteLength;
7431 mPausedBytesRemaining = mBytesRemaining;
7432 mBytesRemaining = 0; // stop writing
7433 }
7434 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007435 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007436 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007437 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007438 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007439 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007440 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007441 track->flushAck();
7442 if (last) {
7443 mFlushPending = true;
7444 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007445 } else if (track->isResumePending()){
7446 track->resumeAck();
7447 if (last) {
7448 if (mPausedBytesRemaining) {
7449 // Need to continue write that was interrupted
7450 mCurrentWriteLength = mPausedWriteLength;
7451 mBytesRemaining = mPausedBytesRemaining;
7452 mPausedBytesRemaining = 0;
7453 }
7454 if (mHwPaused) {
7455 doHwResume = true;
7456 mHwPaused = false;
7457 // threadLoop_mix() will handle the case that we need to
7458 // resume an interrupted write
7459 }
7460 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007461 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007462
Eric Laurent3df841a2016-07-15 15:15:40 -07007463 mLeftVolFloat = mRightVolFloat = -1.0;
7464
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007465 // Do not handle new data in this iteration even if track->framesReady()
7466 mixerStatus = MIXER_TRACKS_ENABLED;
7467 }
7468 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007469 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007470 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung11e74242023-06-26 19:20:57 -07007471 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7472 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007473 if (last) {
7474 // make sure processVolume_l() will apply new volume even if 0
7475 mLeftVolFloat = mRightVolFloat = -1.0;
7476 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007477 }
7478
7479 if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007480 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007481 if (previousTrack != 0) {
7482 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007483 // Flush any data still being written from last track
7484 mBytesRemaining = 0;
7485 if (mPausedBytesRemaining) {
7486 // Last track was paused so we also need to flush saved
7487 // mixbuffer state and invalidate track so that it will
7488 // re-submit that unwritten data when it is next resumed
7489 mPausedBytesRemaining = 0;
7490 // Invalidate is a bit drastic - would be more efficient
7491 // to have a flag to tell client that some of the
7492 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007493 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007494 }
7495 // flush data already sent to the DSP if changing audio session as audio
7496 // comes from a different source. Also invalidate previous track to force a
7497 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007498 if (previousTrack->sessionId() != track->sessionId()) {
7499 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007500 }
7501 }
7502 }
7503 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007504 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007505 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007506 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007507 } else {
Andy Hung11e74242023-06-26 19:20:57 -07007508 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007509 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007510 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007511 mixerStatus = MIXER_TRACKS_READY;
7512 }
7513 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007514 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007515 if (track->isStopping_1()) {
Andy Hung11e74242023-06-26 19:20:57 -07007516 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007517 // Hardware buffer can hold a large amount of audio so we must
7518 // wait for all current track's data to drain before we say
7519 // that the track is stopped.
7520 if (mBytesRemaining == 0) {
7521 // Only start draining when all data in mixbuffer
7522 // has been written
7523 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung11e74242023-06-26 19:20:57 -07007524 track->setState(IAfTrackBase::STOPPING_2);
7525 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007526 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7527 if (last && !mStandby) {
7528 // do not modify drain sequence if we are already draining. This happens
7529 // when resuming from pause after drain.
7530 if ((mDrainSequence & 1) == 0) {
7531 mSleepTimeUs = 0;
7532 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7533 mixerStatus = MIXER_DRAIN_TRACK;
7534 mDrainSequence += 2;
7535 }
7536 if (mHwPaused) {
7537 // It is possible to move from PAUSED to STOPPING_1 without
7538 // a resume so we must ensure hardware is running
7539 doHwResume = true;
7540 mHwPaused = false;
7541 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007542 }
7543 }
Eric Laurente93cc032016-05-05 10:15:10 -07007544 } else if (last) {
Andy Hung11e74242023-06-26 19:20:57 -07007545 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007546 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007547 }
7548 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007549 // Drain has completed or we are in standby, signal presentation complete
7550 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung11e74242023-06-26 19:20:57 -07007551 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007552 mOutput->presentationComplete();
7553 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007554 track->reset();
7555 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007556 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007557 if (!mUseAsyncWrite) {
7558 // If we don't get explicit drain notification we must
7559 // register discontinuity regardless of whether this is
7560 // the previous (!last) or the upcoming (last) track
7561 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007562 mTimestampVerifier.discontinuity(
7563 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007564 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007565 }
7566 } else {
7567 // No buffers for this track. Give it a few chances to
7568 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007569 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007570 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung11e74242023-06-26 19:20:57 -07007571 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007572 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung11e74242023-06-26 19:20:57 -07007573 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007574 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007575 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7576 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007577 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007578 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007579 // it will then automatically call start() when data is available
7580 track->disable();
7581 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007582 } else if (last){
7583 mixerStatus = MIXER_TRACKS_ENABLED;
7584 }
7585 }
7586 }
7587 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007588 if (track->isReady()) { // check ready to prevent premature start.
7589 processVolume_l(track, last);
7590 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007591 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007592
Eric Laurentea0fade2013-10-04 16:23:48 -07007593 // make sure the pause/flush/resume sequence is executed in the right order.
7594 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7595 // before flush and then resume HW. This can happen in case of pause/flush/resume
7596 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007597 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007598 status_t result = mOutput->stream->pause();
7599 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007600 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007601 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007602 if (mFlushPending) {
7603 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007604 }
Eric Laurentfd477972013-10-25 18:10:40 -07007605 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007606 status_t result = mOutput->stream->resume();
7607 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007608 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007609
Eric Laurentbfb1b832013-01-07 09:53:42 -08007610 // remove all the tracks that need to be...
7611 removeTracks_l(*tracksToRemove);
7612
7613 return mixerStatus;
7614}
7615
Eric Laurentbfb1b832013-01-07 09:53:42 -08007616// must be called with thread mutex locked
Andy Hung4b17e882023-07-07 13:47:37 -07007617bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007618{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007619 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7620 mWriteAckSequence, mDrainSequence);
7621 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007622 return true;
7623 }
7624 return false;
7625}
7626
Andy Hung4b17e882023-07-07 13:47:37 -07007627bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007628{
Andy Hungf8635b62023-08-31 16:13:39 -07007629 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007630 return waitingAsyncCallback_l();
7631}
7632
Andy Hung4b17e882023-07-07 13:47:37 -07007633void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007634{
Eric Laurente659ef42014-09-29 13:06:46 -07007635 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007636 // Flush anything still waiting in the mixbuffer
7637 mCurrentWriteLength = 0;
7638 mBytesRemaining = 0;
7639 mPausedWriteLength = 0;
7640 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007641 // reset bytes written count to reflect that DSP buffers are empty after flush.
7642 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007643
Eric Laurentbfb1b832013-01-07 09:53:42 -08007644 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007645 // discard any pending drain or write ack by incrementing sequence
7646 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7647 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007648 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007649 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7650 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007651 }
7652}
7653
Andy Hung4b17e882023-07-07 13:47:37 -07007654void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007655{
Andy Hungf8635b62023-08-31 16:13:39 -07007656 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007657 if (PlaybackThread::invalidateTracks_l(streamType)) {
7658 mFlushPending = true;
7659 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007660}
7661
Andy Hung4b17e882023-07-07 13:47:37 -07007662void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf8635b62023-08-31 16:13:39 -07007663 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007664 if (PlaybackThread::invalidateTracks_l(portIds)) {
7665 mFlushPending = true;
7666 }
7667}
7668
Eric Laurentbfb1b832013-01-07 09:53:42 -08007669// ----------------------------------------------------------------------------
7670
Andy Hung4b17e882023-07-07 13:47:37 -07007671/* static */
7672sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -07007673 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007674 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07007675 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -07007676}
7677
Andy Hung7535ed92023-07-17 17:05:00 -07007678DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07007679 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -07007680 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007681 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007682 mWaitTimeMs(UINT_MAX)
7683{
7684 addOutputTrack(mainThread);
7685}
7686
Andy Hung4b17e882023-07-07 13:47:37 -07007687DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007688{
7689 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7690 mOutputTracks[i]->destroy();
7691 }
7692}
7693
Andy Hung4b17e882023-07-07 13:47:37 -07007694void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007695{
7696 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007697 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007698 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007699 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007700 if (mMixerBufferValid) {
7701 memset(mMixerBuffer, 0, mMixerBufferSize);
7702 } else {
7703 memset(mSinkBuffer, 0, mSinkBufferSize);
7704 }
Eric Laurent81784c32012-11-19 14:55:58 -08007705 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007706 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007707 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007708 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007709 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007710}
7711
Andy Hung4b17e882023-07-07 13:47:37 -07007712void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007713{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007714 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007715 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007716 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007717 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007718 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007719 }
7720 } else if (mBytesWritten != 0) {
7721 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7722 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007723 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007724 } else {
7725 // flush remaining overflow buffers in output tracks
7726 writeFrames = 0;
7727 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007728 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007729 }
7730}
7731
Andy Hung4b17e882023-07-07 13:47:37 -07007732ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007733{
Jiabin Huang4d0c9e82024-10-28 21:51:36 +00007734 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08007735 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007736 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7737
7738 // Consider the first OutputTrack for timestamp and frame counting.
7739
7740 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7741 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7742 // we always claim success.
7743 if (i == 0) {
7744 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7745 ALOGD_IF(correction != 0 && writeFrames != 0,
7746 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7747 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7748 mFramesWritten -= correction;
7749 }
7750
7751 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007752 }
Jiabin Huang4d0c9e82024-10-28 21:51:36 +00007753 ATRACE_END();
Andy Hungcf10d742020-04-28 15:38:24 -07007754 if (mStandby) {
7755 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007756 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007757 mStandby = false;
7758 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007759 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007760}
7761
Andy Hung4b17e882023-07-07 13:47:37 -07007762void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007763{
7764 // DuplicatingThread implements standby by stopping all tracks
7765 for (size_t i = 0; i < outputTracks.size(); i++) {
7766 outputTracks[i]->stop();
7767 }
7768}
7769
Andy Hung8a5abfd2023-12-07 19:35:12 -08007770void DuplicatingThread::threadLoop_exit()
7771{
7772 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7773 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7774 // Do so here in the threadLoop_exit().
7775
7776 SortedVector <sp<IAfOutputTrack>> localTracks;
7777 {
7778 audio_utils::lock_guard l(mutex());
7779 localTracks = std::move(mOutputTracks);
7780 mOutputTracks.clear();
7781 }
7782 localTracks.clear();
7783 outputTracks.clear();
7784 PlaybackThread::threadLoop_exit();
7785}
7786
Andy Hung4b17e882023-07-07 13:47:37 -07007787void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007788{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007789 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007790
7791 std::stringstream ss;
7792 const size_t numTracks = mOutputTracks.size();
7793 ss << " " << numTracks << " OutputTracks";
7794 if (numTracks > 0) {
7795 ss << ":";
7796 for (const auto &track : mOutputTracks) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007797 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007798 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007799 if (thread.get() != nullptr) {
7800 ss << thread.get() << ", " << thread->id();
7801 } else {
7802 ss << "null";
7803 }
7804 ss << ")";
7805 }
7806 }
7807 ss << "\n";
7808 std::string result = ss.str();
7809 write(fd, result.c_str(), result.size());
7810}
7811
Andy Hung4b17e882023-07-07 13:47:37 -07007812void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007813{
7814 outputTracks = mOutputTracks;
7815}
7816
Andy Hung4b17e882023-07-07 13:47:37 -07007817void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007818{
7819 outputTracks.clear();
7820}
7821
Andy Hung4b17e882023-07-07 13:47:37 -07007822void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007823{
Andy Hungf8635b62023-08-31 16:13:39 -07007824 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007825 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7826 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7827 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7828 const size_t frameCount =
7829 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7830 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7831 // from different OutputTracks and their associated MixerThreads (e.g. one may
7832 // nearly empty and the other may be dropping data).
7833
Svet Ganov33761132021-05-13 22:51:08 +00007834 // TODO b/182392769: use attribution source util, move to server edge
7835 AttributionSourceState attributionSource = AttributionSourceState();
7836 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007837 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007838 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007839 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007840 attributionSource.token = sp<BBinder>::make();
Andy Hung11e74242023-06-26 19:20:57 -07007841 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007842 this,
7843 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007844 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007845 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007846 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007847 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007848 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7849 if (status != NO_ERROR) {
7850 ALOGE("addOutputTrack() initCheck failed %d", status);
7851 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007852 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007853 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7854 mOutputTracks.add(outputTrack);
7855 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7856 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007857}
7858
Andy Hung4b17e882023-07-07 13:47:37 -07007859void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007860{
Andy Hungf8635b62023-08-31 16:13:39 -07007861 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007862 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7863 if (mOutputTracks[i]->thread() == thread) {
7864 mOutputTracks[i]->destroy();
7865 mOutputTracks.removeAt(i);
7866 updateWaitTime_l();
Andy Hung160664b2023-09-15 18:19:28 -07007867 // NO_THREAD_SAFETY_ANALYSIS
7868 // Lambda workaround: as thread != this
7869 // we can safely call the remote thread getOutput.
7870 const bool equalOutput =
7871 [&](){ return thread->getOutput() == mOutput; }();
7872 if (equalOutput) {
7873 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007874 }
Eric Laurent81784c32012-11-19 14:55:58 -08007875 return;
7876 }
7877 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007878 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007879}
7880
Andy Hungb17d24b2023-08-29 14:26:09 -07007881// caller must hold mutex()
Andy Hung4b17e882023-07-07 13:47:37 -07007882void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007883{
7884 mWaitTimeMs = UINT_MAX;
7885 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007886 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007887 if (strong != 0) {
7888 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7889 if (waitTimeMs < mWaitTimeMs) {
7890 mWaitTimeMs = waitTimeMs;
7891 }
7892 }
7893 }
7894}
7895
Andy Hung4b17e882023-07-07 13:47:37 -07007896bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007897{
7898 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung0c1e11e2023-07-06 20:56:16 -07007899 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007900 if (thread == 0) {
7901 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7902 outputTracks[i].get());
7903 return false;
7904 }
Andy Hung0c1e11e2023-07-06 20:56:16 -07007905 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007906 // see note at standby() declaration
Andy Hung3e4c8742023-06-29 21:19:25 -07007907 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007908 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7909 thread.get());
7910 return false;
7911 }
7912 }
7913 return true;
7914}
7915
Andy Hung4b17e882023-07-07 13:47:37 -07007916void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007917 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007918{
Kevin Rocard12381092018-04-11 09:19:59 -07007919 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7920 outputTrack->setMetadatas(metadata.tracks);
7921 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007922}
7923
Andy Hung4b17e882023-07-07 13:47:37 -07007924uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007925{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007926 // return half the wait time in microseconds.
7927 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007928}
7929
Andy Hung4b17e882023-07-07 13:47:37 -07007930void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007931{
7932 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7933 updateWaitTime_l();
7934
7935 MixerThread::cacheParameters_l();
7936}
7937
Eric Laurentb3f315a2021-07-13 15:09:05 +02007938// ----------------------------------------------------------------------------
7939
Andy Hung4b17e882023-07-07 13:47:37 -07007940/* static */
7941sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung7535ed92023-07-17 17:05:00 -07007942 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -07007943 AudioStreamOut* output,
7944 audio_io_handle_t id,
7945 bool systemReady,
7946 audio_config_base_t* mixerConfig) {
Andy Hung7535ed92023-07-17 17:05:00 -07007947 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung4b17e882023-07-07 13:47:37 -07007948}
7949
Andy Hung7535ed92023-07-17 17:05:00 -07007950SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007951 AudioStreamOut* output,
7952 audio_io_handle_t id,
7953 bool systemReady,
7954 audio_config_base_t *mixerConfig)
Andy Hung7535ed92023-07-17 17:05:00 -07007955 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007956{
7957}
7958
Andy Hung4b17e882023-07-07 13:47:37 -07007959void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007960 // if mSupportedLatencyModes is empty, the HAL stream does not support
7961 // latency mode control and we can exit.
7962 if (mSupportedLatencyModes.empty()) {
7963 return;
7964 }
Eric Laurent4c85e372024-02-23 16:50:06 +00007965 // Do not update the HAL latency mode if no track is active
7966 if (mActiveTracks.isEmpty()) {
7967 return;
7968 }
7969
Eric Laurent68a40a82022-05-03 18:15:04 +02007970 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7971 if (mSupportedLatencyModes.size() == 1) {
7972 // If the HAL only support one latency mode currently, confirm the choice
7973 latencyMode = mSupportedLatencyModes[0];
7974 } else if (mSupportedLatencyModes.size() > 1) {
7975 // Request low latency if:
7976 // - The low latency mode is requested by the spatializer controller
7977 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7978 // AND
7979 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007980 for (const auto& track : mActiveTracks) {
7981 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007982 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007983 break;
7984 }
7985 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007986 }
7987
7988 if (latencyMode != mSetLatencyMode) {
7989 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007990 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7991 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007992 if (status == NO_ERROR) {
7993 mSetLatencyMode = latencyMode;
7994 }
7995 }
7996}
7997
Andy Hung4b17e882023-07-07 13:47:37 -07007998status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007999 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008000 return BAD_VALUE;
8001 }
Andy Hungf8635b62023-08-31 16:13:39 -07008002 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008003 mRequestedLatencyMode = mode;
8004 return NO_ERROR;
8005}
8006
Andy Hung4b17e882023-07-07 13:47:37 -07008007void SpatializerThread::checkOutputStageEffects()
Andy Hungf8635b62023-08-31 16:13:39 -07008008NO_THREAD_SAFETY_ANALYSIS
8009// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008010{
8011 bool hasVirtualizer = false;
8012 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008013 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008014 {
Andy Hungf8635b62023-08-31 16:13:39 -07008015 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008016 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008017 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008018 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008019 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8020 }
8021
8022 finalDownMixer = mFinalDownMixer;
8023 mFinalDownMixer.clear();
8024 }
8025
8026 if (hasVirtualizer) {
8027 if (finalDownMixer != nullptr) {
8028 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008029 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008030 }
8031 finalDownMixer.clear();
8032 } else if (!hasDownMixer) {
8033 std::vector<effect_descriptor_t> descriptors;
Andy Hung7535ed92023-07-17 17:05:00 -07008034 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008035 EFFECT_UIID_DOWNMIX, &descriptors);
8036 if (status != NO_ERROR) {
8037 return;
8038 }
8039 ALOG_ASSERT(!descriptors.empty(),
8040 "%s getDescriptors() returned no error but empty list", __func__);
8041
8042 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8043 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008044 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008045
8046 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8047 ALOGW("%s error creating downmixer %d", __func__, status);
8048 finalDownMixer.clear();
8049 } else {
8050 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008051 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008052 }
8053 }
8054
8055 {
Andy Hungf8635b62023-08-31 16:13:39 -07008056 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008057 mFinalDownMixer = finalDownMixer;
8058 }
8059}
8060
Andy Hunge2514462023-12-06 14:59:24 -08008061void SpatializerThread::threadLoop_exit()
8062{
8063 // The Spatializer EffectHandle must be released on the PlaybackThread
8064 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8065 mFinalDownMixer.clear();
8066
8067 PlaybackThread::threadLoop_exit();
8068}
8069
Eric Laurent81784c32012-11-19 14:55:58 -08008070// ----------------------------------------------------------------------------
8071// Record
8072// ----------------------------------------------------------------------------
8073
Andy Hung7535ed92023-07-17 17:05:00 -07008074sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung0c1e11e2023-07-06 20:56:16 -07008075 AudioStreamIn* input,
8076 audio_io_handle_t id,
8077 bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -07008078 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung0c1e11e2023-07-06 20:56:16 -07008079}
8080
Andy Hung7535ed92023-07-17 17:05:00 -07008081RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008082 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008083 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008084 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008085 ) :
Andy Hung7535ed92023-07-17 17:05:00 -07008086 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008087 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008088 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008089 mActiveTracks(&this->mLocalLog),
8090 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008091 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008092 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008093 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8094 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008095 // mFastCapture below
8096 , mFastCaptureFutex(0)
8097 // mInputSource
8098 // mPipeSink
8099 // mPipeSource
8100 , mPipeFramesP2(0)
8101 // mPipeMemory
8102 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008103 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008104 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008105{
Glenn Kastend7dca052015-03-05 16:05:54 -08008106 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung7535ed92023-07-17 17:05:00 -07008107 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008108
George Burgess IVa8f90c12020-05-14 11:27:19 -07008109 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008110 mIsMsdDevice = strcmp(
8111 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8112 }
8113
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008114 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008115
Andy Hungc8fddf32018-08-08 18:32:37 -07008116 // TODO: We may also match on address as well as device type for
8117 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008118 // TODO: This property should be ensure that only contains one single device type.
8119 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8120 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008121 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8122 : AUDIO_DEVICE_NONE));
8123
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008124 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008125 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008126 size_t numCounterOffers = 0;
8127 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008128#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008129 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008130#else
8131 (void)
8132#endif
8133 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008134 ALOG_ASSERT(index == 0);
8135
8136 // initialize fast capture depending on configuration
8137 bool initFastCapture;
8138 switch (kUseFastCapture) {
8139 case FastCapture_Never:
8140 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008141 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008142 break;
8143 case FastCapture_Always:
8144 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008145 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008146 break;
8147 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008148 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008149 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008150 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008151 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8152 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8153 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008154 break;
8155 // case FastCapture_Dynamic:
8156 }
8157
8158 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008159 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008160 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008161 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8162 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008163 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008164 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008165 const sp<MemoryDealer> roHeap(readOnlyHeap());
8166 sp<IMemory> pipeMemory;
8167 if ((roHeap == 0) ||
8168 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008169 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008170 ALOGE("not enough memory for pipe buffer size=%zu; "
8171 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8172 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8173 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008174 goto failed;
8175 }
8176 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8177 memset(pipeBuffer, 0, pipeSize);
8178 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008179 const NBAIO_Format offersFast[1] = {format};
8180 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008181 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008182 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008183 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008184 mPipeSink = pipe;
8185 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008186 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008187 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008188 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008189 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008190 mPipeSource = pipeReader;
8191 mPipeFramesP2 = pipeFramesP2;
8192 mPipeMemory = pipeMemory;
8193
8194 // create fast capture
8195 mFastCapture = new FastCapture();
8196 FastCaptureStateQueue *sq = mFastCapture->sq();
8197#ifdef STATE_QUEUE_DUMP
8198 // FIXME
8199#endif
8200 FastCaptureState *state = sq->begin();
8201 state->mCblk = NULL;
8202 state->mInputSource = mInputSource.get();
8203 state->mInputSourceGen++;
8204 state->mPipeSink = pipe;
8205 state->mPipeSinkGen++;
8206 state->mFrameCount = mFrameCount;
8207 state->mCommand = FastCaptureState::COLD_IDLE;
8208 // already done in constructor initialization list
8209 //mFastCaptureFutex = 0;
8210 state->mColdFutexAddr = &mFastCaptureFutex;
8211 state->mColdGen++;
8212 state->mDumpState = &mFastCaptureDumpState;
8213#ifdef TEE_SINK
8214 // FIXME
8215#endif
Andy Hung7535ed92023-07-17 17:05:00 -07008216 mFastCaptureNBLogWriter =
8217 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008218 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8219 sq->end();
8220 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8221
8222 // start the fast capture
8223 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8224 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008225 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008226 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008227#ifdef AUDIO_WATCHDOG
8228 // FIXME
8229#endif
8230
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008231 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008232 }
Andy Hung8946a282018-04-19 20:04:56 -07008233#ifdef TEE_SINK
8234 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8235 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8236#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008237failed: ;
8238
8239 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008240}
8241
Andy Hung4b17e882023-07-07 13:47:37 -07008242RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008243{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008244 if (mFastCapture != 0) {
8245 FastCaptureStateQueue *sq = mFastCapture->sq();
8246 FastCaptureState *state = sq->begin();
8247 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8248 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8249 if (old == -1) {
8250 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8251 }
8252 }
8253 state->mCommand = FastCaptureState::EXIT;
8254 sq->end();
8255 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8256 mFastCapture->join();
8257 mFastCapture.clear();
8258 }
Andy Hung7535ed92023-07-17 17:05:00 -07008259 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8260 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008261 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008262}
8263
Andy Hung4b17e882023-07-07 13:47:37 -07008264void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008265{
Glenn Kastend7dca052015-03-05 16:05:54 -08008266 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008267}
8268
Andy Hung4b17e882023-07-07 13:47:37 -07008269void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008270{
8271 ALOGV(" preExit()");
Andy Hungf8635b62023-08-31 16:13:39 -07008272 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008273 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008274 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008275 track->invalidate();
8276 }
8277 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008278 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008279}
8280
Andy Hung4b17e882023-07-07 13:47:37 -07008281bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008282{
Eric Laurent81784c32012-11-19 14:55:58 -08008283 nsecs_t lastWarning = 0;
8284
8285 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008286
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008287reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008288 {
Andy Hungf8635b62023-08-31 16:13:39 -07008289 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008290 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008291 }
8292
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008293 // used to request a deferred sleep, to be executed later while mutex is unlocked
8294 uint32_t sleepUs = 0;
8295
Andy Hung1381a072023-10-20 16:41:18 -07008296 // timestamp correction enable is determined under lock, used in processing step.
8297 bool timestampCorrectionEnabled = false;
8298
Andy Hung446f4df2019-02-21 12:26:41 -08008299 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008301 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008302 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungfdb84b92024-03-15 10:15:10 -07008303 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8304 sp<IAfRecordTrack> activeTrack;
Andy Hungb2b01c62024-04-23 13:56:19 -07008305 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008306 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008307
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008308 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung11e74242023-06-26 19:20:57 -07008309 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008310
Glenn Kasten735f45f2014-08-18 15:51:59 -07008311 // reference to the (first and only) active fast track
Andy Hung11e74242023-06-26 19:20:57 -07008312 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008313
Glenn Kasten735f45f2014-08-18 15:51:59 -07008314 // reference to a fast track which is about to be removed
Andy Hung11e74242023-06-26 19:20:57 -07008315 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008316
Eric Laurent33403f02020-05-29 18:35:06 -07008317 bool silenceFastCapture = false;
8318
Andy Hungb17d24b2023-08-29 14:26:09 -07008319 { // scope for mutex()
8320 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008321
Eric Laurent021cf962014-05-13 10:18:14 -07008322 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008323
Eric Laurent000a4192014-01-29 15:17:32 -08008324 // check exitPending here because checkForNewParameters_l() and
Andy Hungb17d24b2023-08-29 14:26:09 -07008325 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008326 if (exitPending()) {
8327 break;
8328 }
8329
Eric Laurent5c25d562016-07-13 17:17:45 -07008330 // sleep with mutex unlocked
8331 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008332 ATRACE_BEGIN("sleepC");
Andy Hungb17d24b2023-08-29 14:26:09 -07008333 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008334 ATRACE_END();
8335 sleepUs = 0;
8336 continue;
8337 }
8338
Glenn Kasten2b806402013-11-20 16:37:38 -08008339 // if no active track(s), then standby and release wakelock
8340 size_t size = mActiveTracks.size();
8341 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008342 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008343 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008344 releaseWakeLock_l();
8345 ALOGV("RecordThread: loop stopping");
8346 // go to sleep
Andy Hungb17d24b2023-08-29 14:26:09 -07008347 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008348 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008349 goto reacquire_wakelock;
8350 }
8351
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008352 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008353 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008354 for (size_t i = 0; i < size; ) {
Andy Hungb2b01c62024-04-23 13:56:19 -07008355 if (activeTrack) { // ensure track release is outside lock.
8356 oldActiveTracks.emplace_back(std::move(activeTrack));
8357 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008358 activeTrack = mActiveTracks[i];
8359 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008360 if (activeTrack->isFastTrack()) {
8361 ALOG_ASSERT(fastTrackToRemove == 0);
8362 fastTrackToRemove = activeTrack;
8363 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008364 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008365 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008366 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008367 continue;
8368 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008369
Andy Hung11e74242023-06-26 19:20:57 -07008370 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008371 switch (activeTrackState) {
8372
Andy Hung11e74242023-06-26 19:20:57 -07008373 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008374 mActiveTracks.remove(activeTrack);
Andy Hung11e74242023-06-26 19:20:57 -07008375 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008376 if (activeTrack->isFastTrack()) {
8377 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8378 // Keep a ref on fast track to wait for FastCapture thread to get updated
8379 // state before potential track removal
8380 fastTrackToRemove = activeTrack;
8381 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008382 doBroadcast = true;
8383 size--;
8384 continue;
8385
Andy Hung11e74242023-06-26 19:20:57 -07008386 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008387 sleepUs = 10000;
8388 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008389 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008390 continue;
8391
Andy Hung11e74242023-06-26 19:20:57 -07008392 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008393 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008394 if (mStandby) {
8395 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008396 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008397 mStandby = false;
8398 }
Andy Hung11e74242023-06-26 19:20:57 -07008399 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008400 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008401 break;
8402
Andy Hung11e74242023-06-26 19:20:57 -07008403 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008404 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008405 break;
8406
Andy Hung11e74242023-06-26 19:20:57 -07008407 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8408 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8409 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008410 default:
Andy Hungce685402018-10-05 17:23:27 -07008411 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8412 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008413 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008414
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008415 if (activeTrack->isFastTrack()) {
8416 ALOG_ASSERT(!mFastTrackAvail);
8417 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008418 // if the active fast track is silenced either:
8419 // 1) silence the whole capture from fast capture buffer if this is
8420 // the only active track
8421 // 2) invalidate this track: this will cause the client to reconnect and possibly
8422 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008423 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008424 if (activeTrack->isSilenced()) {
8425 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008426 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008427 } else {
8428 silenceFastCapture = true;
8429 }
8430 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008431 // Invalidate fast tracks if access to audio history is required as this is not
8432 // possible with fast tracks. Once the fast track has been invalidated, no new
8433 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8434 if (mMaxSharedAudioHistoryMs != 0) {
8435 invalidate = true;
8436 }
8437 if (invalidate) {
8438 activeTrack->invalidate();
8439 ALOG_ASSERT(fastTrackToRemove == 0);
8440 fastTrackToRemove = activeTrack;
8441 removeTrack_l(activeTrack);
8442 mActiveTracks.remove(activeTrack);
8443 size--;
8444 continue;
8445 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008446 fastTrack = activeTrack;
8447 }
Eric Laurent33403f02020-05-29 18:35:06 -07008448
8449 activeTracks.add(activeTrack);
8450 i++;
8451
Glenn Kasten9e982352013-08-14 14:39:50 -07008452 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008453
Andy Hung94dfbb42023-09-06 19:41:47 -07008454 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008455
Kevin Rocard069c2712018-03-29 19:09:14 -07008456 updateMetadata_l();
8457
Eric Laurent5c25d562016-07-13 17:17:45 -07008458 if (allStopped) {
8459 standbyIfNotAlreadyInStandby();
8460 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008461 if (doBroadcast) {
Andy Hungb17d24b2023-08-29 14:26:09 -07008462 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008463 }
8464
8465 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008466 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008467 if (sleepUs == 0) {
8468 sleepUs = kRecordThreadSleepUs;
8469 }
8470 continue;
8471 }
8472 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008473
Andy Hung1381a072023-10-20 16:41:18 -07008474 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008475 lockEffectChains_l(effectChains);
Abdelrahman Daimf6a71612024-11-21 08:57:37 -08008476 // We're exiting locked scope with non empty activeTracks, make sure
8477 // that we're not in standby mode which we could have entered if some
8478 // tracks were muted/unmuted.
8479 mStandby = false;
Eric Laurent81784c32012-11-19 14:55:58 -08008480 }
8481
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008482 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008483
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 size_t size = effectChains.size();
8485 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008486 // thread mutex is not locked, but effect chain is locked
8487 effectChains[i]->process_l();
8488 }
8489
Glenn Kasten735f45f2014-08-18 15:51:59 -07008490 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008491 if (mFastCapture != 0) {
8492 FastCaptureStateQueue *sq = mFastCapture->sq();
8493 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008494 bool didModify = false;
8495 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008496 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8497 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8498 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8499 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8500 if (old == -1) {
8501 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8502 }
8503 }
8504 state->mCommand = FastCaptureState::READ_WRITE;
8505#if 0 // FIXME
Andy Hung7535ed92023-07-17 17:05:00 -07008506 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008507 FastThreadDumpState::kSamplingNforLowRamDevice :
8508 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008509#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008510 didModify = true;
8511 }
8512 audio_track_cblk_t *cblkOld = state->mCblk;
8513 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8514 if (cblkNew != cblkOld) {
8515 state->mCblk = cblkNew;
8516 // block until acked if removing a fast track
8517 if (cblkOld != NULL) {
8518 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8519 }
8520 didModify = true;
8521 }
jiabin01c8f562018-07-19 17:47:28 -07008522 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8523 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8524 if (state->mFastPatchRecordBufferProvider != abp) {
8525 state->mFastPatchRecordBufferProvider = abp;
8526 state->mFastPatchRecordFormat = fastTrack == 0 ?
8527 AUDIO_FORMAT_INVALID : fastTrack->format();
8528 didModify = true;
8529 }
Eric Laurent33403f02020-05-29 18:35:06 -07008530 if (state->mSilenceCapture != silenceFastCapture) {
8531 state->mSilenceCapture = silenceFastCapture;
8532 didModify = true;
8533 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008534 sq->end(didModify);
8535 if (didModify) {
8536 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008537#if 0
8538 if (kUseFastCapture == FastCapture_Dynamic) {
8539 mNormalSource = mPipeSource;
8540 }
8541#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008542 }
8543 }
8544
Glenn Kasten735f45f2014-08-18 15:51:59 -07008545 // now run the fast track destructor with thread mutex unlocked
8546 fastTrackToRemove.clear();
8547
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008548 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8549 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8550 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8551 // If destination is non-contiguous, first read past the nominal end of buffer, then
8552 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008553
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008554 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008555 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008556 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008557
8558 // If an NBAIO source is present, use it to read the normal capture's data
8559 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008560 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008561
8562 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8563 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8564 // we immediately retry the read() to get data and prevent another overflow.
8565 for (int retries = 0; retries <= 2; ++retries) {
8566 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8567 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8568 framesToRead);
8569 if (framesRead != OVERRUN) break;
8570 }
8571
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008572 const ssize_t availableToRead = mPipeSource->availableToRead();
8573 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008574 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008575 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008576 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8577 "more frames to read than fifo size, %zd > %zu",
8578 availableToRead, mPipeFramesP2);
8579 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8580 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8581 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8582 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008583 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8584 }
8585 if (framesRead < 0) {
8586 status_t status = (status_t) framesRead;
8587 switch (status) {
8588 case OVERRUN:
8589 ALOGW("overrun on read from pipe");
8590 framesRead = 0;
8591 break;
8592 case NEGOTIATE:
8593 ALOGE("re-negotiation is needed");
8594 framesRead = -1; // Will cause an attempt to recover.
8595 break;
8596 default:
8597 ALOGE("unknown error %d on read from pipe", status);
8598 break;
8599 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008600 }
8601 // otherwise use the HAL / AudioStreamIn directly
8602 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008603 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008604 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008605 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008606 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008607 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008608 if (result < 0) {
8609 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008610 } else {
8611 framesRead = bytesRead / mFrameSize;
8612 }
8613 }
8614
Andy Hung446f4df2019-02-21 12:26:41 -08008615 const int64_t lastIoEndNs = systemTime(); // end IO timing
8616
Andy Hung3f0c9022016-01-15 17:49:46 -08008617 // Update server timestamp with server stats
8618 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008619 if (framesRead >= 0) {
8620 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8621 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8622 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008623
8624 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008625 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008626 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008627 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008628 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8629 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8630 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008631 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008632 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8633
8634 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hung94dfbb42023-09-06 19:41:47 -07008635 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008636 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008637 id(), (long long)time, (long long)position);
8638 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8639 position = correctedTimestamp.mFrames;
8640 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008641 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008642 id(), (long long)time, (long long)position);
8643 }
8644
Andy Hung3f0c9022016-01-15 17:49:46 -08008645 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8646 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8647 // Note: In general record buffers should tend to be empty in
8648 // a properly running pipeline.
8649 //
8650 // Also, it is not advantageous to call get_presentation_position during the read
8651 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008652 } else {
8653 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008654 }
8655 }
Andy Hunge6c37112019-02-26 17:38:10 -08008656
8657 // From the timestamp, input read latency is negative output write latency.
8658 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung11e74242023-06-26 19:20:57 -07008659 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008660 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8661 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8662 mLatencyMs.add(latencyMs);
8663 }
8664
Andy Hung3f0c9022016-01-15 17:49:46 -08008665 // Use this to track timestamp information
8666 // ALOGD("%s", mTimestamp.toString().c_str());
8667
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008668 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008669 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008670 // Force input into standby so that it tries to recover at next read attempt
8671 inputStandBy();
8672 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008673 }
8674 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008675 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008676 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008677 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008678 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008679
Andy Hung8946a282018-04-19 20:04:56 -07008680#ifdef TEE_SINK
8681 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8682#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008683 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008684 {
8685 size_t part1 = mRsmpInFramesP2 - rear;
8686 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008687 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008688 (framesRead - part1) * mFrameSize);
8689 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008690 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008691 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008692
8693 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008694
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008695 // loop over each active track
8696 for (size_t i = 0; i < size; i++) {
Andy Hung460e10f2024-06-17 15:42:48 -07008697 if (activeTrack) { // ensure track release is outside lock.
8698 oldActiveTracks.emplace_back(std::move(activeTrack));
8699 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008700 activeTrack = activeTracks[i];
8701
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008702 // skip fast tracks, as those are handled directly by FastCapture
8703 if (activeTrack->isFastTrack()) {
8704 continue;
8705 }
8706
Andy Hung73c02e42015-03-29 01:13:58 -07008707 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008708 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8709
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008710 enum {
8711 OVERRUN_UNKNOWN,
8712 OVERRUN_TRUE,
8713 OVERRUN_FALSE
8714 } overrun = OVERRUN_UNKNOWN;
8715
8716 // loop over getNextBuffer to handle circular sink
8717 for (;;) {
8718
Andy Hung11e74242023-06-26 19:20:57 -07008719 activeTrack->sinkBuffer().frameCount = ~0;
8720 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8721 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008722 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8723
Andy Hung73c02e42015-03-29 01:13:58 -07008724 // check available frames and handle overrun conditions
8725 // if the record track isn't draining fast enough.
8726 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008727 size_t framesIn;
Andy Hung11e74242023-06-26 19:20:57 -07008728 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008729 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008730 overrun = OVERRUN_TRUE;
8731 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008732 if (framesOut == 0 || framesIn == 0) {
8733 break;
8734 }
8735
Andy Hung6770c6f2015-04-07 13:43:36 -07008736 // Don't allow framesOut to be larger than what is possible with resampling
8737 // from framesIn.
8738 // This isn't strictly necessary but helps limit buffer resizing in
8739 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008740 if (audio_is_linear_pcm(activeTrack->format())) {
8741 framesOut = min(framesOut,
8742 destinationFramesPossible(
8743 framesIn, mSampleRate, activeTrack->sampleRate()));
8744 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008745
8746 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008747 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008748 // straight from RecordThread buffer to RecordTrack buffer.
8749 AudioBufferProvider::Buffer buffer;
8750 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008751 const status_t getNextBufferStatus =
Andy Hung11e74242023-06-26 19:20:57 -07008752 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008753 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008754 ALOGV_IF(buffer.frameCount != framesOut,
8755 "%s() read less than expected (%zu vs %zu)",
8756 __func__, buffer.frameCount, framesOut);
8757 framesOut = buffer.frameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008758 memcpy(activeTrack->sinkBuffer().raw,
8759 buffer.raw, buffer.frameCount * mFrameSize);
8760 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008761 } else {
8762 framesOut = 0;
8763 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008764 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008765 }
8766 } else {
8767 // process frames from the RecordThread buffer provider to the RecordTrack
8768 // buffer
Andy Hung11e74242023-06-26 19:20:57 -07008769 framesOut = activeTrack->recordBufferConverter()->convert(
8770 activeTrack->sinkBuffer().raw,
8771 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008772 framesOut);
8773 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008774
8775 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8776 overrun = OVERRUN_FALSE;
8777 }
8778
Andy Hung93bb5732023-05-04 21:16:34 -07008779 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8780 const ssize_t framesToDrop =
Andy Hung11e74242023-06-26 19:20:57 -07008781 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008782 if (framesToDrop == 0) {
8783 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008784 if (framesOut > 0) {
Andy Hung11e74242023-06-26 19:20:57 -07008785 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008786 // Sanitize before releasing if the track has no access to the source data
8787 // An idle UID receives silence from non virtual devices until active
8788 if (activeTrack->isSilenced()) {
Andy Hung11e74242023-06-26 19:20:57 -07008789 memset(activeTrack->sinkBuffer().raw,
8790 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008791 }
Andy Hung11e74242023-06-26 19:20:57 -07008792 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008793 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008794 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008795 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008796 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008797 }
8798 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008799
8800 switch (overrun) {
8801 case OVERRUN_TRUE:
8802 // client isn't retrieving buffers fast enough
8803 if (!activeTrack->setOverflow()) {
8804 nsecs_t now = systemTime();
8805 // FIXME should lastWarning per track?
8806 if ((now - lastWarning) > kWarningThrottleNs) {
8807 ALOGW("RecordThread: buffer overflow");
8808 lastWarning = now;
8809 }
8810 }
8811 break;
8812 case OVERRUN_FALSE:
8813 activeTrack->clearOverflow();
8814 break;
8815 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008816 break;
8817 }
8818
Andy Hung3f0c9022016-01-15 17:49:46 -08008819 // update frame information and push timestamp out
8820 activeTrack->updateTrackFrameInfo(
Andy Hung11e74242023-06-26 19:20:57 -07008821 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008822 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8823 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008824 }
8825
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008826unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008827 // enable changes in effect chain
8828 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008829 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008830 if (audio_has_proportional_frames(mFormat)
8831 && loopCount == lastLoopCountRead + 1) {
8832 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8833 const double jitterMs =
8834 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8835 {framesRead, readPeriodNs},
8836 {0, 0} /* lastTimestamp */, mSampleRate);
8837 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8838
Andy Hungf8635b62023-08-31 16:13:39 -07008839 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008840 mIoJitterMs.add(jitterMs);
8841 mProcessTimeMs.add(processMs);
8842 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008843 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008844 // update timing info.
8845 mLastIoBeginNs = lastIoBeginNs;
8846 mLastIoEndNs = lastIoEndNs;
8847 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008848 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008849 mThreadloopExecutor.process(); // process any remaining deferred actions.
8850 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008851
Glenn Kasten93e471f2013-08-19 08:40:07 -07008852 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008853
8854 {
Andy Hungf8635b62023-08-31 16:13:39 -07008855 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008856 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07008857 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008858 track->invalidate();
8859 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008860 mActiveTracks.clear();
Andy Hungb17d24b2023-08-29 14:26:09 -07008861 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008862 }
8863
8864 releaseWakeLock();
8865
8866 ALOGV("RecordThread %p exiting", this);
8867 return false;
8868}
8869
Andy Hung4b17e882023-07-07 13:47:37 -07008870void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008871{
8872 if (!mStandby) {
8873 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008874 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008875 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008876 mStandby = true;
8877 }
8878}
8879
Andy Hung4b17e882023-07-07 13:47:37 -07008880void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008881{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008882 // Idle the fast capture if it's currently running
8883 if (mFastCapture != 0) {
8884 FastCaptureStateQueue *sq = mFastCapture->sq();
8885 FastCaptureState *state = sq->begin();
8886 if (!(state->mCommand & FastCaptureState::IDLE)) {
8887 state->mCommand = FastCaptureState::COLD_IDLE;
8888 state->mColdFutexAddr = &mFastCaptureFutex;
8889 state->mColdGen++;
8890 mFastCaptureFutex = 0;
8891 sq->end();
8892 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8893 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8894#if 0
8895 if (kUseFastCapture == FastCapture_Dynamic) {
8896 // FIXME
8897 }
8898#endif
8899#ifdef AUDIO_WATCHDOG
8900 // FIXME
8901#endif
8902 } else {
8903 sq->end(false /*didModify*/);
8904 }
8905 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008906 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008907 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008908
8909 // If going into standby, flush the pipe source.
8910 if (mPipeSource.get() != nullptr) {
8911 const ssize_t flushed = mPipeSource->flush();
8912 if (flushed > 0) {
8913 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8914 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8915 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8916 }
8917 }
Eric Laurent81784c32012-11-19 14:55:58 -08008918}
8919
Andy Hungb17d24b2023-08-29 14:26:09 -07008920// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07008921sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008922 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008923 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008924 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008925 audio_format_t format,
8926 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008927 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008928 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008929 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008930 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008931 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008932 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008933 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008934 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008935 audio_port_handle_t portId,
8936 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008937{
Glenn Kasten74935e42013-12-19 08:56:45 -08008938 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008939 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung11e74242023-06-26 19:20:57 -07008940 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008941 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008942 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008943 audio_input_flags_t requestedFlags = *flags;
8944 uint32_t sampleRate;
8945
8946 lStatus = initCheck();
8947 if (lStatus != NO_ERROR) {
8948 ALOGE("createRecordTrack_l() audio driver not initialized");
8949 goto Exit;
8950 }
8951
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008952 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8953 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8954 lStatus = BAD_VALUE;
8955 goto Exit;
8956 }
8957
Eric Laurentec376dc2021-04-08 20:41:22 +02008958 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008959 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008960 lStatus = PERMISSION_DENIED;
8961 goto Exit;
8962 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008963 if (maxSharedAudioHistoryMs < 0
Andy Hung409572b2023-07-19 12:47:35 -07008964 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008965 lStatus = BAD_VALUE;
8966 goto Exit;
8967 }
8968 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008969 if (*pSampleRate == 0) {
8970 *pSampleRate = mSampleRate;
8971 }
8972 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008973
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008974 // special case for FAST flag considered OK if fast capture is present and access to
8975 // audio history is not required
8976 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008977 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8978 }
8979
Eric Laurentf14db3c2017-12-08 14:20:36 -08008980 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008981 if ((*flags & inputFlags) != *flags) {
8982 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8983 " input flags (%08x)",
8984 *flags, inputFlags);
8985 *flags = (audio_input_flags_t)(*flags & inputFlags);
8986 }
Eric Laurent81784c32012-11-19 14:55:58 -08008987
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008988 // client expresses a preference for FAST and no access to audio history,
8989 // but we get the final say
8990 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008991 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008992 // we formerly checked for a callback handler (non-0 tid),
8993 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008994 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008995 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008996 // Frame count is not specified (0), or is less than or equal the pipe depth.
8997 // It is OK to provide a higher capacity than requested.
8998 // We will force it to mPipeFramesP2 below.
8999 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009000 // PCM data
9001 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009002 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009003 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009004 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009005 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009006 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009007 hasFastCapture() &&
9008 // there are sufficient fast track slots available
9009 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009010 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009011 // check compatibility with audio effects.
Andy Hungf8635b62023-08-31 16:13:39 -07009012 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009013 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009014 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009015 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009016 audio_input_flags_t old = *flags;
9017 chain->checkInputFlagCompatibility(flags);
9018 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009019 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9020 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009021 }
9022 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009023 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009024 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9025 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009026 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009027 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9028 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009029 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009030 this, frameCount, mFrameCount, mPipeFramesP2,
9031 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009032 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009033 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009034 }
9035 }
9036
Eric Laurentf14db3c2017-12-08 14:20:36 -08009037 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9038 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9039 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9040 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9041 lStatus = BAD_TYPE;
9042 goto Exit;
9043 }
9044
Glenn Kasten74105912014-07-03 12:28:53 -07009045 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009046 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009047 // fast track: frame count is exactly the pipe depth
9048 frameCount = mPipeFramesP2;
9049 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009050 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009051 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009052 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9053 // or 20 ms if there is a fast capture
9054 // TODO This could be a roundupRatio inline, and const
9055 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9056 * sampleRate + mSampleRate - 1) / mSampleRate;
9057 // minimum number of notification periods is at least kMinNotifications,
9058 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9059 static const size_t kMinNotifications = 3;
9060 static const uint32_t kMinMs = 30;
9061 // TODO This could be a roundupRatio inline
9062 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9063 // TODO This could be a roundupRatio inline
9064 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9065 maxNotificationFrames;
9066 const size_t minFrameCount = maxNotificationFrames *
9067 max(kMinNotifications, minNotificationsByMs);
9068 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009069 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9070 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009071 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009072 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009073 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009074 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009075
Andy Hungb17d24b2023-08-29 14:26:09 -07009076 { // scope for mutex()
Andy Hungf8635b62023-08-31 16:13:39 -07009077 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009078 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009079 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009080 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009081 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009082 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009083 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009084 }
Eric Laurent81784c32012-11-19 14:55:58 -08009085
Andy Hung11e74242023-06-26 19:20:57 -07009086 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009087 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009088 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung11e74242023-06-26 19:20:57 -07009089 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009090 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009091
Glenn Kasten03003332013-08-06 15:40:54 -07009092 lStatus = track->initCheck();
9093 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009094 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009095 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009096 goto Exit;
9097 }
9098 mTracks.add(track);
9099
Eric Laurent05067782016-06-01 18:27:28 -07009100 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009101 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9102 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9103 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009104 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009105 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009106
9107 if (maxSharedAudioHistoryMs != 0) {
9108 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9109 }
Eric Laurent81784c32012-11-19 14:55:58 -08009110 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009111
Eric Laurent81784c32012-11-19 14:55:58 -08009112 lStatus = NO_ERROR;
9113
9114Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009115 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009116 return track;
9117}
9118
Andy Hung4b17e882023-07-07 13:47:37 -07009119status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009120 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009121 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009122{
9123 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9124 sp<ThreadBase> strongMe = this;
9125 status_t status = NO_ERROR;
9126
9127 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009128 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009129 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung11e74242023-06-26 19:20:57 -07009130 recordTrack->synchronizedRecordState().startRecording(
Andy Hung7535ed92023-07-17 17:05:00 -07009131 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009132 event, triggerSession,
9133 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009134 }
9135
9136 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009137 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hungf8635b62023-08-31 16:13:39 -07009138 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009139 if (recordTrack->isInvalid()) {
9140 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009141 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9142 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009143 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009144 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung11e74242023-06-26 19:20:57 -07009145 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009146 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9147 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009148 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung11e74242023-06-26 19:20:57 -07009149 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009150 } else {
Andy Hung11e74242023-06-26 19:20:57 -07009151 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009152 }
9153 return status;
9154 }
9155
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009156 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9157 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9158 // or using a separate command thread
Andy Hung11e74242023-06-26 19:20:57 -07009159 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009160 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009161 if (recordTrack->isExternalTrack()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009162 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009163 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungb17d24b2023-08-29 14:26:09 -07009164 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009165 if (recordTrack->isInvalid()) {
9166 recordTrack->clearSyncStartEvent();
Andy Hung11e74242023-06-26 19:20:57 -07009167 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9168 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009169 // STARTING_2 forces destroy to call stopInput.
9170 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009171 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9172 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009173 }
Andy Hung11e74242023-06-26 19:20:57 -07009174 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009175 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung11e74242023-06-26 19:20:57 -07009176 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009177 // Someone else has changed state, let them take over,
9178 // leave mState in the new state.
9179 recordTrack->clearSyncStartEvent();
9180 return INVALID_OPERATION;
9181 }
9182 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009183 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009184 ALOGW("%s(%d): startInput failed, status %d",
9185 __func__, recordTrack->id(), status);
9186 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9187 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009188 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009189 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009190 return status;
9191 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009192 sendIoConfigEvent_l(
9193 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009194 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009195
9196 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9197
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009198 // Catch up with current buffer indices if thread is already running.
9199 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9200 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9201 // see previously buffered data before it called start(), but with greater risk of overrun.
9202
Andy Hung11e74242023-06-26 19:20:57 -07009203 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009204 if (!recordTrack->isDirect()) {
9205 // clear any converter state as new data will be discontinuous
Andy Hung11e74242023-06-26 19:20:57 -07009206 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009207 }
Andy Hung11e74242023-06-26 19:20:57 -07009208 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009209 // signal thread to start
Andy Hungb17d24b2023-08-29 14:26:09 -07009210 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009211 return status;
9212 }
Eric Laurent81784c32012-11-19 14:55:58 -08009213}
9214
Andy Hung4b17e882023-07-07 13:47:37 -07009215void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009216{
Andy Hung4b17e882023-07-07 13:47:37 -07009217 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009218
9219 if (strongEvent != 0) {
Andy Hungfafbebc2023-06-23 19:27:19 -07009220 sp<IAfTrackBase> ptr =
9221 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9222 if (ptr != nullptr) {
Andy Hungeb6b5f82023-07-14 11:00:08 -07009223 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungfafbebc2023-06-23 19:27:19 -07009224 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009225 }
Eric Laurent81784c32012-11-19 14:55:58 -08009226 }
9227}
9228
Andy Hung4b17e882023-07-07 13:47:37 -07009229bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009230 ALOGV("RecordThread::stop");
Andy Hungb17d24b2023-08-29 14:26:09 -07009231 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009232 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung11e74242023-06-26 19:20:57 -07009233 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009234 return false;
9235 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009236 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung11e74242023-06-26 19:20:57 -07009237 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009238
Andy Hungabfab202019-03-07 19:45:54 -08009239 // NOTE: Waiting here is important to keep stop synchronous.
9240 // This is needed for proper patchRecord peer release.
Andy Hung11e74242023-06-26 19:20:57 -07009241 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungb17d24b2023-08-29 14:26:09 -07009242 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009243 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009244 }
Andy Hungce685402018-10-05 17:23:27 -07009245
Andy Hung11e74242023-06-26 19:20:57 -07009246 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009247 ALOGV("Record stopped OK");
9248 return true;
9249 }
Andy Hungce685402018-10-05 17:23:27 -07009250
9251 // don't handle anything - we've been invalidated or restarted and in a different state
9252 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung11e74242023-06-26 19:20:57 -07009253 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009254 return false;
9255}
9256
Andy Hung4b17e882023-07-07 13:47:37 -07009257bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009258{
9259 return false;
9260}
9261
Andy Hung4b17e882023-07-07 13:47:37 -07009262status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009263{
9264#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9265 if (!isValidSyncEvent(event)) {
9266 return BAD_VALUE;
9267 }
9268
Glenn Kastend848eb42016-03-08 13:42:11 -08009269 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009270 status_t ret = NAME_NOT_FOUND;
9271
Andy Hungf8635b62023-08-31 16:13:39 -07009272 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009273
9274 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009275 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009276 if (eventSession == track->sessionId()) {
9277 (void) track->setSyncEvent(event);
9278 ret = NO_ERROR;
9279 }
9280 }
9281 return ret;
9282#else
9283 return BAD_VALUE;
9284#endif
9285}
9286
Andy Hung4b17e882023-07-07 13:47:37 -07009287status_t RecordThread::getActiveMicrophones(
Andy Hung0c1e11e2023-07-06 20:56:16 -07009288 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009289{
9290 ALOGV("RecordThread::getActiveMicrophones");
Andy Hungf8635b62023-08-31 16:13:39 -07009291 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009292 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009293 return NO_INIT;
9294 }
jiabin9ff780e2018-03-19 18:19:52 -07009295 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9296 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009297}
9298
Andy Hung4b17e882023-07-07 13:47:37 -07009299status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009300 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009301{
Paul McLean12340082019-03-19 09:35:05 -06009302 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hungf8635b62023-08-31 16:13:39 -07009303 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009304 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009305 return NO_INIT;
9306 }
Paul McLean12340082019-03-19 09:35:05 -06009307 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009308}
9309
Andy Hung4b17e882023-07-07 13:47:37 -07009310status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009311{
Paul McLean12340082019-03-19 09:35:05 -06009312 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hungf8635b62023-08-31 16:13:39 -07009313 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009314 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009315 return NO_INIT;
9316 }
Paul McLean12340082019-03-19 09:35:05 -06009317 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009318}
9319
Andy Hung4b17e882023-07-07 13:47:37 -07009320status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009321 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9322 int64_t sharedAudioStartMs) {
Andy Hungf8635b62023-08-31 16:13:39 -07009323 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009324 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9325}
9326
Andy Hung4b17e882023-07-07 13:47:37 -07009327status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009328 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9329 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009330
Eric Laurentec376dc2021-04-08 20:41:22 +02009331 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9332 return BAD_VALUE;
9333 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009334
9335 if (sharedAudioStartMs < 0
9336 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009337 return BAD_VALUE;
9338 }
9339
Eric Laurent2407ce32021-04-26 14:56:03 +02009340 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9341 // As we cannot detect more than one wraparound, only accept values up current write position
9342 // after one wraparound
9343 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9344 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009345 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009346 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9347 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009348 // Bring the start frame position within the input buffer to match the documented
9349 // "best effort" behavior of the API.
9350 if (sharedOffset < 0) {
9351 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009352 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009353 sharedAudioStartFrames =
9354 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009355 }
9356
Eric Laurentec376dc2021-04-08 20:41:22 +02009357 mSharedAudioPackageName = sharedAudioPackageName;
9358 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009359 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009360 } else {
9361 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009362 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009363 }
9364 return NO_ERROR;
9365}
9366
Andy Hung4b17e882023-07-07 13:47:37 -07009367void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009368 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9369 mSharedAudioStartFrames = -1;
9370 mSharedAudioPackageName = "";
9371}
9372
Andy Hung4b17e882023-07-07 13:47:37 -07009373ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009374{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009375 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009376 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009377 }
9378 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009379 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung11e74242023-06-26 19:20:57 -07009380 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009381 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009382 }
9383 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009384 MetadataUpdate change;
9385 change.recordMetadataUpdate = metadata.tracks;
9386 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009387}
9388
Andy Hungb17d24b2023-08-29 14:26:09 -07009389// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -07009390void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009391{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009392 track->terminate();
Andy Hung11e74242023-06-26 19:20:57 -07009393 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009394
Eric Laurent81784c32012-11-19 14:55:58 -08009395 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009396 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009397 removeTrack_l(track);
9398 }
9399}
9400
Andy Hung4b17e882023-07-07 13:47:37 -07009401void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009402{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009403 String8 result;
9404 track->appendDump(result, false /* active */);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009405 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009406
Eric Laurent81784c32012-11-19 14:55:58 -08009407 mTracks.remove(track);
9408 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009409 if (track->isFastTrack()) {
9410 ALOG_ASSERT(!mFastTrackAvail);
9411 mFastTrackAvail = true;
9412 }
Eric Laurent81784c32012-11-19 14:55:58 -08009413}
9414
Andy Hung4b17e882023-07-07 13:47:37 -07009415void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009416{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009417 AudioStreamIn *input = mInput;
9418 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9419 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009420 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009421 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009422 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009423 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009424 }
Andy Hungbfa64962017-06-12 14:43:19 -07009425
9426 if (input != nullptr) {
9427 dprintf(fd, " Hal stream dump:\n");
9428 (void)input->stream->dump(fd);
9429 }
9430
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009431 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009432 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009433
Glenn Kasten2f90c512015-12-02 11:40:09 -08009434 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9435 // while we are dumping it. It may be inconsistent, but it won't mutate!
9436 // This is a large object so we place it on the heap.
9437 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009438 const std::unique_ptr<FastCaptureDumpState> copy =
9439 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009440 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009441}
9442
Andy Hung4b17e882023-07-07 13:47:37 -07009443void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009444{
Eric Laurent81784c32012-11-19 14:55:58 -08009445 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009446 size_t numtracks = mTracks.size();
9447 size_t numactive = mActiveTracks.size();
9448 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009449 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009450 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009451 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009452 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009453 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009454 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009455 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009456 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009457 if (track != 0) {
9458 bool active = mActiveTracks.indexOf(track) >= 0;
9459 if (active) {
9460 numactiveseen++;
9461 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009462 result.append(prefix);
9463 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009464 }
Eric Laurent81784c32012-11-19 14:55:58 -08009465 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009466 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009467 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009468 }
9469
Marco Nelissenb2208842014-02-07 14:00:50 -08009470 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009471 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009472 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009473 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009474 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009475 for (size_t i = 0; i < numactive; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -07009476 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009477 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009478 result.append(prefix);
9479 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009480 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009481 }
Eric Laurent81784c32012-11-19 14:55:58 -08009482
9483 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00009484 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009485}
9486
Andy Hung4b17e882023-07-07 13:47:37 -07009487void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009488{
Andy Hungf8635b62023-08-31 16:13:39 -07009489 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009490 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009491 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009492 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009493 track->setSilenced(silenced);
9494 }
9495 }
9496}
Andy Hung73c02e42015-03-29 01:13:58 -07009497
Andy Hung11e74242023-06-26 19:20:57 -07009498void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009499{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009500 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009501 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009502 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009503 const int32_t rear = recordThread->mRsmpInRear;
9504 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009505 if (mRecordTrack->startFrames() >= 0) {
9506 int32_t startFrames = mRecordTrack->startFrames();
9507 // Accept a recent wraparound of mRsmpInRear
9508 if (startFrames <= rear) {
9509 deltaFrames = rear - startFrames;
9510 } else {
9511 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009512 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009513 // start frame cannot be further in the past than start of resampling buffer
9514 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9515 deltaFrames = recordThread->mRsmpInFrames;
9516 }
9517 }
9518 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009519}
9520
Andy Hung11e74242023-06-26 19:20:57 -07009521void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009522 size_t *framesAvailable, bool *hasOverrun)
9523{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009524 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung4b17e882023-07-07 13:47:37 -07009525 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009526 const int32_t rear = recordThread->mRsmpInRear;
9527 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009528 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009529
9530 size_t framesIn;
9531 bool overrun = false;
9532 if (filled < 0) {
9533 // should not happen, but treat like a massive overrun and re-sync
9534 framesIn = 0;
9535 mRsmpInFront = rear;
9536 overrun = true;
9537 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9538 framesIn = (size_t) filled;
9539 } else {
9540 // client is not keeping up with server, but give it latest data
9541 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009542 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9543 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009544 overrun = true;
9545 }
9546 if (framesAvailable != NULL) {
9547 *framesAvailable = framesIn;
9548 }
9549 if (hasOverrun != NULL) {
9550 *hasOverrun = overrun;
9551 }
9552}
9553
Eric Laurent81784c32012-11-19 14:55:58 -08009554// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009555status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009556 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009557{
Andy Hung0c1e11e2023-07-06 20:56:16 -07009558 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009559 if (threadBase == 0) {
9560 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009561 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009562 return NOT_ENOUGH_DATA;
9563 }
Andy Hung4b17e882023-07-07 13:47:37 -07009564 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009565 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009566 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009567 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009568 // FIXME should not be P2 (don't want to increase latency)
9569 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009570 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009571 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009572
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009573 front &= recordThread->mRsmpInFramesP2 - 1;
9574 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009575 if (part1 > (size_t) filled) {
9576 part1 = filled;
9577 }
9578 size_t ask = buffer->frameCount;
9579 ALOG_ASSERT(ask > 0);
9580 if (part1 > ask) {
9581 part1 = ask;
9582 }
9583 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009584 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009585 buffer->raw = NULL;
9586 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009587 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009588 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009589 }
9590
Andy Hung57446612015-04-19 23:56:46 -07009591 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009592 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009593 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009594 return NO_ERROR;
9595}
9596
9597// AudioBufferProvider interface
Andy Hung11e74242023-06-26 19:20:57 -07009598void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009599 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009600{
Hongwei Wang95e37682019-04-12 11:13:36 -07009601 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009602 if (stepCount == 0) {
9603 return;
9604 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009605 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009606 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009607 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009608 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009609 buffer->frameCount = 0;
9610}
9611
Andy Hung4b17e882023-07-07 13:47:37 -07009612void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009613{
Andy Hungf8635b62023-08-31 16:13:39 -07009614 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009615 checkBtNrec_l();
9616}
9617
Andy Hung4b17e882023-07-07 13:47:37 -07009618void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009619{
9620 // disable AEC and NS if the device is a BT SCO headset supporting those
9621 // pre processings
Andy Hung94dfbb42023-09-06 19:41:47 -07009622 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung7535ed92023-07-17 17:05:00 -07009623 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009624 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9625 for (size_t i = 0; i < mEffectChains.size(); i++) {
9626 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9627 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9628 }
9629 }
9630}
9631
Andy Hung97a893e2015-03-29 01:03:07 -07009632
Andy Hung4b17e882023-07-07 13:47:37 -07009633bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009634 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009635{
9636 bool reconfig = false;
9637
Eric Laurent10351942014-05-08 18:49:52 -07009638 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009639
Eric Laurent10351942014-05-08 18:49:52 -07009640 audio_format_t reqFormat = mFormat;
9641 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009642 // 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 +08009643 [[maybe_unused]] audio_channel_mask_t channelMask =
9644 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009645
9646 AudioParameter param = AudioParameter(keyValuePair);
9647 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009648
9649 // scope for AutoPark extends to end of method
9650 AutoPark<FastCapture> park(mFastCapture);
9651
Eric Laurent10351942014-05-08 18:49:52 -07009652 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9653 // channel count change can be requested. Do we mandate the first client defines the
9654 // HAL sampling rate and channel count or do we allow changes on the fly?
9655 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9656 samplingRate = value;
9657 reconfig = true;
9658 }
9659 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009660 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009661 status = BAD_VALUE;
9662 } else {
9663 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009664 reconfig = true;
9665 }
Eric Laurent10351942014-05-08 18:49:52 -07009666 }
9667 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9668 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009669 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009670 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009671 status = BAD_VALUE;
9672 } else {
9673 channelMask = mask;
9674 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009675 }
Eric Laurent10351942014-05-08 18:49:52 -07009676 }
9677 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9678 // do not accept frame count changes if tracks are open as the track buffer
9679 // size depends on frame count and correct behavior would not be guaranteed
9680 // if frame count is changed after track creation
9681 if (mActiveTracks.size() > 0) {
9682 status = INVALID_OPERATION;
9683 } else {
9684 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009685 }
Eric Laurent10351942014-05-08 18:49:52 -07009686 }
9687 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009688 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009689 }
9690 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9691 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009692 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009693 }
Glenn Kastene198c362013-08-13 09:13:36 -07009694
Eric Laurent10351942014-05-08 18:49:52 -07009695 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009696 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009697 if (status == INVALID_OPERATION) {
9698 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009699 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009700 }
9701 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009702 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009703 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9704 if (mInput->stream->getAudioProperties(&config) == OK &&
9705 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9706 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009707 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009708 status = NO_ERROR;
9709 }
Eric Laurent81784c32012-11-19 14:55:58 -08009710 }
Eric Laurent10351942014-05-08 18:49:52 -07009711 if (status == NO_ERROR) {
9712 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009713 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009714 }
9715 }
Eric Laurent81784c32012-11-19 14:55:58 -08009716 }
Eric Laurent10351942014-05-08 18:49:52 -07009717
Eric Laurent81784c32012-11-19 14:55:58 -08009718 return reconfig;
9719}
9720
Andy Hung4b17e882023-07-07 13:47:37 -07009721String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009722{
Andy Hungf8635b62023-08-31 16:13:39 -07009723 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009724 if (initCheck() == NO_ERROR) {
9725 String8 out_s8;
9726 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9727 return out_s8;
9728 }
Eric Laurent81784c32012-11-19 14:55:58 -08009729 }
Andy Hung920f6572022-10-06 12:09:49 -07009730 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009731}
9732
Andy Hung94dfbb42023-09-06 19:41:47 -07009733void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009734 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009735 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009736 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009737 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009738 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009739 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009740 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9741 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009742 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009743 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009744 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009745 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009746 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009747 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009748 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009749 break;
9750 }
Andy Hung94dfbb42023-09-06 19:41:47 -07009751 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009752}
9753
Andy Hung4b17e882023-07-07 13:47:37 -07009754void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009755{
Dean Wheatley6c009512023-10-23 09:34:14 +11009756 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9757 mSampleRate = audioConfig.sample_rate;
9758 mChannelMask = audioConfig.channel_mask;
9759 if (!audio_is_input_channel(mChannelMask)) {
9760 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9761 }
9762
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009763 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009764
9765 // Get actual HAL format.
9766 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9767 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9768 // Get format from the shim, which will be different than the HAL format
9769 // if recording compressed audio from IEC61937 wrapped sources.
9770 mFormat = audioConfig.format;
9771 if (!audio_is_valid_format(mFormat)) {
9772 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9773 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009774 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009775 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9776 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009777 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009778 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009779 ALOGI("HAL format %#x is not linear pcm", mFormat);
9780 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009781 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009782 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9783 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009784 result = mInput->stream->getBufferSize(&mBufferSize);
9785 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009786 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009787 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9788 "mBufferSize=%zu, mFrameCount=%zu",
9789 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009790
Eric Laurentec376dc2021-04-08 20:41:22 +02009791 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9792 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009793 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009794
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009795 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9796 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009797
9798 audio_input_flags_t flags = mInput->flags;
9799 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9800 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -07009801 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009802 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9803 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9804 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9805 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9806 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9807 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009808}
9809
Andy Hung4b17e882023-07-07 13:47:37 -07009810uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009811{
Andy Hungf8635b62023-08-31 16:13:39 -07009812 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009813 uint32_t result;
9814 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9815 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009816 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009817 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009818}
9819
Andy Hung4b17e882023-07-07 13:47:37 -07009820KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009821{
Glenn Kastend848eb42016-03-08 13:42:11 -08009822 KeyedVector<audio_session_t, bool> ids;
Andy Hungf8635b62023-08-31 16:13:39 -07009823 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009824 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung11e74242023-06-26 19:20:57 -07009825 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009826 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009827 if (ids.indexOfKey(sessionId) < 0) {
9828 ids.add(sessionId, true);
9829 }
9830 }
9831 return ids;
9832}
9833
Andy Hung4b17e882023-07-07 13:47:37 -07009834AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009835{
Andy Hungf8635b62023-08-31 16:13:39 -07009836 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009837 AudioStreamIn *input = mInput;
9838 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009839 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009840 return input;
9841}
9842
Andy Hungb17d24b2023-08-29 14:26:09 -07009843// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung4b17e882023-07-07 13:47:37 -07009844sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009845{
9846 if (mInput == NULL) {
9847 return NULL;
9848 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009849 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009850}
9851
Andy Hung4b17e882023-07-07 13:47:37 -07009852status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009853{
Eric Laurent81784c32012-11-19 14:55:58 -08009854 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009855 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009856 chain->setInBuffer(NULL);
9857 chain->setOutBuffer(NULL);
9858
9859 checkSuspendOnAddEffectChain_l(chain);
9860
Eric Laurent1b928682014-10-02 19:41:47 -07009861 // make sure enabled pre processing effects state is communicated to the HAL as we
9862 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009863 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009864
Eric Laurent81784c32012-11-19 14:55:58 -08009865 mEffectChains.add(chain);
9866
9867 return NO_ERROR;
9868}
9869
Andy Hung4b17e882023-07-07 13:47:37 -07009870size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009871{
9872 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009873
9874 for (size_t i = 0; i < mEffectChains.size(); i++) {
9875 if (chain == mEffectChains[i]) {
9876 mEffectChains.removeAt(i);
9877 break;
9878 }
Eric Laurent81784c32012-11-19 14:55:58 -08009879 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009880 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009881}
9882
Andy Hung4b17e882023-07-07 13:47:37 -07009883status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009884 audio_patch_handle_t *handle)
9885{
9886 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009887
9888 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009889 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009890 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009891 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009892 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009893 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009894 }
9895
Eric Laurentd8365c52017-07-16 15:27:05 -07009896 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009897
9898 // store new source and send to effects
9899 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9900 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009901 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009902 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009903 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009904 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009905
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009906 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009907 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9908 status = hwDevice->createAudioPatch(patch->num_sources,
9909 patch->sources,
9910 patch->num_sinks,
9911 patch->sinks,
9912 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009913 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009914 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9915 patch->sinks[0].ext.mix.usecase.source,
9916 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009917 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009918 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009919
jiabinc52b1ff2019-10-31 17:20:42 -07009920 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009921 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009922 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009923 }
Eric Laurent296fb132015-05-01 11:38:42 -07009924
Andy Hungc2b11cb2020-04-22 09:04:01 -07009925 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009926 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009927 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009928 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009929 // also dispatch to active AudioRecords
9930 for (const auto &track : mActiveTracks) {
9931 track->logEndInterval();
9932 track->logBeginInterval(pathSourcesAsString);
9933 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009934 // Force meteadata update after a route change
9935 mActiveTracks.setHasChanged();
9936
Eric Laurent1c333e22014-05-20 10:48:17 -07009937 return status;
9938}
9939
Andy Hung4b17e882023-07-07 13:47:37 -07009940status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009941{
9942 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009943
jiabinc52b1ff2019-10-31 17:20:42 -07009944 mPatch = audio_patch{};
9945 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009946
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009947 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009948 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9949 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009950 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009951 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009952 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009953 // Force meteadata update after a route change
9954 mActiveTracks.setHasChanged();
9955
Eric Laurent1c333e22014-05-20 10:48:17 -07009956 return status;
9957}
9958
Andy Hung4b17e882023-07-07 13:47:37 -07009959void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009960{
Andy Hungf8635b62023-08-31 16:13:39 -07009961 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009962 mOutDevices = outDevices;
9963 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9964 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009965 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009966 }
9967}
9968
Andy Hung4b17e882023-07-07 13:47:37 -07009969int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009970{
9971 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009972 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009973 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009974 int32_t oldestFront = mRsmpInRear;
9975 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009976 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009977 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009978 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009979 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009980 if (filled > maxFilled) {
9981 oldestFront = front;
9982 maxFilled = filled;
9983 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009984 }
Andy Hung920f6572022-10-06 12:09:49 -07009985 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009986 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9987 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009988 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009989}
9990
Andy Hung4b17e882023-07-07 13:47:37 -07009991void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009992{
9993 if (offset == 0) {
9994 return;
9995 }
9996 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung11e74242023-06-26 19:20:57 -07009997 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009998 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung11e74242023-06-26 19:20:57 -07009999 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010000 }
10001}
10002
Andy Hung4b17e882023-07-07 13:47:37 -070010003void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010004{
10005 // This is the formula for calculating the temporary buffer size.
10006 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10007 // 1 full output buffer, regardless of the alignment of the available input.
10008 // The value is somewhat arbitrary, and could probably be even larger.
10009 // A larger value should allow more old data to be read after a track calls start(),
10010 // without increasing latency.
10011 //
10012 // Note this is independent of the maximum downsampling ratio permitted for capture.
10013 size_t minRsmpInFrames = mFrameCount * 7;
10014
10015 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10016 // capture history available to another client using the same session ID:
10017 // dimension the resampler input buffer accordingly.
10018
10019 // Get oldest client read position: getOldestFront_l() must be called before altering
10020 // mRsmpInRear, or mRsmpInFrames
10021 int32_t previousFront = getOldestFront_l();
10022 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10023 int32_t previousRear = mRsmpInRear;
10024 mRsmpInRear = 0;
10025
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010026 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung4b17e882023-07-07 13:47:37 -070010027 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010028 "resizeInputBuffer_l() called with invalid max shared history %d",
10029 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010030 if (maxSharedAudioHistoryMs != 0) {
10031 // resizeInputBuffer_l should never be called with a non zero shared history if the
10032 // buffer was not already allocated
10033 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10034 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10035 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10036 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010037 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010038 return;
10039 }
10040 mRsmpInFrames = rsmpInFrames;
10041 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010042 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010043 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10044 // initialized
10045 if (mRsmpInFrames < minRsmpInFrames) {
10046 mRsmpInFrames = minRsmpInFrames;
10047 }
10048 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10049
10050 // TODO optimize audio capture buffer sizes ...
10051 // Here we calculate the size of the sliding buffer used as a source
10052 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10053 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10054 // be better to have it derived from the pipe depth in the long term.
10055 // The current value is higher than necessary. However it should not add to latency.
10056
10057 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10058 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10059
10060 void *rsmpInBuffer;
10061 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10062 // if posix_memalign fails, will segv here.
10063 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10064
10065 // Copy audio history if any from old buffer before freeing it
10066 if (previousRear != 0) {
10067 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10068 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10069
10070 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10071 previousFront &= previousRsmpInFramesP2 - 1;
10072 size_t part1 = previousRsmpInFramesP2 - previousFront;
10073 if (part1 > (size_t) unread) {
10074 part1 = unread;
10075 }
10076 if (part1 != 0) {
10077 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10078 part1 * mFrameSize);
10079 mRsmpInRear = part1;
10080 part1 = unread - part1;
10081 if (part1 != 0) {
10082 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10083 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10084 mRsmpInRear += part1;
10085 }
10086 }
10087 // Update front for all clients according to new rear
10088 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10089 } else {
10090 mRsmpInRear = 0;
10091 }
10092 free(mRsmpInBuffer);
10093 mRsmpInBuffer = rsmpInBuffer;
10094}
10095
Andy Hung4b17e882023-07-07 13:47:37 -070010096void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010097{
Andy Hungf8635b62023-08-31 16:13:39 -070010098 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010099 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010100 if (record->getSource()) {
10101 mSource = record->getSource();
10102 }
Eric Laurent83b88082014-06-20 18:31:16 -070010103}
10104
Andy Hung4b17e882023-07-07 13:47:37 -070010105void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010106{
Andy Hungf8635b62023-08-31 16:13:39 -070010107 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010108 if (mSource == record->getSource()) {
10109 mSource = mInput;
10110 }
Eric Laurent83b88082014-06-20 18:31:16 -070010111 destroyTrack_l(record);
10112}
10113
Andy Hung4b17e882023-07-07 13:47:37 -070010114void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010115{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010116 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010117 config->role = AUDIO_PORT_ROLE_SINK;
10118 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10119 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010120 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10121 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10122 config->flags.input = mInput->flags;
10123 }
Eric Laurent83b88082014-06-20 18:31:16 -070010124}
Eric Laurent1c333e22014-05-20 10:48:17 -070010125
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126// ----------------------------------------------------------------------------
10127// Mmap
10128// ----------------------------------------------------------------------------
10129
Andy Hung765de282023-07-07 15:58:48 -070010130// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10131// MmapPlaybackThread or MmapCaptureThread instance.
10132class MmapThreadHandle : public MmapStreamInterface {
10133public:
10134 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10135 ~MmapThreadHandle() override;
10136
10137 // MmapStreamInterface virtuals
10138 status_t createMmapBuffer(int32_t minSizeFrames,
10139 struct audio_mmap_buffer_info* info) final;
10140 status_t getMmapPosition(struct audio_mmap_position* position) final;
10141 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10142 status_t start(const AudioClient& client,
10143 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10144 status_t stop(audio_port_handle_t handle) final;
10145 status_t standby() final;
10146 status_t reportData(const void* buffer, size_t frameCount) final;
10147private:
10148 const sp<IAfMmapThread> mThread;
10149};
10150
10151/* static */
10152sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10153 const sp<IAfMmapThread>& mmapThread) {
10154 return sp<MmapThreadHandle>::make(mmapThread);
10155}
10156
10157MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 : mThread(thread)
10159{
Phil Burk9fabbf82017-08-03 12:02:00 -070010160 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161}
10162
Andy Hung765de282023-07-07 15:58:48 -070010163// MmapStreamInterface could be directly implemented by MmapThread excepting this
10164// special handling on adapter dtor.
10165MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010166{
Phil Burk9fabbf82017-08-03 12:02:00 -070010167 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168}
10169
Andy Hung765de282023-07-07 15:58:48 -070010170status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010171 struct audio_mmap_buffer_info *info)
10172{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010173 return mThread->createMmapBuffer(minSizeFrames, info);
10174}
10175
Andy Hung765de282023-07-07 15:58:48 -070010176status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010177{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 return mThread->getMmapPosition(position);
10179}
10180
Andy Hung765de282023-07-07 15:58:48 -070010181status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010182 int64_t *timeNanos) {
10183 return mThread->getExternalPosition(position, timeNanos);
10184}
10185
Andy Hung765de282023-07-07 15:58:48 -070010186status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010187 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010188{
jiabind1f1cb62020-03-24 11:57:57 -070010189 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010190}
10191
Andy Hung765de282023-07-07 15:58:48 -070010192status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010193{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010194 return mThread->stop(handle);
10195}
10196
Andy Hung765de282023-07-07 15:58:48 -070010197status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010198{
Eric Laurent18b57012017-02-13 16:23:52 -080010199 return mThread->standby();
10200}
10201
Andy Hung765de282023-07-07 15:58:48 -070010202status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10203{
jiabinfc791ee2023-02-15 19:43:40 +000010204 return mThread->reportData(buffer, frameCount);
10205}
10206
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207
Andy Hung4b17e882023-07-07 13:47:37 -070010208MmapThread::MmapThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010209 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010210 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung7535ed92023-07-17 17:05:00 -070010211 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010212 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010213 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010214 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010215 mActiveTracks(&this->mLocalLog),
10216 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10217 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010218{
Eric Laurent18b57012017-02-13 16:23:52 -080010219 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010220 readHalParameters_l();
10221}
10222
Andy Hung4b17e882023-07-07 13:47:37 -070010223void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010224{
10225 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10226}
10227
Andy Hung4b17e882023-07-07 13:47:37 -070010228void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229{
Andy Hung11e74242023-06-26 19:20:57 -070010230 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010231 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010232 {
Andy Hungf8635b62023-08-31 16:13:39 -070010233 audio_utils::lock_guard _l(mutex());
Andy Hung11e74242023-06-26 19:20:57 -070010234 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010235 activeTracks.add(t);
10236 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010237 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010238 }
Andy Hung11e74242023-06-26 19:20:57 -070010239 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010240 stop(t->portId());
10241 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010242 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010244 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 } else {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010246 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010247 }
10248}
10249
10250
Andy Hung160664b2023-09-15 18:19:28 -070010251void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010252 audio_stream_type_t streamType __unused,
10253 audio_session_t sessionId,
10254 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010255 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256 audio_port_handle_t portId)
10257{
10258 mAttr = *attr;
10259 mSessionId = sessionId;
10260 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010261 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010262 mPortId = portId;
10263}
10264
Andy Hung4b17e882023-07-07 13:47:37 -070010265status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266 struct audio_mmap_buffer_info *info)
10267{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010268 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 if (mHalStream == 0) {
10270 return NO_INIT;
10271 }
Eric Laurent18b57012017-02-13 16:23:52 -080010272 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010273 return mHalStream->createMmapBuffer(minSizeFrames, info);
10274}
10275
Andy Hung4b17e882023-07-07 13:47:37 -070010276status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010277{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010278 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279 if (mHalStream == 0) {
10280 return NO_INIT;
10281 }
10282 return mHalStream->getMmapPosition(position);
10283}
10284
Andy Hung4b17e882023-07-07 13:47:37 -070010285status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010286{
Eric Laurentdda206a2022-07-08 17:28:35 +020010287 // The HAL must receive track metadata before starting the stream
10288 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010289 status_t ret = mHalStream->start();
10290 if (ret != NO_ERROR) {
10291 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10292 return ret;
10293 }
Andy Hungcf10d742020-04-28 15:38:24 -070010294 if (mStandby) {
10295 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010296 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010297 mStandby = false;
10298 }
Eric Laurent331679c2018-04-16 17:03:16 -070010299 return NO_ERROR;
10300}
10301
Andy Hung4b17e882023-07-07 13:47:37 -070010302status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010303 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010304 audio_port_handle_t *handle)
10305{
Andy Hungbcfd9e12023-09-19 14:48:41 -070010306 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010307 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010308 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010309 if (mHalStream == 0) {
10310 return NO_INIT;
10311 }
10312
10313 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314
Eric Laurentdda206a2022-07-08 17:28:35 +020010315 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010316 if (*handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010317 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010318 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010319 }
10320
10321 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10322
10323 audio_io_handle_t io = mId;
Andy Hungc3af0112023-07-19 16:56:19 -070010324 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010325 client.attributionSource);
10326
Andy Hungbcfd9e12023-09-19 14:48:41 -070010327 const auto localSessionId = mSessionId;
10328 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010329 if (isOutput()) {
10330 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10331 config.sample_rate = mSampleRate;
10332 config.channel_mask = mChannelMask;
10333 config.format = mFormat;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010334 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010335 audio_output_flags_t flags =
10336 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010337 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010338 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010339 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010340 bool isBitPerfect;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010341 mutex().unlock();
10342 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10343 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010344 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010345 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010346 &config,
10347 flags,
10348 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010349 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010350 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010351 &isSpatialized,
10352 &isBitPerfect);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010353 mutex().lock();
10354 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010355 ALOGD_IF(!secondaryOutputs.empty(),
10356 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010357 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010358 audio_config_base_t config;
10359 config.sample_rate = mSampleRate;
10360 config.channel_mask = mChannelMask;
10361 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010362 audio_port_handle_t deviceId = mDeviceId;
Andy Hungbcfd9e12023-09-19 14:48:41 -070010363 mutex().unlock();
10364 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010365 RECORD_RIID_INVALID,
Andy Hungbcfd9e12023-09-19 14:48:41 -070010366 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010367 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010368 &config,
10369 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10370 &deviceId,
10371 &portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010372 mutex().lock();
10373 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010374 }
10375 // APM should not chose a different input or output stream for the same set of attributes
10376 // and audo configuration
10377 if (ret != NO_ERROR || io != mId) {
10378 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10379 __FUNCTION__, ret, io, mId);
10380 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381 }
10382
10383 if (isOutput()) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010384 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010385 ret = AudioSystem::startOutput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010386 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387 } else {
jiabin09609032022-06-15 19:26:01 +000010388 {
10389 // Add the track record before starting input so that the silent status for the
10390 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010391 setClientSilencedState_l(portId, false /*silenced*/);
10392 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010393 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010394 ret = AudioSystem::startInput(portId);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010395 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396 }
10397
10398 // abort if start is rejected by audio policy manager
10399 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010400 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010401 if (!mActiveTracks.isEmpty()) {
Andy Hungb17d24b2023-08-29 14:26:09 -070010402 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010403 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010404 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010405 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010406 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010407 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010408 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010409 } else {
10410 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411 }
jiabin09609032022-06-15 19:26:01 +000010412 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010413 return PERMISSION_DENIED;
10414 }
10415
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010416 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung11e74242023-06-26 19:20:57 -070010417 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10418 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010419 mChannelMask, mSessionId, isOutput(),
10420 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010421 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010422 if (!isOutput()) {
10423 track->setSilenced_l(isClientSilenced_l(portId));
10424 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010425
Eric Laurent4eb58f12018-12-07 16:41:02 -080010426 if (isOutput()) {
10427 // force volume update when a new track is added
10428 mHalVolFloat = -1.0f;
10429 } else if (!track->isSilenced_l()) {
Andy Hung11e74242023-06-26 19:20:57 -070010430 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010431 if (t->isSilenced_l()
10432 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010433 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010434 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010435 }
10436 }
10437
Eric Laurent6acd1d42017-01-04 14:23:29 -080010438 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010439 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010440 if (chain != 0) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010441 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010442 chain->incTrackCnt();
10443 chain->incActiveTrackCnt();
10444 }
10445
Andy Hungc2b11cb2020-04-22 09:04:01 -070010446 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010448
10449 if (mActiveTracks.size() == 1) {
10450 ret = exitStandby_l();
10451 }
10452
Eric Laurent6acd1d42017-01-04 14:23:29 -080010453 broadcast_l();
10454
Eric Laurentdda206a2022-07-08 17:28:35 +020010455 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456
Eric Laurentdda206a2022-07-08 17:28:35 +020010457 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010458}
10459
Andy Hung4b17e882023-07-07 13:47:37 -070010460status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hungbcfd9e12023-09-19 14:48:41 -070010463 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464
10465 if (mHalStream == 0) {
10466 return NO_INIT;
10467 }
10468
Eric Laurenta54f1282017-07-01 19:39:32 -070010469 if (handle == mPortId) {
Andy Hungbcfd9e12023-09-19 14:48:41 -070010470 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010471 return NO_ERROR;
10472 }
10473
Andy Hung11e74242023-06-26 19:20:57 -070010474 sp<IAfMmapTrack> track;
10475 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010476 if (handle == t->portId()) {
10477 track = t;
10478 break;
10479 }
10480 }
10481 if (track == 0) {
10482 return BAD_VALUE;
10483 }
10484
10485 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010486 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010487
Andy Hungb17d24b2023-08-29 14:26:09 -070010488 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010489 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010490 AudioSystem::stopOutput(track->portId());
10491 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010492 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010493 AudioSystem::stopInput(track->portId());
10494 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 }
Andy Hungb17d24b2023-08-29 14:26:09 -070010496 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497
Andy Hung116bc262023-06-20 18:56:17 -070010498 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499 if (chain != 0) {
10500 chain->decActiveTrackCnt();
10501 chain->decTrackCnt();
10502 }
10503
Eric Laurentdda206a2022-07-08 17:28:35 +020010504 if (mActiveTracks.isEmpty()) {
10505 mHalStream->stop();
10506 }
10507
Eric Laurent6acd1d42017-01-04 14:23:29 -080010508 broadcast_l();
10509
Eric Laurent6acd1d42017-01-04 14:23:29 -080010510 return NO_ERROR;
10511}
10512
Andy Hung4b17e882023-07-07 13:47:37 -070010513status_t MmapThread::standby()
Andy Hungbcfd9e12023-09-19 14:48:41 -070010514NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010515{
10516 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010517 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010518
10519 if (mHalStream == 0) {
10520 return NO_INIT;
10521 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010522 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010523 return INVALID_OPERATION;
10524 }
10525 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010526 if (!mStandby) {
10527 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010528 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010529 mStandby = true;
10530 }
Andy Hungbcfd9e12023-09-19 14:48:41 -070010531 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010532 return NO_ERROR;
10533}
10534
Andy Hung4b17e882023-07-07 13:47:37 -070010535status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010536 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10537 return INVALID_OPERATION;
10538}
10539
Andy Hung4b17e882023-07-07 13:47:37 -070010540void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010541{
10542 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10543 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10544 mFormat = mHALFormat;
10545 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10546 result = mHalStream->getFrameSize(&mFrameSize);
10547 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010548 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10549 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550 result = mHalStream->getBufferSize(&mBufferSize);
10551 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10552 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010553
Andy Hungcf10d742020-04-28 15:38:24 -070010554 // TODO: make a readHalParameters call?
10555 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010556 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung409572b2023-07-19 12:47:35 -070010557 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010558 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10559 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10560 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10561 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10562 /*
10563 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10564 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10565 (int32_t)mHapticChannelMask)
10566 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10567 (int32_t)mHapticChannelCount)
10568 */
10569 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung409572b2023-07-19 12:47:35 -070010570 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010571 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10572 (int32_t)mFrameCount) // sic - added HAL
10573 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010574}
10575
Andy Hung4b17e882023-07-07 13:47:37 -070010576bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577{
Andy Hung94dfbb42023-09-06 19:41:47 -070010578 {
10579 audio_utils::unique_lock _l(mutex());
10580 checkSilentMode_l();
10581 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582
10583 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10584
10585 while (!exitPending())
10586 {
Andy Hung116bc262023-06-20 18:56:17 -070010587 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588
Andy Hung13850be2019-03-14 11:33:09 -070010589 { // under Thread lock
Andy Hungb17d24b2023-08-29 14:26:09 -070010590 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010591
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592 if (mSignalPending) {
10593 // A signal was raised while we were unlocked
10594 mSignalPending = false;
10595 } else {
10596 if (mConfigEvents.isEmpty()) {
10597 // we're about to wait, flush the binder command buffer
10598 IPCThreadState::self()->flushCommands();
10599
10600 if (exitPending()) {
10601 break;
10602 }
10603
Eric Laurent6acd1d42017-01-04 14:23:29 -080010604 // wait until we have something to do...
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010605 ALOGV("%s going to sleep", myName.c_str());
Andy Hungb17d24b2023-08-29 14:26:09 -070010606 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010607 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010608
10609 checkSilentMode_l();
10610
10611 continue;
10612 }
10613 }
10614
10615 processConfigEvents_l();
10616
10617 processVolume_l();
10618
10619 checkInvalidTracks_l();
10620
Andy Hung94dfbb42023-09-06 19:41:47 -070010621 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010622
Kevin Rocard069c2712018-03-29 19:09:14 -070010623 updateMetadata_l();
10624
Eric Laurent6acd1d42017-01-04 14:23:29 -080010625 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010626 } // release Thread lock
10627
Eric Laurent6acd1d42017-01-04 14:23:29 -080010628 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010629 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630 }
Andy Hung13850be2019-03-14 11:33:09 -070010631
10632 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633 unlockEffectChains(effectChains);
10634 // Effect chains will be actually deleted here if they were removed from
10635 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010636 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010638 mThreadloopExecutor.process(); // process any remaining deferred actions.
10639 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010640
10641 threadLoop_exit();
10642
10643 if (!mStandby) {
10644 threadLoop_standby();
10645 mStandby = true;
10646 }
10647
Eric Laurent6acd1d42017-01-04 14:23:29 -080010648 ALOGV("Thread %p type %d exiting", this, mType);
10649 return false;
10650}
10651
Andy Hungb17d24b2023-08-29 14:26:09 -070010652// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070010653bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 status_t& status)
10655{
10656 AudioParameter param = AudioParameter(keyValuePair);
10657 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010658 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010659 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010660 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010661 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010662 if (sendToHal) {
10663 status = mHalStream->setParameters(keyValuePair);
10664 } else {
10665 status = NO_ERROR;
10666 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010667
10668 return false;
10669}
10670
Andy Hung4b17e882023-07-07 13:47:37 -070010671String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010672{
Andy Hungf8635b62023-08-31 16:13:39 -070010673 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010674 String8 out_s8;
10675 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10676 return out_s8;
10677 }
Andy Hung920f6572022-10-06 12:09:49 -070010678 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679}
10680
Andy Hung94dfbb42023-09-06 19:41:47 -070010681void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010682 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010683 sp<AudioIoDescriptor> desc;
10684 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010685 switch (event) {
10686 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010687 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010689 isInput = true;
10690 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010692 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010693 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010694 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10695 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 case AUDIO_INPUT_CLOSED:
10698 case AUDIO_OUTPUT_CLOSED:
10699 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010700 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010701 break;
10702 }
Andy Hung94dfbb42023-09-06 19:41:47 -070010703 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704}
10705
Andy Hung4b17e882023-07-07 13:47:37 -070010706status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 audio_patch_handle_t *handle)
Andy Hungb17d24b2023-08-29 14:26:09 -070010708NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709{
10710 status_t status = NO_ERROR;
10711
10712 // store new device and send to effects
10713 audio_devices_t type = AUDIO_DEVICE_NONE;
10714 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010715 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10716 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10717 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010718 if (isOutput()) {
10719 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010720 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10721 && !mAudioHwDev->supportsAudioPatches(),
10722 "Enumerated device type(%#x) must not be used "
10723 "as it does not support audio patches",
10724 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010725 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010726 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10727 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010728 }
10729 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010730 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731 } else {
10732 type = patch->sources[0].ext.device.type;
10733 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010734 numDevices = mPatch.num_sources;
10735 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010736 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737 }
10738
10739 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010740 if (isOutput()) {
10741 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10742 } else {
10743 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10744 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745 }
10746
jiabinc52b1ff2019-10-31 17:20:42 -070010747 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010748 // store new source and send to effects
10749 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10750 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10751 for (size_t i = 0; i < mEffectChains.size(); i++) {
10752 mEffectChains[i]->setAudioSource_l(mAudioSource);
10753 }
10754 }
10755 }
10756
jiabin78b86f22024-02-22 00:39:29 +000010757 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10758 // okay to notify the client earlier before the new patch creation.
10759 if (mDeviceId != deviceId) {
10760 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10761 // The aaudioservice handle the routing changed event asynchronously. In that case,
10762 // it is safe to hold the lock here.
10763 callback->onRoutingChanged(deviceId);
10764 }
10765 }
10766
Eric Laurent6acd1d42017-01-04 14:23:29 -080010767 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010768 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10769 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010770 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010771 audio_port_config port;
10772 std::optional<audio_source_t> source;
10773 if (isOutput()) {
10774 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010775 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010776 port = patch->sources[0];
10777 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010778 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010779 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780 *handle = AUDIO_PATCH_HANDLE_NONE;
10781 }
10782
jiabinc52b1ff2019-10-31 17:20:42 -070010783 if (numDevices == 0 || mDeviceId != deviceId) {
10784 if (isOutput()) {
10785 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10786 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010787 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010788 } else {
10789 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10790 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10791 }
jiabinc52b1ff2019-10-31 17:20:42 -070010792 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010793 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010794 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010795 // Force meteadata update after a route change
10796 mActiveTracks.setHasChanged();
10797
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798 return status;
10799}
10800
Andy Hung4b17e882023-07-07 13:47:37 -070010801status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010802{
10803 status_t status = NO_ERROR;
10804
jiabinc52b1ff2019-10-31 17:20:42 -070010805 mPatch = audio_patch{};
10806 mOutDeviceTypeAddrs.clear();
10807 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010808
10809 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10810 supportsAudioPatches : false;
10811
10812 if (supportsAudioPatches) {
10813 status = mHalDevice->releaseAudioPatch(handle);
10814 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010815 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010816 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010817 // Force meteadata update after a route change
10818 mActiveTracks.setHasChanged();
10819
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820 return status;
10821}
10822
Andy Hung4b17e882023-07-07 13:47:37 -070010823void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hungbcfd9e12023-09-19 14:48:41 -070010824NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010825{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010826 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827 if (isOutput()) {
10828 config->role = AUDIO_PORT_ROLE_SOURCE;
10829 config->ext.mix.hw_module = mAudioHwDev->handle();
10830 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10831 } else {
10832 config->role = AUDIO_PORT_ROLE_SINK;
10833 config->ext.mix.hw_module = mAudioHwDev->handle();
10834 config->ext.mix.usecase.source = mAudioSource;
10835 }
10836}
10837
Andy Hung4b17e882023-07-07 13:47:37 -070010838status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839{
10840 audio_session_t session = chain->sessionId();
10841
10842 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10843 // Attach all tracks with same session ID to this chain.
10844 // indicate all active tracks in the chain
Andy Hung11e74242023-06-26 19:20:57 -070010845 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010846 if (session == track->sessionId()) {
10847 chain->incTrackCnt();
10848 chain->incActiveTrackCnt();
10849 }
10850 }
10851
10852 chain->setThread(this);
10853 chain->setInBuffer(nullptr);
10854 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010855 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856
10857 mEffectChains.add(chain);
10858 checkSuspendOnAddEffectChain_l(chain);
10859 return NO_ERROR;
10860}
10861
Andy Hung4b17e882023-07-07 13:47:37 -070010862size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010863{
10864 audio_session_t session = chain->sessionId();
10865
10866 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10867
10868 for (size_t i = 0; i < mEffectChains.size(); i++) {
10869 if (chain == mEffectChains[i]) {
10870 mEffectChains.removeAt(i);
10871 // detach all active tracks from the chain
10872 // detach all tracks with same session ID from this chain
Andy Hung11e74242023-06-26 19:20:57 -070010873 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010874 if (session == track->sessionId()) {
10875 chain->decActiveTrackCnt();
10876 chain->decTrackCnt();
10877 }
10878 }
10879 break;
10880 }
10881 }
10882 return mEffectChains.size();
10883}
10884
Andy Hung4b17e882023-07-07 13:47:37 -070010885void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886{
10887 mHalStream->standby();
10888}
10889
Andy Hung4b17e882023-07-07 13:47:37 -070010890void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010891{
Phil Burk7dce7282017-09-27 13:51:41 -070010892 // Do not call callback->onTearDown() because it is redundant for thread exit
10893 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010894}
10895
Andy Hung4b17e882023-07-07 13:47:37 -070010896status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010897{
10898 return BAD_VALUE;
10899}
10900
Andy Hung4b17e882023-07-07 13:47:37 -070010901bool MmapThread::isValidSyncEvent(
10902 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010903{
10904 return false;
10905}
10906
Andy Hung4b17e882023-07-07 13:47:37 -070010907status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010908 const effect_descriptor_t *desc, audio_session_t sessionId)
10909{
10910 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010911 if (audio_is_global_session(sessionId)) {
10912 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010913 desc->name, mThreadName);
10914 return BAD_VALUE;
10915 }
10916
10917 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10918 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10919 desc->name);
10920 return BAD_VALUE;
10921 }
10922 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010923 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10924 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010925 return BAD_VALUE;
10926 }
10927
10928 // Only allow effects without processing load or latency
10929 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10930 return BAD_VALUE;
10931 }
10932
Andy Hung116bc262023-06-20 18:56:17 -070010933 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010934 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10935 return BAD_VALUE;
10936 }
10937
Eric Laurent6acd1d42017-01-04 14:23:29 -080010938 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010939}
10940
Andy Hung4b17e882023-07-07 13:47:37 -070010941void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942{
Andy Hung11e74242023-06-26 19:20:57 -070010943 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010944 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010945 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10946 // The aaudioservice handle the routing changed event asynchronously. In that case,
10947 // it is safe to hold the lock here.
10948 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10949 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010950 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10951 mNoCallbackWarningCount++;
10952 }
10953 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954 }
10955 }
10956}
10957
Andy Hung4b17e882023-07-07 13:47:37 -070010958void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010960 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10961 mAttr.content_type, mAttr.usage, mAttr.source);
10962 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010963 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010964 dprintf(fd, " No active clients\n");
10965 }
10966}
10967
Andy Hung4b17e882023-07-07 13:47:37 -070010968void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010970 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010971 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010972 dprintf(fd, " %zu Tracks\n", numtracks);
10973 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010975 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010976 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010977 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung11e74242023-06-26 19:20:57 -070010978 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010979 result.append(prefix);
10980 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010981 }
10982 } else {
10983 dprintf(fd, "\n");
10984 }
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +000010985 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010986}
10987
Andy Hung4b17e882023-07-07 13:47:37 -070010988/* static */
10989sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070010990 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070010991 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070010992 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070010993}
10994
10995MmapPlaybackThread::MmapPlaybackThread(
Andy Hung7535ed92023-07-17 17:05:00 -070010996 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010997 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070010998 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010999 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011000 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011001{
11002 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11003 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung7535ed92023-07-17 17:05:00 -070011004 mMasterVolume = afThreadCallback->masterVolume_l();
11005 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent19611512023-07-03 18:14:07 +020011006
11007 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11008 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11009 mStreamTypes[stream].volume = 0.0f;
11010 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11011 }
11012 // Audio patch and call assistant volume are always max
11013 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11014 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11015 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11016 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
11017
Eric Laurent6acd1d42017-01-04 14:23:29 -080011018 if (mAudioHwDev) {
11019 if (mAudioHwDev->canSetMasterVolume()) {
11020 mMasterVolume = 1.0;
11021 }
11022
11023 if (mAudioHwDev->canSetMasterMute()) {
11024 mMasterMute = false;
11025 }
11026 }
11027}
11028
Andy Hung4b17e882023-07-07 13:47:37 -070011029void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011030 audio_stream_type_t streamType,
11031 audio_session_t sessionId,
11032 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011033 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011034 audio_port_handle_t portId)
11035{
Andy Hung160664b2023-09-15 18:19:28 -070011036 audio_utils::lock_guard l(mutex());
11037 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011038 mStreamType = streamType;
11039}
11040
Andy Hung4b17e882023-07-07 13:47:37 -070011041AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011042{
Andy Hungf8635b62023-08-31 16:13:39 -070011043 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011044 AudioStreamOut *output = mOutput;
11045 mOutput = NULL;
11046 return output;
11047}
11048
Andy Hung4b17e882023-07-07 13:47:37 -070011049void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011050{
Andy Hungf8635b62023-08-31 16:13:39 -070011051 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011052 // Don't apply master volume in SW if our HAL can do it for us.
11053 if (mAudioHwDev &&
11054 mAudioHwDev->canSetMasterVolume()) {
11055 mMasterVolume = 1.0;
11056 } else {
11057 mMasterVolume = value;
11058 }
11059}
11060
Andy Hung4b17e882023-07-07 13:47:37 -070011061void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011062{
Andy Hungf8635b62023-08-31 16:13:39 -070011063 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011064 // Don't apply master mute in SW if our HAL can do it for us.
11065 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11066 mMasterMute = false;
11067 } else {
11068 mMasterMute = muted;
11069 }
11070}
11071
Andy Hung4b17e882023-07-07 13:47:37 -070011072void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011073{
Andy Hungf8635b62023-08-31 16:13:39 -070011074 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011075 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011076 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077 broadcast_l();
11078 }
11079}
11080
Andy Hung4b17e882023-07-07 13:47:37 -070011081float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011082{
Andy Hungf8635b62023-08-31 16:13:39 -070011083 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011084 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011085}
11086
Andy Hung4b17e882023-07-07 13:47:37 -070011087void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011088{
Andy Hungf8635b62023-08-31 16:13:39 -070011089 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020011090 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011091 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092 broadcast_l();
11093 }
11094}
11095
Andy Hung4b17e882023-07-07 13:47:37 -070011096void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011097{
Andy Hungf8635b62023-08-31 16:13:39 -070011098 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011099 if (streamType == mStreamType) {
Andy Hung11e74242023-06-26 19:20:57 -070011100 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011101 track->invalidate();
11102 }
11103 broadcast_l();
11104 }
11105}
11106
Andy Hung4b17e882023-07-07 13:47:37 -070011107void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011108{
Andy Hungf8635b62023-08-31 16:13:39 -070011109 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011110 bool trackMatch = false;
Andy Hung11e74242023-06-26 19:20:57 -070011111 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011112 if (portIds.find(track->portId()) != portIds.end()) {
11113 track->invalidate();
11114 trackMatch = true;
11115 portIds.erase(track->portId());
11116 }
11117 if (portIds.empty()) {
11118 break;
11119 }
11120 }
11121 if (trackMatch) {
11122 broadcast_l();
11123 }
11124}
11125
Andy Hung4b17e882023-07-07 13:47:37 -070011126void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011127NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011128{
11129 float volume;
11130
Eric Laurent19611512023-07-03 18:14:07 +020011131 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011132 volume = 0;
11133 } else {
Eric Laurent19611512023-07-03 18:14:07 +020011134 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011135 }
11136
11137 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011138 // Convert volumes from float to 8.24
11139 uint32_t vol = (uint32_t)(volume * (1 << 24));
11140
11141 // Delegate volume control to effect in track effect chain if needed
11142 // only one effect chain can be present on DirectOutputThread, so if
11143 // there is one, the track is connected to it
11144 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011145 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011146 volume = (float)vol / (1 << 24);
11147 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011148 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011149 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11150 mHalVolFloat = volume; // HW volume control worked, so update value.
11151 mNoCallbackWarningCount = 0;
11152 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011153 sp<MmapStreamCallback> callback = mCallback.promote();
11154 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011155 mHalVolFloat = volume; // SW volume control worked, so update value.
11156 mNoCallbackWarningCount = 0;
Andy Hungb17d24b2023-08-29 14:26:09 -070011157 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011158 callback->onVolumeChanged(volume);
Andy Hungb17d24b2023-08-29 14:26:09 -070011159 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011160 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011161 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11162 ALOGW("Could not set MMAP stream volume: no volume callback!");
11163 mNoCallbackWarningCount++;
11164 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011165 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011166 }
Andy Hung11e74242023-06-26 19:20:57 -070011167 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011168 track->setMetadataHasChanged();
Andy Hung7535ed92023-07-17 17:05:00 -070011169 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011170 /*muteState=*/{mMasterMute,
Eric Laurent19611512023-07-03 18:14:07 +020011171 streamVolume_l() == 0.f,
11172 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011173 // TODO(b/241533526): adjust logic to include mute from AppOps
11174 false /*muteFromPlaybackRestricted*/,
11175 false /*muteFromClientVolume*/,
11176 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011177 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011178 }
11179}
11180
Andy Hung4b17e882023-07-07 13:47:37 -070011181ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011182{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011183 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011184 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011185 }
11186 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011187 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011188 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011189 playback_track_metadata_v7_t trackMetadata;
11190 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011191 .usage = track->attributes().usage,
11192 .content_type = track->attributes().content_type,
11193 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011194 };
11195 trackMetadata.channel_mask = track->channelMask(),
11196 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11197 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011198 }
11199 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011200
11201 MetadataUpdate change;
11202 change.playbackMetadataUpdate = metadata.tracks;
11203 return change;
11204};
Kevin Rocard069c2712018-03-29 19:09:14 -070011205
Andy Hung4b17e882023-07-07 13:47:37 -070011206void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011207{
11208 if (!mMasterMute) {
11209 char value[PROPERTY_VALUE_MAX];
11210 if (property_get("ro.audio.silent", value, "0") > 0) {
11211 char *endptr;
11212 unsigned long ul = strtoul(value, &endptr, 0);
11213 if (*endptr == '\0' && ul != 0) {
Andy Hung6fb26892024-02-20 16:32:57 -080011214 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011215 // The setprop command will not allow a property to be changed after
11216 // the first time it is set, so we don't have to worry about un-muting.
11217 setMasterMute_l(true);
11218 }
11219 }
11220 }
11221}
11222
Andy Hung4b17e882023-07-07 13:47:37 -070011223void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011224{
11225 MmapThread::toAudioPortConfig(config);
11226 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11227 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11228 config->flags.output = mOutput->flags;
11229 }
11230}
11231
Andy Hung4b17e882023-07-07 13:47:37 -070011232status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung3e4c8742023-06-29 21:19:25 -070011233 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011234{
11235 if (mOutput == nullptr) {
11236 return NO_INIT;
11237 }
11238 struct timespec timestamp;
11239 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11240 if (status == NO_ERROR) {
11241 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11242 }
11243 return status;
11244}
11245
Andy Hung4b17e882023-07-07 13:47:37 -070011246status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011247 // Send to MelProcessor for sound dose measurement.
11248 auto processor = mMelProcessor.load();
11249 if (processor) {
11250 processor->process(buffer, frameCount * mFrameSize);
11251 }
11252
jiabinfc791ee2023-02-15 19:43:40 +000011253 return NO_ERROR;
11254}
11255
Andy Hungb17d24b2023-08-29 14:26:09 -070011256// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011257void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011258 const sp<audio_utils::MelProcessor>& processor)
11259{
11260 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011261 mMelProcessor.store(processor);
11262 if (processor) {
11263 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011264 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011265
11266 // no need to update output format for MMapPlaybackThread since it is
11267 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011268}
11269
Andy Hungb17d24b2023-08-29 14:26:09 -070011270// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung4b17e882023-07-07 13:47:37 -070011271void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011272{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011273 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11274 auto melProcessor = mMelProcessor.load();
11275 if (melProcessor != nullptr) {
11276 melProcessor->pause();
11277 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011278}
11279
Andy Hung4b17e882023-07-07 13:47:37 -070011280void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011281{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011282 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011283
Glenn Kastend3bb6452016-12-05 18:14:37 -080011284 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent19611512023-07-03 18:14:07 +020011285 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011286 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11287}
11288
Andy Hung4b17e882023-07-07 13:47:37 -070011289/* static */
11290sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung7535ed92023-07-17 17:05:00 -070011291 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung4b17e882023-07-07 13:47:37 -070011292 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011293 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011294}
11295
11296MmapCaptureThread::MmapCaptureThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011297 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011298 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011299 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011300 mInput(input)
11301{
11302 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11303 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11304}
11305
Andy Hung4b17e882023-07-07 13:47:37 -070011306status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011307{
Phil Burkf054fc32018-12-06 09:45:59 -080011308 {
11309 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011310 if (mInput != nullptr && mInput->stream != nullptr) {
11311 mInput->stream->setGain(1.0f);
11312 }
11313 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011314 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011315}
11316
Andy Hung4b17e882023-07-07 13:47:37 -070011317AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011318{
Andy Hungf8635b62023-08-31 16:13:39 -070011319 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011320 AudioStreamIn *input = mInput;
11321 mInput = NULL;
11322 return input;
11323}
Kevin Rocard069c2712018-03-29 19:09:14 -070011324
Andy Hung4b17e882023-07-07 13:47:37 -070011325void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011326{
11327 bool changed = false;
11328 bool silenced = false;
11329
11330 sp<MmapStreamCallback> callback = mCallback.promote();
11331 if (callback == 0) {
11332 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11333 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11334 mNoCallbackWarningCount++;
11335 }
11336 }
11337
11338 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11339 // track is silenced and unmute otherwise
11340 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11341 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11342 changed = true;
11343 silenced = mActiveTracks[i]->isSilenced_l();
11344 }
11345 }
11346
11347 if (changed) {
11348 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11349 }
11350}
11351
Andy Hung4b17e882023-07-07 13:47:37 -070011352ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011353{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011354 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011355 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011356 }
11357 StreamInHalInterface::SinkMetadata metadata;
Andy Hung11e74242023-06-26 19:20:57 -070011358 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011359 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011360 record_track_metadata_v7_t trackMetadata;
11361 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011362 .source = track->attributes().source,
11363 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011364 };
11365 trackMetadata.channel_mask = track->channelMask(),
11366 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11367 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011368 }
11369 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011370 MetadataUpdate change;
11371 change.recordMetadataUpdate = metadata.tracks;
11372 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011373}
11374
Andy Hung4b17e882023-07-07 13:47:37 -070011375void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011376{
Andy Hungf8635b62023-08-31 16:13:39 -070011377 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011378 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011379 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011380 mActiveTracks[i]->setSilenced_l(silenced);
11381 broadcast_l();
11382 }
11383 }
jiabin09609032022-06-15 19:26:01 +000011384 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011385}
11386
Andy Hung4b17e882023-07-07 13:47:37 -070011387void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011388{
11389 MmapThread::toAudioPortConfig(config);
11390 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11391 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11392 config->flags.input = mInput->flags;
11393 }
11394}
11395
Andy Hung4b17e882023-07-07 13:47:37 -070011396status_t MmapCaptureThread::getExternalPosition(
Andy Hung3e4c8742023-06-29 21:19:25 -070011397 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011398{
11399 if (mInput == nullptr) {
11400 return NO_INIT;
11401 }
11402 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11403}
11404
jiabinc658e452022-10-21 20:52:21 +000011405// ----------------------------------------------------------------------------
11406
Andy Hung4b17e882023-07-07 13:47:37 -070011407/* static */
11408sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung7535ed92023-07-17 17:05:00 -070011409 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung4b17e882023-07-07 13:47:37 -070011410 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung7535ed92023-07-17 17:05:00 -070011411 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung4b17e882023-07-07 13:47:37 -070011412}
11413
Andy Hung7535ed92023-07-17 17:05:00 -070011414BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011415 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung7535ed92023-07-17 17:05:00 -070011416 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011417
Andy Hung4b17e882023-07-07 13:47:37 -070011418PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung11e74242023-06-26 19:20:57 -070011419 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011420 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11421 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011422 float volumeLeft = 1.0f;
11423 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011424 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11425 bitPerfectTrack != nullptr) {
11426 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011427 mAudioMixer->setParameter(
11428 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11429 mAudioMixer->setParameter(
11430 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11431 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011432 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011433 mIsBitPerfect = true;
11434 } else {
11435 mIsBitPerfect = false;
11436 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11437 // active.
11438 for (const auto& track : mActiveTracks) {
11439 const int trackId = track->id();
11440 mAudioMixer->setParameter(
11441 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11442 }
11443 }
jiabin76d94692022-12-15 21:51:21 +000011444 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11445 mVolumeLeft = volumeLeft;
11446 mVolumeRight = volumeRight;
11447 setVolumeForOutput_l(volumeLeft, volumeRight);
11448 }
jiabinc658e452022-10-21 20:52:21 +000011449 return result;
11450}
11451
Andy Hung4b17e882023-07-07 13:47:37 -070011452void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011453 MixerThread::threadLoop_mix();
11454 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11455}
11456
jiabin220eea12024-05-17 17:55:20 +000011457void BitPerfectThread::setTracksInternalMute(
11458 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11459 for (auto& track : mTracks) {
11460 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11461 track->setInternalMute(it->second);
11462 tracksInternalMute->erase(it);
11463 }
11464 }
11465}
11466
11467sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11468 if (com::android::media::audioserver::
11469 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11470 sp<IAfTrack> bitPerfectTrack = nullptr;
11471 bool allOtherTracksMuted = true;
11472 // Return the bit perfect track if all other tracks are muted
11473 for (const auto& track : mActiveTracks) {
11474 if (track->isBitPerfect()) {
11475 bitPerfectTrack = track;
11476 } else if (track->getFinalVolume() != 0.f) {
11477 allOtherTracksMuted = false;
11478 if (bitPerfectTrack != nullptr) {
11479 break;
11480 }
11481 }
11482 }
11483 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11484 } else {
11485 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11486 return mActiveTracks[0];
11487 }
11488 }
11489 return nullptr;
11490}
11491
Glenn Kasten63238ef2015-03-02 15:50:29 -080011492} // namespace android