blob: f9f6b40be323f4ef6fe2e0b1757533c0f9ae8ff7 [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 Hung25a80ac2023-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>
36#ifdef DEBUG_CPU_USAGE
37#include <audio_utils/Statistics.h>
38#include <cpustats/ThreadCpuUsage.h>
39#endif
40#include <audio_utils/channels.h>
41#include <audio_utils/format.h>
42#include <audio_utils/minifloat.h>
43#include <audio_utils/mono_blend.h>
44#include <audio_utils/primitives.h>
45#include <audio_utils/safe_math.h>
46#include <audiomanager/AudioManager.h>
47#include <binder/IPCThreadState.h>
48#include <binder/IServiceManager.h>
49#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010050#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070051#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080052#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070053#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070054#include <media/AudioContainers.h>
55#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070056#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070057#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070058#ifdef ADD_BATTERY_DATA
59#include <media/IMediaPlayerService.h>
60#include <media/IMediaDeathNotifier.h>
61#endif
62#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080063#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070064#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070065#include <media/audiohal/EffectsFactoryHalInterface.h>
66#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070067#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080068#include <media/nbaio/AudioStreamOutSink.h>
69#include <media/nbaio/MonoPipe.h>
70#include <media/nbaio/MonoPipeReader.h>
71#include <media/nbaio/Pipe.h>
72#include <media/nbaio/PipeReader.h>
73#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080074#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070075#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070076#include <mediautils/SchedulingPolicyService.h>
77#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070078#include <powermanager/PowerManager.h>
79#include <private/android_filesystem_config.h>
80#include <private/media/AudioTrackShared.h>
81#include <system/audio_effects/effect_aec.h>
82#include <system/audio_effects/effect_downmix.h>
83#include <system/audio_effects/effect_ns.h>
84#include <system/audio_effects/effect_spatializer.h>
85#include <utils/Log.h>
86#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080087
Andy Hung25a80ac2023-07-19 12:47:35 -070088#include <fcntl.h>
89#include <linux/futex.h>
90#include <math.h>
91#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080092#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070093#include <sstream>
94#include <string>
95#include <sys/stat.h>
96#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080097
Eric Laurent81784c32012-11-19 14:55:58 -080098// ----------------------------------------------------------------------------
99
100// Note: the following macro is used for extremely verbose logging message. In
101// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
102// 0; but one side effect of this is to turn all LOGV's as well. Some messages
103// are so verbose that we want to suppress them even when we have ALOG_ASSERT
104// turned on. Do not uncomment the #def below unless you really know what you
105// are doing and want to see all of the extremely verbose messages.
106//#define VERY_VERY_VERBOSE_LOGGING
107#ifdef VERY_VERY_VERBOSE_LOGGING
108#define ALOGVV ALOGV
109#else
110#define ALOGVV(a...) do { } while(0)
111#endif
112
Andy Hung6770c6f2015-04-07 13:43:36 -0700113// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700114#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116template <typename T>
117static inline T min(const T& a, const T& b)
118{
119 return a < b ? a : b;
120}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700121
Eric Laurent81784c32012-11-19 14:55:58 -0800122namespace android {
123
Andy Hungee58e4a2023-07-07 13:47:37 -0700124using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700125using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000126using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700127
Andy Hung25a80ac2023-07-19 12:47:35 -0700128// Keep in sync with java definition in media/java/android/media/AudioRecord.java
129static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// retry counts for buffer fill timeout
132// 50 * ~20msecs = 1 second
133static const int8_t kMaxTrackRetries = 50;
134static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700135
Eric Laurent81784c32012-11-19 14:55:58 -0800136// allow less retry attempts on direct output thread.
137// direct outputs can be a scarce resource in audio hardware and should
138// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700139// Notes:
140// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
141// in case the data write is bursty for the AudioTrack. The application
142// should endeavor to write at least once every kMaxTrackRetriesDirectMs
143// to prevent an underrun situation. If the data is bursty, then
144// the application can also throttle the data sent to be even.
145// 2) For compressed audio data, any data present in the AudioTrack buffer
146// will be sent and reset the retry count. This delivers data as
147// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
148// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
149// of data to be available, then any remaining data is delivered.
150// This is required to ensure the last bit of data is delivered before underrun.
151//
152// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
153// or the size of the HAL period for proportional / linear PCM tracks.
154static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800155
156// don't warn about blocked writes or record buffer overflows more often than this
157static const nsecs_t kWarningThrottleNs = seconds(5);
158
159// RecordThread loop sleep time upon application overrun or audio HAL read error
160static const int kRecordThreadSleepUs = 5000;
161
Eric Laurent10351942014-05-08 18:49:52 -0700162// maximum time to wait in sendConfigEvent_l() for a status to be received
163static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800164
165// minimum sleep time for the mixer thread loop when tracks are active but in underrun
166static const uint32_t kMinThreadSleepTimeUs = 5000;
167// maximum divider applied to the active sleep time in the mixer thread loop
168static const uint32_t kMaxThreadSleepTimeShift = 2;
169
Andy Hung09a50072014-02-27 14:30:47 -0800170// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800172static const uint32_t kMinNormalSinkBufferSizeMs = 20;
173// maximum normal sink buffer size
174static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800175
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700176// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
177// FIXME This should be based on experimentally observed scheduling jitter
178static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
179
Eric Laurent972a1732013-09-04 09:42:59 -0700180// Offloaded output thread standby delay: allows track transition without going to standby
181static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
182
Eric Laurent51716182016-02-29 18:00:56 -0800183// Direct output thread minimum sleep time in idle or active(underrun) state
184static const nsecs_t kDirectMinSleepTimeUs = 10000;
185
Brian Lindahl65e90012022-07-27 18:01:07 +0200186// Minimum amount of time between checking to see if the timestamp is advancing
187// for underrun detection. If we check too frequently, we may not detect a
188// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800189static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200190
Glenn Kasten1b291842016-07-18 14:55:21 -0700191// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
192// balance between power consumption and latency, and allows threads to be scheduled reliably
193// by the CFS scheduler.
194// FIXME Express other hardcoded references to 20ms with references to this constant and move
195// it appropriately.
196#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800197
Eric Laurent81784c32012-11-19 14:55:58 -0800198// Whether to use fast mixer
199static const enum {
200 FastMixer_Never, // never initialize or use: for debugging only
201 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
202 // normal mixer multiplier is 1
203 FastMixer_Static, // initialize if needed, then use all the time if initialized,
204 // multiplier is calculated based on min & max normal mixer buffer size
205 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
206 // multiplier is calculated based on min & max normal mixer buffer size
207 // FIXME for FastMixer_Dynamic:
208 // Supporting this option will require fixing HALs that can't handle large writes.
209 // For example, one HAL implementation returns an error from a large write,
210 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
211 // We could either fix the HAL implementations, or provide a wrapper that breaks
212 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
213} kUseFastMixer = FastMixer_Static;
214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700215// Whether to use fast capture
216static const enum {
217 FastCapture_Never, // never initialize or use: for debugging only
218 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
219 FastCapture_Static, // initialize if needed, then use all the time if initialized
220} kUseFastCapture = FastCapture_Static;
221
Eric Laurent81784c32012-11-19 14:55:58 -0800222// Priorities for requestPriority
223static const int kPriorityAudioApp = 2;
224static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000226// Request real-time priority for PlaybackThread in ARC
227static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800228
Glenn Kastenea38ee72016-04-18 11:08:01 -0700229// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
230// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
231// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700232
233// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800234static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800235
Glenn Kasten03490092014-05-27 12:30:54 -0700236// The minimum and maximum allowed values
237static const int kFastTrackMultiplierMin = 1;
238static const int kFastTrackMultiplierMax = 2;
239
240// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
241static int sFastTrackMultiplier = kFastTrackMultiplier;
242
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700243// See Thread::readOnlyHeap().
244// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
245// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
246// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700247static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700248
Andy Hung25a80ac2023-07-19 12:47:35 -0700249static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700250
251static nsecs_t getStandbyTimeInNanos() {
252 static nsecs_t standbyTimeInNanos = []() {
253 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
254 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
255 ALOGI("%s: Using %d ms as standby time", __func__, ms);
256 return milliseconds(ms);
257 }();
258 return standbyTimeInNanos;
259}
260
Andy Hung81994d62023-07-20 21:44:14 -0700261// Set kEnableExtendedChannels to true to enable greater than stereo output
262// for the MixerThread and device sink. Number of channels allowed is
263// FCC_2 <= channels <= FCC_LIMIT.
264constexpr bool kEnableExtendedChannels = true;
265
266// Returns true if channel mask is permitted for the PCM sink in the MixerThread
267/* static */
268bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
269 switch (audio_channel_mask_get_representation(channelMask)) {
270 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
271 // Haptic channel mask is only applicable for channel position mask.
272 const uint32_t channelCount = audio_channel_count_from_out_mask(
273 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
274 const uint32_t maxChannelCount = kEnableExtendedChannels
275 ? FCC_LIMIT : FCC_2;
276 if (channelCount < FCC_2 // mono is not supported at this time
277 || channelCount > maxChannelCount) {
278 return false;
279 }
280 // check that channelMask is the "canonical" one we expect for the channelCount.
281 return audio_channel_position_mask_is_out_canonical(channelMask);
282 }
283 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
284 if (kEnableExtendedChannels) {
285 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
286 if (channelCount >= FCC_2 // mono is not supported at this time
287 && channelCount <= FCC_LIMIT) {
288 return true;
289 }
290 }
291 return false;
292 default:
293 return false;
294 }
295}
296
297// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
298constexpr bool kEnableExtendedPrecision = true;
299
300// Returns true if format is permitted for the PCM sink in the MixerThread
301/* static */
302bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
303 switch (format) {
304 case AUDIO_FORMAT_PCM_16_BIT:
305 return true;
306 case AUDIO_FORMAT_PCM_FLOAT:
307 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
308 case AUDIO_FORMAT_PCM_32_BIT:
309 case AUDIO_FORMAT_PCM_8_24_BIT:
310 return kEnableExtendedPrecision;
311 default:
312 return false;
313 }
314}
315
Eric Laurent81784c32012-11-19 14:55:58 -0800316// ----------------------------------------------------------------------------
317
Andy Hung25a80ac2023-07-19 12:47:35 -0700318// formatToString() needs to be exact for MediaMetrics purposes.
319// Do not use media/TypeConverter.h toString().
320/* static */
321std::string IAfThreadBase::formatToString(audio_format_t format) {
322 std::string result;
323 FormatConverter::toString(format, result);
324 return result;
325}
326
Andy Hungb68f5eb2019-12-03 16:49:17 -0800327// TODO: move all toString helpers to audio.h
328// under #ifdef __cplusplus #endif
329static std::string patchSinksToString(const struct audio_patch *patch)
330{
331 std::stringstream ss;
332 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700333 if (i > 0) {
334 ss << "|";
335 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800336 ss << "(" << toString(patch->sinks[i].ext.device.type)
337 << ", " << patch->sinks[i].ext.device.address << ")";
338 }
339 return ss.str();
340}
341
342static std::string patchSourcesToString(const struct audio_patch *patch)
343{
344 std::stringstream ss;
345 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700346 if (i > 0) {
347 ss << "|";
348 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800349 ss << "(" << toString(patch->sources[i].ext.device.type)
350 << ", " << patch->sources[i].ext.device.address << ")";
351 }
352 return ss.str();
353}
354
Andy Hung4bd53e72022-11-17 17:21:45 -0800355static std::string toString(audio_latency_mode_t mode) {
356 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000357 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
358 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800359}
360
361// Could be made a template, but other toString overloads for std::vector are confused.
362static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
363 std::string s("{ ");
364 for (const auto& e : elements) {
365 s.append(toString(e));
366 s.append(" ");
367 }
368 s.append("}");
369 return s;
370}
371
Glenn Kasten03490092014-05-27 12:30:54 -0700372static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
373
374static void sFastTrackMultiplierInit()
375{
376 char value[PROPERTY_VALUE_MAX];
377 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
378 char *endptr;
379 unsigned long ul = strtoul(value, &endptr, 0);
380 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
381 sFastTrackMultiplier = (int) ul;
382 }
383 }
384}
385
386// ----------------------------------------------------------------------------
387
Eric Laurent81784c32012-11-19 14:55:58 -0800388#ifdef ADD_BATTERY_DATA
389// To collect the amplifier usage
390static void addBatteryData(uint32_t params) {
391 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
392 if (service == NULL) {
393 // it already logged
394 return;
395 }
396
397 service->addBatteryData(params);
398}
399#endif
400
Andy Hung3f0c9022016-01-15 17:49:46 -0800401// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
402struct {
403 // call when you acquire a partial wakelock
404 void acquire(const sp<IBinder> &wakeLockToken) {
405 pthread_mutex_lock(&mLock);
406 if (wakeLockToken.get() == nullptr) {
407 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
408 } else {
409 if (mCount == 0) {
410 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
411 }
412 ++mCount;
413 }
414 pthread_mutex_unlock(&mLock);
415 }
416
417 // call when you release a partial wakelock.
418 void release(const sp<IBinder> &wakeLockToken) {
419 if (wakeLockToken.get() == nullptr) {
420 return;
421 }
422 pthread_mutex_lock(&mLock);
423 if (--mCount < 0) {
424 ALOGE("negative wakelock count");
425 mCount = 0;
426 }
427 pthread_mutex_unlock(&mLock);
428 }
429
430 // retrieves the boottime timebase offset from monotonic.
431 int64_t getBoottimeOffset() {
432 pthread_mutex_lock(&mLock);
433 int64_t boottimeOffset = mBoottimeOffset;
434 pthread_mutex_unlock(&mLock);
435 return boottimeOffset;
436 }
437
438 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
439 // and the selected timebase.
440 // Currently only TIMEBASE_BOOTTIME is allowed.
441 //
442 // This only needs to be called upon acquiring the first partial wakelock
443 // after all other partial wakelocks are released.
444 //
445 // We do an empirical measurement of the offset rather than parsing
446 // /proc/timer_list since the latter is not a formal kernel ABI.
447 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
448 int clockbase;
449 switch (timebase) {
450 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
451 clockbase = SYSTEM_TIME_BOOTTIME;
452 break;
453 default:
454 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
455 break;
456 }
457 // try three times to get the clock offset, choose the one
458 // with the minimum gap in measurements.
459 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700460 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800461 for (int i = 0; i < tries; ++i) {
462 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
463 const nsecs_t tbase = systemTime(clockbase);
464 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
465 const nsecs_t gap = tmono2 - tmono;
466 if (i == 0 || gap < bestGap) {
467 bestGap = gap;
468 measured = tbase - ((tmono + tmono2) >> 1);
469 }
470 }
471
472 // to avoid micro-adjusting, we don't change the timebase
473 // unless it is significantly different.
474 //
475 // Assumption: It probably takes more than toleranceNs to
476 // suspend and resume the device.
477 static int64_t toleranceNs = 10000; // 10 us
478 if (llabs(*offset - measured) > toleranceNs) {
479 ALOGV("Adjusting timebase offset old: %lld new: %lld",
480 (long long)*offset, (long long)measured);
481 *offset = measured;
482 }
483 }
484
485 pthread_mutex_t mLock;
486 int32_t mCount;
487 int64_t mBoottimeOffset;
488} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800489
490// ----------------------------------------------------------------------------
491// CPU Stats
492// ----------------------------------------------------------------------------
493
494class CpuStats {
495public:
496 CpuStats();
497 void sample(const String8 &title);
498#ifdef DEBUG_CPU_USAGE
499private:
500 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700501 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800502
Andy Hung16698b82018-08-01 10:48:38 -0700503 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800504
505 int mCpuNum; // thread's current CPU number
506 int mCpukHz; // frequency of thread's current CPU in kHz
507#endif
508};
509
510CpuStats::CpuStats()
511#ifdef DEBUG_CPU_USAGE
512 : mCpuNum(-1), mCpukHz(-1)
513#endif
514{
515}
516
Glenn Kasten0f11b512014-01-31 16:18:54 -0800517void CpuStats::sample(const String8 &title
518#ifndef DEBUG_CPU_USAGE
519 __unused
520#endif
521 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800522#ifdef DEBUG_CPU_USAGE
523 // get current thread's delta CPU time in wall clock ns
524 double wcNs;
525 bool valid = mCpuUsage.sampleAndEnable(wcNs);
526
527 // record sample for wall clock statistics
528 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700529 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800530 }
531
532 // get the current CPU number
533 int cpuNum = sched_getcpu();
534
535 // get the current CPU frequency in kHz
536 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
537
538 // check if either CPU number or frequency changed
539 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
540 mCpuNum = cpuNum;
541 mCpukHz = cpukHz;
542 // ignore sample for purposes of cycles
543 valid = false;
544 }
545
546 // if no change in CPU number or frequency, then record sample for cycle statistics
547 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700548 const double cycles = wcNs * cpukHz * 0.000001;
549 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800550 }
551
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800553 // mCpuUsage.elapsed() is expensive, so don't call it every loop
554 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700555 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800556 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700557 const double perLoop = elapsed / (double) n;
558 const double perLoop100 = perLoop * 0.01;
559 const double perLoop1k = perLoop * 0.001;
560 const double mean = mWcStats.getMean();
561 const double stddev = mWcStats.getStdDev();
562 const double minimum = mWcStats.getMin();
563 const double maximum = mWcStats.getMax();
564 const double meanCycles = mHzStats.getMean();
565 const double stddevCycles = mHzStats.getStdDev();
566 const double minCycles = mHzStats.getMin();
567 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800568 mCpuUsage.resetElapsed();
569 mWcStats.reset();
570 mHzStats.reset();
571 ALOGD("CPU usage for %s over past %.1f secs\n"
572 " (%u mixer loops at %.1f mean ms per loop):\n"
573 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
574 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
575 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000576 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800577 elapsed * .000000001, n, perLoop * .000001,
578 mean * .001,
579 stddev * .001,
580 minimum * .001,
581 maximum * .001,
582 mean / perLoop100,
583 stddev / perLoop100,
584 minimum / perLoop100,
585 maximum / perLoop100,
586 meanCycles / perLoop1k,
587 stddevCycles / perLoop1k,
588 minCycles / perLoop1k,
589 maxCycles / perLoop1k);
590
591 }
592 }
593#endif
594};
595
596// ----------------------------------------------------------------------------
597// ThreadBase
598// ----------------------------------------------------------------------------
599
Glenn Kasten97b7b752014-09-28 13:04:24 -0700600// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700601const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700602{
603 switch (type) {
604 case MIXER:
605 return "MIXER";
606 case DIRECT:
607 return "DIRECT";
608 case DUPLICATING:
609 return "DUPLICATING";
610 case RECORD:
611 return "RECORD";
612 case OFFLOAD:
613 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700614 case MMAP_PLAYBACK:
615 return "MMAP_PLAYBACK";
616 case MMAP_CAPTURE:
617 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200618 case SPATIALIZER:
619 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000620 case BIT_PERFECT:
621 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700622 default:
623 return "unknown";
624 }
625}
626
Andy Hung583043b2023-07-17 17:05:00 -0700627ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700628 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800629 : Thread(false /*canCallJava*/),
630 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700631 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700632 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
633 isOut),
634 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700635 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800636 // are set by PlaybackThread::readOutputParameters_l() or
637 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700638 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700639 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700640 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800641 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700642 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800643 mSystemReady(systemReady),
644 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800645{
Andy Hungcf10d742020-04-28 15:38:24 -0700646 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700647 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800648}
649
Andy Hungee58e4a2023-07-07 13:47:37 -0700650ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800651{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700652 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700653 mConfigEvents.clear();
654
Eric Laurent81784c32012-11-19 14:55:58 -0800655 // do not lock the mutex in destructor
656 releaseWakeLock_l();
657 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800658 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800659 binder->unlinkToDeath(mDeathRecipient);
660 }
Andy Hungd0979812019-02-21 15:51:44 -0800661
662 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800663}
664
Andy Hungee58e4a2023-07-07 13:47:37 -0700665status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700666{
667 status_t status = initCheck();
668 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800669 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700670 } else {
671 ALOGE("No working audio driver found.");
672 }
673 return status;
674}
675
Andy Hungee58e4a2023-07-07 13:47:37 -0700676void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800677{
678 ALOGV("ThreadBase::exit");
679 // do any cleanup required for exit to succeed
680 preExit();
681 {
682 // This lock prevents the following race in thread (uniprocessor for illustration):
683 // if (!exitPending()) {
684 // // context switch from here to exit()
685 // // exit() calls requestExit(), what exitPending() observes
686 // // exit() calls signal(), which is dropped since no waiters
687 // // context switch back from exit() to here
688 // mWaitWorkCV.wait(...);
689 // // now thread is hung
690 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700691 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800692 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700693 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800694 }
695 // When Thread::requestExitAndWait is made virtual and this method is renamed to
696 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
697 requestExitAndWait();
698}
699
Andy Hungee58e4a2023-07-07 13:47:37 -0700700status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800701{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000702 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700703 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800704
Eric Laurent10351942014-05-08 18:49:52 -0700705 return sendSetParameterConfigEvent_l(keyValuePairs);
706}
707
708// sendConfigEvent_l() must be called with ThreadBase::mLock held
709// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700710status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700711NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700712{
713 status_t status = NO_ERROR;
714
Eric Laurent72e3f392015-05-20 14:43:50 -0700715 if (event->mRequiresSystemReady && !mSystemReady) {
716 event->mWaitStatus = false;
717 mPendingConfigEvents.add(event);
718 return status;
719 }
Eric Laurent10351942014-05-08 18:49:52 -0700720 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700721 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700722 mWaitWorkCV.notify_one();
723 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700724 {
Andy Hungc5007f82023-08-29 14:26:09 -0700725 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700726 while (event->mWaitStatus) {
Andy Hungc5007f82023-08-29 14:26:09 -0700727 if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
728 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700729 event->mStatus = TIMED_OUT;
730 event->mWaitStatus = false;
731 }
732 }
733 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800734 }
Andy Hungc5007f82023-08-29 14:26:09 -0700735 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800736 return status;
737}
738
Andy Hungee58e4a2023-07-07 13:47:37 -0700739void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700740 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800741{
Andy Hung972bec12023-08-31 16:13:39 -0700742 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700743 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800744}
745
Andy Hungc5007f82023-08-29 14:26:09 -0700746// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700747void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700748 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800749{
Andy Hungd0979812019-02-21 15:51:44 -0800750 // The audio statistics history is exponentially weighted to forget events
751 // about five or more seconds in the past. In order to have
752 // crisper statistics for mediametrics, we reset the statistics on
753 // an IoConfigEvent, to reflect different properties for a new device.
754 mIoJitterMs.reset();
755 mLatencyMs.reset();
756 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000757 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100758 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800759
Eric Laurent09f1ed22019-04-24 17:45:17 -0700760 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700761 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800762}
763
Andy Hungee58e4a2023-07-07 13:47:37 -0700764void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700765{
Andy Hung972bec12023-08-31 16:13:39 -0700766 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800767 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700768}
769
Andy Hungc5007f82023-08-29 14:26:09 -0700770// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700771void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800772 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800773{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800774 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700775 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800776}
777
Andy Hungc5007f82023-08-29 14:26:09 -0700778// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700779status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800780{
Andy Hung2ddee192015-12-18 17:34:44 -0800781 sp<ConfigEvent> configEvent;
782 AudioParameter param(keyValuePair);
783 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700784 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800785 setMasterMono_l(value != 0);
786 if (param.size() == 1) {
787 return NO_ERROR; // should be a solo parameter - we don't pass down
788 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700789 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800790 configEvent = new SetParameterConfigEvent(param.toString());
791 } else {
792 configEvent = new SetParameterConfigEvent(keyValuePair);
793 }
Eric Laurent10351942014-05-08 18:49:52 -0700794 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700795}
796
Andy Hungee58e4a2023-07-07 13:47:37 -0700797status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700798 const struct audio_patch *patch,
799 audio_patch_handle_t *handle)
800{
Andy Hung972bec12023-08-31 16:13:39 -0700801 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700802 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
803 status_t status = sendConfigEvent_l(configEvent);
804 if (status == NO_ERROR) {
805 CreateAudioPatchConfigEventData *data =
806 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
807 *handle = data->mHandle;
808 }
809 return status;
810}
811
Andy Hungee58e4a2023-07-07 13:47:37 -0700812status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 const audio_patch_handle_t handle)
814{
Andy Hung972bec12023-08-31 16:13:39 -0700815 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700816 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
817 return sendConfigEvent_l(configEvent);
818}
819
Andy Hungee58e4a2023-07-07 13:47:37 -0700820status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700821 const DeviceDescriptorBaseVector& outDevices)
822{
823 if (type() != RECORD) {
824 // The update out device operation is only for record thread.
825 return INVALID_OPERATION;
826 }
Andy Hung972bec12023-08-31 16:13:39 -0700827 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700828 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
829 return sendConfigEvent_l(configEvent);
830}
831
Andy Hungee58e4a2023-07-07 13:47:37 -0700832void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200833{
834 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
835 sp<ConfigEvent> configEvent =
836 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
837 sendConfigEvent_l(configEvent);
838}
Eric Laurent1c333e22014-05-20 10:48:17 -0700839
Andy Hungee58e4a2023-07-07 13:47:37 -0700840void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200841{
Andy Hung972bec12023-08-31 16:13:39 -0700842 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200843 sendCheckOutputStageEffectsEvent_l();
844}
845
Andy Hungee58e4a2023-07-07 13:47:37 -0700846void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200847{
848 sp<ConfigEvent> configEvent =
849 (ConfigEvent *)new CheckOutputStageEffectsEvent();
850 sendConfigEvent_l(configEvent);
851}
852
Andy Hungee58e4a2023-07-07 13:47:37 -0700853void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200854{
855 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
856 sendConfigEvent_l(configEvent);
857}
858
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700859// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700860void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700861{
Eric Laurent10351942014-05-08 18:49:52 -0700862 bool configChanged = false;
863
Eric Laurent81784c32012-11-19 14:55:58 -0800864 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700865 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700866 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800867 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700868 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700869 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700870 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
871 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800872 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700873 true /*asynchronous*/);
874 if (err != 0) {
875 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700876 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700877 }
878 } break;
879 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700880 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700881 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700882 } break;
883 case CFG_EVENT_SET_PARAMETER: {
884 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
885 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
886 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700887 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000888 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700889 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700890 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700891 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700892 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700893 CreateAudioPatchConfigEventData *data =
894 (CreateAudioPatchConfigEventData *)event->mData.get();
895 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700896 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200897 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700898 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
899 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
900 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700901 } break;
902 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700903 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700904 ReleaseAudioPatchConfigEventData *data =
905 (ReleaseAudioPatchConfigEventData *)event->mData.get();
906 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700907 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200908 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700909 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
910 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
911 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
912 } break;
913 case CFG_EVENT_UPDATE_OUT_DEVICE: {
914 UpdateOutDevicesConfigEventData *data =
915 (UpdateOutDevicesConfigEventData *)event->mData.get();
916 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700917 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200918 case CFG_EVENT_RESIZE_BUFFER: {
919 ResizeBufferConfigEventData *data =
920 (ResizeBufferConfigEventData *)event->mData.get();
921 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
922 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200923
924 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
925 setCheckOutputStageEffects();
926 } break;
927
Eric Laurent68a40a82022-05-03 18:15:04 +0200928 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
929 onHalLatencyModesChanged_l();
930 } break;
931
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700932 default:
Eric Laurent10351942014-05-08 18:49:52 -0700933 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700934 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800935 }
Eric Laurent10351942014-05-08 18:49:52 -0700936 {
Andy Hung972bec12023-08-31 16:13:39 -0700937 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700938 if (event->mWaitStatus) {
939 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700940 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700941 }
942 }
943 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
944 }
945
946 if (configChanged) {
947 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800948 }
Eric Laurent81784c32012-11-19 14:55:58 -0800949}
950
Marco Nelissenb2208842014-02-07 14:00:50 -0800951String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
952 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700953 const audio_channel_representation_t representation =
954 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700955
956 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800957 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700958 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
959 if (output) {
960 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
961 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
962 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700963 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700964 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
965 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
966 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
967 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
968 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
969 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
973 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700976 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
977 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
978 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
980 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
981 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
982 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700983 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700984 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
985 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700986 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
987 } else {
988 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
989 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
990 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
991 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
992 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
994 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
995 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
996 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
997 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
998 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
999 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001000 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1001 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1002 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001003 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001004 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1005 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001006 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1007 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1008 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1009 }
1010 const int len = s.length();
1011 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001012 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001013 s.unlockBuffer(len - 2); // remove trailing ", "
1014 }
1015 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001016 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001017 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1018 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1019 return s;
1020 default:
1021 s.appendFormat("unknown mask, representation:%d bits:%#x",
1022 representation, audio_channel_mask_get_bits(mask));
1023 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001024 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001025}
1026
Andy Hungee58e4a2023-07-07 13:47:37 -07001027void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001028NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001029{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001030 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1031 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1032
Andy Hungc5007f82023-08-29 14:26:09 -07001033 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001034 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001035 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001036 }
1037
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001038 dumpBase_l(fd, args);
1039 dumpInternals_l(fd, args);
1040 dumpTracks_l(fd, args);
1041 dumpEffectChains_l(fd, args);
1042
1043 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001044 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001045 }
1046
1047 dprintf(fd, " Local log:\n");
1048 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001049
1050 // --all does the statistics
1051 bool dumpAll = false;
1052 for (const auto &arg : args) {
1053 if (arg == String16("--all")) {
1054 dumpAll = true;
1055 }
1056 }
1057 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001058 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001059 if (!sched.empty()) {
1060 (void)write(fd, sched.c_str(), sched.size());
1061 }
1062 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001063}
1064
Andy Hungee58e4a2023-07-07 13:47:37 -07001065void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001066{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001067 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001068 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001069 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001070 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001071 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1072 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001073 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001074 dprintf(fd, " Channel count: %u\n", mChannelCount);
1075 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001076 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001077 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1078 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001079 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001080 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001081 size_t numConfig = mConfigEvents.size();
1082 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001083 const size_t SIZE = 256;
1084 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001085 for (size_t i = 0; i < numConfig; i++) {
1086 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001088 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001090 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001091 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001092 }
Andy Hung293558a2017-03-21 12:19:20 -07001093 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001094 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001095 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001096 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001097 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001098 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001099
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001100 // Dump timestamp statistics for the Thread types that support it.
1101 if (mType == RECORD
1102 || mType == MIXER
1103 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001104 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001105 || mType == OFFLOAD
1106 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001107 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001108 dprintf(fd, " Timestamp corrected: %s\n",
1109 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001110 }
1111
Andy Hung446f4df2019-02-21 12:26:41 -08001112 if (mLastIoBeginNs > 0) { // MMAP may not set this
1113 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1114 isOutput() ? "write" : "read",
1115 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1116 }
1117
1118 if (mProcessTimeMs.getN() > 0) {
1119 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1120 }
1121
1122 if (mIoJitterMs.getN() > 0) {
1123 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1124 isOutput() ? "write" : "read",
1125 mIoJitterMs.toString().c_str());
1126 }
1127
Andy Hunge6c37112019-02-26 17:38:10 -08001128 if (mLatencyMs.getN() > 0) {
1129 dprintf(fd, " Threadloop %s latency stats: %s\n",
1130 isOutput() ? "write" : "read",
1131 mLatencyMs.toString().c_str());
1132 }
Robert Wu06db0a32021-08-10 19:05:34 +00001133
1134 if (mMonopipePipeDepthStats.getN() > 0) {
1135 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1136 isOutput() ? "write" : "read",
1137 mMonopipePipeDepthStats.toString().c_str());
1138 }
Eric Laurent81784c32012-11-19 14:55:58 -08001139}
1140
Andy Hungee58e4a2023-07-07 13:47:37 -07001141void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001142{
1143 const size_t SIZE = 256;
1144 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001145
Marco Nelissenb2208842014-02-07 14:00:50 -08001146 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001147 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001148 write(fd, buffer, strlen(buffer));
1149
Marco Nelissenb2208842014-02-07 14:00:50 -08001150 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001151 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001152 if (chain != 0) {
1153 chain->dump(fd, args);
1154 }
1155 }
1156}
1157
Andy Hungee58e4a2023-07-07 13:47:37 -07001158void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001159{
Andy Hung972bec12023-08-31 16:13:39 -07001160 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001161 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001162}
1163
Andy Hungee58e4a2023-07-07 13:47:37 -07001164String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001165{
1166 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001167 case MIXER:
1168 return String16("AudioMix");
1169 case DIRECT:
1170 return String16("AudioDirectOut");
1171 case DUPLICATING:
1172 return String16("AudioDup");
1173 case RECORD:
1174 return String16("AudioIn");
1175 case OFFLOAD:
1176 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001177 case MMAP_PLAYBACK:
1178 return String16("MmapPlayback");
1179 case MMAP_CAPTURE:
1180 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001181 case SPATIALIZER:
1182 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001183 default:
1184 ALOG_ASSERT(false);
1185 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001186 }
1187}
1188
Andy Hungee58e4a2023-07-07 13:47:37 -07001189void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001190{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001191 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001192 if (mPowerManager != 0) {
1193 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001194 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001195 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1196 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001197 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001198 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001199 {} /* workSource */,
1200 {} /* historyTag */);
1201 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001202 mWakeLockToken = binder;
1203 }
Chris Ye6597d732020-02-28 22:38:25 -08001204 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001205 }
Wei Jia3f273d12015-11-24 09:06:49 -08001206
Andy Hung3f0c9022016-01-15 17:49:46 -08001207 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001208 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1209 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001210}
1211
Andy Hungee58e4a2023-07-07 13:47:37 -07001212void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001213{
Andy Hung972bec12023-08-31 16:13:39 -07001214 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001215 releaseWakeLock_l();
1216}
1217
Andy Hungee58e4a2023-07-07 13:47:37 -07001218void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001219{
Andy Hung3f0c9022016-01-15 17:49:46 -08001220 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001221 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001222 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001223 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001224 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001225 }
1226 mWakeLockToken.clear();
1227 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001228}
1229
Andy Hungee58e4a2023-07-07 13:47:37 -07001230void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001231 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001232 // use checkService() to avoid blocking if power service is not up yet
1233 sp<IBinder> binder =
1234 defaultServiceManager()->checkService(String16("power"));
1235 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001236 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001238 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001239 binder->linkToDeath(mDeathRecipient);
1240 }
1241 }
1242}
1243
Andy Hungee58e4a2023-07-07 13:47:37 -07001244void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001245 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001246
1247#if !LOG_NDEBUG
1248 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001249 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001250 s << uid << " ";
1251 }
1252 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1253#endif
1254
Andy Hung438e7572015-12-14 15:51:17 -08001255 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1256 if (mSystemReady) {
1257 ALOGE("no wake lock to update, but system ready!");
1258 } else {
1259 ALOGW("no wake lock to update, system not ready yet");
1260 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001261 return;
1262 }
1263 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001264 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001265 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1266 mWakeLockToken, uidsAsInt);
1267 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001268 }
1269}
1270
Andy Hungee58e4a2023-07-07 13:47:37 -07001271void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001272{
Andy Hung972bec12023-08-31 16:13:39 -07001273 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001274 releaseWakeLock_l();
1275 mPowerManager.clear();
1276}
1277
Andy Hungee58e4a2023-07-07 13:47:37 -07001278void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001279 const DeviceDescriptorBaseVector& outDevices __unused)
1280{
1281 ALOGE("%s should only be called in RecordThread", __func__);
1282}
1283
Andy Hungee58e4a2023-07-07 13:47:37 -07001284void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001285{
1286 ALOGE("%s should only be called in RecordThread", __func__);
1287}
1288
Andy Hungee58e4a2023-07-07 13:47:37 -07001289void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001290{
1291 sp<ThreadBase> thread = mThread.promote();
1292 if (thread != 0) {
1293 thread->clearPowerManager();
1294 }
1295 ALOGW("power manager service died !!!");
1296}
1297
Andy Hungee58e4a2023-07-07 13:47:37 -07001298void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001299 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001300{
Andy Hung116bc262023-06-20 18:56:17 -07001301 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001302 if (chain != 0) {
1303 if (type != NULL) {
1304 chain->setEffectSuspended_l(type, suspend);
1305 } else {
1306 chain->setEffectSuspendedAll_l(suspend);
1307 }
1308 }
1309
1310 updateSuspendedSessions_l(type, suspend, sessionId);
1311}
1312
Andy Hungee58e4a2023-07-07 13:47:37 -07001313void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001314{
1315 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1316 if (index < 0) {
1317 return;
1318 }
1319
1320 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1321 mSuspendedSessions.valueAt(index);
1322
1323 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001324 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001326 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001327 chain->setEffectSuspendedAll_l(true);
1328 } else {
1329 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1330 desc->mType.timeLow);
1331 chain->setEffectSuspended_l(&desc->mType, true);
1332 }
1333 }
1334 }
1335}
1336
Andy Hungee58e4a2023-07-07 13:47:37 -07001337void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001338 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001339 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001340{
1341 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1342
1343 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1344
1345 if (suspend) {
1346 if (index >= 0) {
1347 sessionEffects = mSuspendedSessions.valueAt(index);
1348 } else {
1349 mSuspendedSessions.add(sessionId, sessionEffects);
1350 }
1351 } else {
1352 if (index < 0) {
1353 return;
1354 }
1355 sessionEffects = mSuspendedSessions.valueAt(index);
1356 }
1357
1358
Andy Hung116bc262023-06-20 18:56:17 -07001359 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001360 if (type != NULL) {
1361 key = type->timeLow;
1362 }
1363 index = sessionEffects.indexOfKey(key);
1364
1365 sp<SuspendedSessionDesc> desc;
1366 if (suspend) {
1367 if (index >= 0) {
1368 desc = sessionEffects.valueAt(index);
1369 } else {
1370 desc = new SuspendedSessionDesc();
1371 if (type != NULL) {
1372 desc->mType = *type;
1373 }
1374 sessionEffects.add(key, desc);
1375 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1376 }
1377 desc->mRefCount++;
1378 } else {
1379 if (index < 0) {
1380 return;
1381 }
1382 desc = sessionEffects.valueAt(index);
1383 if (--desc->mRefCount == 0) {
1384 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1385 sessionEffects.removeItemsAt(index);
1386 if (sessionEffects.isEmpty()) {
1387 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1388 sessionId);
1389 mSuspendedSessions.removeItem(sessionId);
1390 }
1391 }
1392 }
1393 if (!sessionEffects.isEmpty()) {
1394 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1395 }
1396}
1397
Andy Hungee58e4a2023-07-07 13:47:37 -07001398void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001399 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001400 bool threadLocked)
1401NO_THREAD_SAFETY_ANALYSIS // manual locking
1402{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001403 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001404 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001405 }
Eric Laurent81784c32012-11-19 14:55:58 -08001406
Eric Laurent81784c32012-11-19 14:55:58 -08001407 if (mType != RECORD) {
1408 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1409 // another session. This gives the priority to well behaved effect control panels
1410 // and applications not using global effects.
1411 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1412 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001413 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001414 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1415 }
1416 }
1417
Eric Laurent6b446ce2019-12-13 10:56:31 -08001418 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001419 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001420 }
1421}
1422
Andy Hungc5007f82023-08-29 14:26:09 -07001423// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001424status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001425 const effect_descriptor_t *desc, audio_session_t sessionId)
1426{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001427 // No global output effect sessions on record threads
1428 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1429 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001430 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1431 desc->name, mThreadName);
1432 return BAD_VALUE;
1433 }
1434 // only pre processing effects on record thread
1435 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1436 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1437 desc->name, mThreadName);
1438 return BAD_VALUE;
1439 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001440
1441 // always allow effects without processing load or latency
1442 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1443 return NO_ERROR;
1444 }
1445
Eric Laurent4c415062016-06-17 16:14:16 -07001446 audio_input_flags_t flags = mInput->flags;
1447 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1448 if (flags & AUDIO_INPUT_FLAG_RAW) {
1449 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1450 desc->name, mThreadName);
1451 return BAD_VALUE;
1452 }
1453 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1454 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1455 desc->name, mThreadName);
1456 return BAD_VALUE;
1457 }
1458 }
jiabineb3bda02020-06-30 14:07:03 -07001459
Andy Hung116bc262023-06-20 18:56:17 -07001460 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001461 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1462 return BAD_VALUE;
1463 }
Eric Laurent4c415062016-06-17 16:14:16 -07001464 return NO_ERROR;
1465}
1466
Andy Hungc5007f82023-08-29 14:26:09 -07001467// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001468status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001469 const effect_descriptor_t *desc, audio_session_t sessionId)
1470{
1471 // no preprocessing on playback threads
1472 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001473 ALOGW("%s: pre processing effect %s created on playback"
1474 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001475 return BAD_VALUE;
1476 }
1477
Eric Laurent3e4de772017-07-16 16:55:08 -07001478 // always allow effects without processing load or latency
1479 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1480 return NO_ERROR;
1481 }
1482
Andy Hung116bc262023-06-20 18:56:17 -07001483 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001484 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1485 __func__);
1486 return BAD_VALUE;
1487 }
1488
Eric Laurent4eb45d02023-12-20 12:07:17 +01001489 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001490 && mType != SPATIALIZER) {
1491 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1492 __func__, mType);
1493 return BAD_VALUE;
1494 }
1495
Eric Laurent4c415062016-06-17 16:14:16 -07001496 switch (mType) {
1497 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001498 audio_output_flags_t flags = mOutput->flags;
1499 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1500 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1501 // global effects are applied only to non fast tracks if they are SW
1502 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1503 break;
1504 }
1505 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1506 // only post processing on output stage session
1507 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001508 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1509 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001510 return BAD_VALUE;
1511 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001512 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1513 // only post processing on output stage session
1514 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001515 ALOGW("%s: non post processing effect %s not allowed on device session",
1516 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001517 return BAD_VALUE;
1518 }
Eric Laurent4c415062016-06-17 16:14:16 -07001519 } else {
1520 // no restriction on effects applied on non fast tracks
1521 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1522 break;
1523 }
1524 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001525
Eric Laurent4c415062016-06-17 16:14:16 -07001526 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001527 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001528 return BAD_VALUE;
1529 }
1530 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001531 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1532 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001533 return BAD_VALUE;
1534 }
1535 }
1536 } break;
1537 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001538 // nothing actionable on offload threads, if the effect:
1539 // - is offloadable: the effect can be created
1540 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1541 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001542 break;
1543 case DIRECT:
1544 // Reject any effect on Direct output threads for now, since the format of
1545 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001546 ALOGW("%s: effect %s on DIRECT output thread %s",
1547 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001548 return BAD_VALUE;
1549 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001550 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001551 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1552 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001553 return BAD_VALUE;
1554 }
1555 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001556 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1557 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001558 return BAD_VALUE;
1559 }
1560 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001561 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1562 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001563 return BAD_VALUE;
1564 }
1565 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001566 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001567 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1568 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1569 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1570 // are supported and added after the spatializer.
1571 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1572 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1573 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001574 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001575 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1576 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001577 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001578 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1579 break;
1580 }
1581 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1582 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1583 __func__, desc->name);
1584 return BAD_VALUE;
1585 }
1586 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1587 // only post processing on output stage session
1588 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1589 ALOGW("%s: non post processing effect %s not allowed on device session",
1590 __func__, desc->name);
1591 return BAD_VALUE;
1592 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001593 }
1594 break;
jiabinc658e452022-10-21 20:52:21 +00001595 case BIT_PERFECT:
1596 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1597 // Allow HW accelerated effects of tunnel type
1598 break;
1599 }
1600 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1601 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1602 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1603 // 3) there is any bit-perfect track with the given session id.
1604 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1605 sessionId == AUDIO_SESSION_DEVICE) {
1606 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1607 __func__, desc->name, mThreadName);
1608 return BAD_VALUE;
1609 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1610 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1611 __func__, desc->name, sessionId);
1612 return BAD_VALUE;
1613 }
1614 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001615 default:
1616 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1617 }
1618
1619 return NO_ERROR;
1620}
1621
Andy Hungc5007f82023-08-29 14:26:09 -07001622// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001623sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001624 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001625 const sp<IEffectClient>& effectClient,
1626 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001627 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001628 effect_descriptor_t *desc,
1629 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001630 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001631 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001632 bool probe,
1633 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001634{
Andy Hung116bc262023-06-20 18:56:17 -07001635 sp<IAfEffectModule> effect;
1636 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001637 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001638 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001639 bool chainCreated = false;
1640 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001641 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001642
1643 lStatus = initCheck();
1644 if (lStatus != NO_ERROR) {
1645 ALOGW("createEffect_l() Audio driver not initialized.");
1646 goto Exit;
1647 }
1648
Eric Laurent81784c32012-11-19 14:55:58 -08001649 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1650
Andy Hungc5007f82023-08-29 14:26:09 -07001651 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001652 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001653
Eric Laurent4c415062016-06-17 16:14:16 -07001654 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001655 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001656 goto Exit;
1657 }
1658
Eric Laurent81784c32012-11-19 14:55:58 -08001659 // check for existing effect chain with the requested audio session
1660 chain = getEffectChain_l(sessionId);
1661 if (chain == 0) {
1662 // create a new chain for this session
1663 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001664 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001665 addEffectChain_l(chain);
1666 chain->setStrategy(getStrategyForSession_l(sessionId));
1667 chainCreated = true;
1668 } else {
1669 effect = chain->getEffectFromDesc_l(desc);
1670 }
1671
1672 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1673
1674 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001675 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001676 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001677 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001678 if (lStatus != NO_ERROR) {
1679 goto Exit;
1680 }
1681 effectCreated = true;
1682
jiabinc52b1ff2019-10-31 17:20:42 -07001683 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001684 effect->setDevices(outDeviceTypeAddrs());
1685 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001686 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001687 effect->setAudioSource(mAudioSource);
1688 }
jiabin1319f5a2021-03-30 22:21:24 +00001689 if (effect->isHapticGenerator()) {
1690 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1691 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001692 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001693 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001694 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001695 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001696 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001697 }
1698 }
Eric Laurent81784c32012-11-19 14:55:58 -08001699 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001700 handle = IAfEffectHandle::create(
1701 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001702 lStatus = handle->initCheck();
1703 if (lStatus == OK) {
1704 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001705 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001706 }
Eric Laurent81784c32012-11-19 14:55:58 -08001707 if (enabled != NULL) {
1708 *enabled = (int)effect->isEnabled();
1709 }
1710 }
1711
1712Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001713 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001714 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001715 if (effectCreated) {
1716 chain->removeEffect_l(effect);
1717 }
Eric Laurent81784c32012-11-19 14:55:58 -08001718 if (chainCreated) {
1719 removeEffectChain_l(chain);
1720 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001721 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001722 }
1723
Glenn Kasten9156ef32013-08-06 15:39:08 -07001724 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001725 return handle;
1726}
1727
Andy Hungee58e4a2023-07-07 13:47:37 -07001728void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001729 bool unpinIfLast)
1730{
1731 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001732 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001733 {
Andy Hung972bec12023-08-31 16:13:39 -07001734 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001735 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001736 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001737 return;
1738 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001739 effect = effectBase->asEffectModule();
1740 if (effect == nullptr) {
1741 return;
1742 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001743 // restore suspended effects if the disconnected handle was enabled and the last one.
1744 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1745 if (remove) {
1746 removeEffect_l(effect, true);
1747 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001748 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001749 }
1750 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001751 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001752 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001753 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001754 }
1755 }
1756}
1757
Andy Hungee58e4a2023-07-07 13:47:37 -07001758void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001759 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001760 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001761 broadcast_l();
1762 }
1763 if (!effect->isOffloadable()) {
1764 if (mType == ThreadBase::OFFLOAD) {
1765 PlaybackThread *t = (PlaybackThread *)this;
1766 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1767 }
1768 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001769 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001770 }
1771 }
1772}
1773
Andy Hungee58e4a2023-07-07 13:47:37 -07001774void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001775 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001776 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001777 broadcast_l();
1778 }
1779}
1780
Andy Hungee58e4a2023-07-07 13:47:37 -07001781sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001782 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001783{
Andy Hung972bec12023-08-31 16:13:39 -07001784 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001785 return getEffect_l(sessionId, effectId);
1786}
1787
Andy Hungee58e4a2023-07-07 13:47:37 -07001788sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001789 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001790{
Andy Hung116bc262023-06-20 18:56:17 -07001791 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001792 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1793}
1794
Andy Hungee58e4a2023-07-07 13:47:37 -07001795std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001796{
Andy Hung116bc262023-06-20 18:56:17 -07001797 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001798 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001799}
1800
Andy Hung972bec12023-08-31 16:13:39 -07001801// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1802// ThreadBase::mutex() held
1803status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001804{
1805 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001806 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001807 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001808 bool chainCreated = false;
1809
Eric Laurent5baf2af2013-09-12 17:37:00 -07001810 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001811 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1812 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001813
Eric Laurent81784c32012-11-19 14:55:58 -08001814 if (chain == 0) {
1815 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001816 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001817 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001818 addEffectChain_l(chain);
1819 chain->setStrategy(getStrategyForSession_l(sessionId));
1820 chainCreated = true;
1821 }
Andy Hung972bec12023-08-31 16:13:39 -07001822 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001823
1824 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001825 ALOGW("%s: %p effect %s already present in chain %p",
1826 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001827 return BAD_VALUE;
1828 }
1829
Shunkai Yaod125e402024-01-20 03:19:06 +00001830 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001831
Eric Laurent81784c32012-11-19 14:55:58 -08001832 status_t status = chain->addEffect_l(effect);
1833 if (status != NO_ERROR) {
1834 if (chainCreated) {
1835 removeEffectChain_l(chain);
1836 }
1837 return status;
1838 }
1839
jiabin8f278ee2019-11-11 12:16:27 -08001840 effect->setDevices(outDeviceTypeAddrs());
1841 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001842 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001843 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001844
Eric Laurent81784c32012-11-19 14:55:58 -08001845 return NO_ERROR;
1846}
1847
Andy Hungee58e4a2023-07-07 13:47:37 -07001848void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001849
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001850 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001851 effect_descriptor_t desc = effect->desc();
1852 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1853 detachAuxEffect_l(effect->id());
1854 }
1855
Andy Hung116bc262023-06-20 18:56:17 -07001856 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001857 if (chain != 0) {
1858 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001859 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001860 removeEffectChain_l(chain);
1861 }
1862 } else {
1863 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1864 }
1865}
1866
Shunkai Yaof4847652024-01-12 00:25:20 +00001867void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1868 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001869{
1870 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001871 for (const auto& effectChain : effectChains) {
1872 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001873 }
1874}
1875
Shunkai Yaof4847652024-01-12 00:25:20 +00001876void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1877 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001878{
Shunkai Yaof4847652024-01-12 00:25:20 +00001879 for (const auto& effectChain : effectChains) {
1880 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001881 }
1882}
1883
Andy Hungee58e4a2023-07-07 13:47:37 -07001884sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001885{
Andy Hung972bec12023-08-31 16:13:39 -07001886 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001887 return getEffectChain_l(sessionId);
1888}
1889
Andy Hungee58e4a2023-07-07 13:47:37 -07001890sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001891 const
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
1893 size_t size = mEffectChains.size();
1894 for (size_t i = 0; i < size; i++) {
1895 if (mEffectChains[i]->sessionId() == sessionId) {
1896 return mEffectChains[i];
1897 }
1898 }
1899 return 0;
1900}
1901
Andy Hungee58e4a2023-07-07 13:47:37 -07001902void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001903{
Andy Hung972bec12023-08-31 16:13:39 -07001904 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001905 size_t size = mEffectChains.size();
1906 for (size_t i = 0; i < size; i++) {
1907 mEffectChains[i]->setMode_l(mode);
1908 }
1909}
1910
Andy Hungee58e4a2023-07-07 13:47:37 -07001911void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001912{
1913 config->type = AUDIO_PORT_TYPE_MIX;
1914 config->ext.mix.handle = mId;
1915 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001916 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001917 config->channel_mask = mChannelMask;
1918 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1919 AUDIO_PORT_CONFIG_FORMAT;
1920}
1921
Andy Hungee58e4a2023-07-07 13:47:37 -07001922void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001923{
Andy Hung972bec12023-08-31 16:13:39 -07001924 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001925 if (mSystemReady) {
1926 return;
1927 }
1928 mSystemReady = true;
1929
1930 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1931 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1932 }
1933 mPendingConfigEvents.clear();
1934}
1935
Andy Hungdae27702016-10-31 14:01:16 -07001936template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001937ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001938 ssize_t index = mActiveTracks.indexOf(track);
1939 if (index >= 0) {
1940 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1941 return index;
1942 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001943 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001944 mActiveTracksGeneration++;
1945 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001946 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001947 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001948 return mActiveTracks.add(track);
1949}
1950
1951template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001952ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001953 ssize_t index = mActiveTracks.remove(track);
1954 if (index < 0) {
1955 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1956 return index;
1957 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001958 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001959 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001960 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001961 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001962 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001963#ifdef TEE_SINK
1964 track->dumpTee(-1 /* fd */, "_REMOVE");
1965#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001966 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001967 return index;
1968}
1969
1970template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001971void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001972 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001973 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001974 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001975 }
1976 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001977 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001978 mActiveTracks.clear();
1979 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001980}
1981
1982template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001983void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001984 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001985 // Updates ActiveTracks client uids to the thread wakelock.
1986 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1987 thread->updateWakeLockUids_l(getWakeLockUids());
1988 mLastActiveTracksGeneration = mActiveTracksGeneration;
1989 }
Andy Hungdae27702016-10-31 14:01:16 -07001990}
Eric Laurent83b88082014-06-20 18:31:16 -07001991
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001992template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001993bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001994 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001995 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001996
1997 for (const sp<T> &track : mActiveTracks) {
1998 // Do not short-circuit as all hasChanged states must be reset
1999 // as all the metadata are going to be sent
2000 hasChanged |= track->readAndClearHasChanged();
2001 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002002 return hasChanged;
2003}
2004
2005template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002006void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002007 const char *funcName, const sp<T> &track) const {
2008 if (mLocalLog != nullptr) {
2009 String8 result;
2010 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002011 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002012 }
2013}
2014
Andy Hungee58e4a2023-07-07 13:47:37 -07002015void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002016{
2017 // Thread could be blocked waiting for async
2018 // so signal it to handle state changes immediately
2019 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2020 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2021 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002022 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002023}
2024
Andy Hungd0979812019-02-21 15:51:44 -08002025// Call only from threadLoop() or when it is idle.
2026// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002027void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002028NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002029{
2030 // Do not log if we have no stats.
2031 // We choose the timestamp verifier because it is the most likely item to be present.
2032 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2033 if (nstats == 0) {
2034 return;
2035 }
2036
2037 // Don't log more frequently than once per 12 hours.
2038 // We use BOOTTIME to include suspend time.
2039 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2040 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2041 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2042 return;
2043 }
2044
2045 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2046 mLastRecordedTimeNs = timeNs;
2047
Ray Essickf27e9872019-12-07 06:28:46 -08002048 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002049
2050#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2051
2052 // thread configuration
2053 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2054 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2055 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2056 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2057 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2058 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2059 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002060 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2061 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002062
2063 // thread statistics
2064 if (mIoJitterMs.getN() > 0) {
2065 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2066 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2067 }
2068 if (mProcessTimeMs.getN() > 0) {
2069 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2070 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2071 }
2072 const auto tsjitter = mTimestampVerifier.getJitterMs();
2073 if (tsjitter.getN() > 0) {
2074 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2075 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2076 }
2077 if (mLatencyMs.getN() > 0) {
2078 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2079 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2080 }
Robert Wu06db0a32021-08-10 19:05:34 +00002081 if (mMonopipePipeDepthStats.getN() > 0) {
2082 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2083 mMonopipePipeDepthStats.getMean());
2084 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2085 mMonopipePipeDepthStats.getStdDev());
2086 }
Andy Hungd0979812019-02-21 15:51:44 -08002087
2088 item->selfrecord();
2089}
2090
Andy Hungee58e4a2023-07-07 13:47:37 -07002091product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002092{
Andy Hung583043b2023-07-17 17:05:00 -07002093 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002094 return PRODUCT_STRATEGY_NONE;
2095 }
2096 return AudioSystem::getStrategyForStream(stream);
2097}
2098
Andy Hungc5007f82023-08-29 14:26:09 -07002099// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002100void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002101 const sp<audio_utils::MelProcessor>& /*processor*/)
2102{
2103 // Do nothing
2104 ALOGW("%s: ThreadBase does not support CSD", __func__);
2105}
2106
Andy Hungc5007f82023-08-29 14:26:09 -07002107// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002108void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002109{
2110 // Do nothing
2111 ALOGW("%s: ThreadBase does not support CSD", __func__);
2112}
2113
Eric Laurent81784c32012-11-19 14:55:58 -08002114// ----------------------------------------------------------------------------
2115// Playback
2116// ----------------------------------------------------------------------------
2117
Andy Hung583043b2023-07-17 17:05:00 -07002118PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002119 AudioStreamOut* output,
2120 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002121 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002122 bool systemReady,
2123 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002124 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002125 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002126 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002127 mMixerBuffer(NULL),
2128 mMixerBufferSize(0),
2129 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2130 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002131 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002132 mEffectBuffer(NULL),
2133 mEffectBufferSize(0),
2134 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2135 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002136 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002137 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002138 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002139 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002140 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002141 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002142 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002143 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002144 mMixerStatus(MIXER_IDLE),
2145 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002146 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002147 mBytesRemaining(0),
2148 mCurrentWriteLength(0),
2149 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002150 mWriteAckSequence(0),
2151 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002152 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002153 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002154 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002155 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002156 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002157 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002158 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002159{
Glenn Kastend7dca052015-03-05 16:05:54 -08002160 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002161 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002162
Andy Hungc5007f82023-08-29 14:26:09 -07002163 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // it would be safer to explicitly pass initial masterVolume/masterMute as
2165 // parameter.
2166 //
2167 // If the HAL we are using has support for master volume or master mute,
2168 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2169 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002170 mMasterVolume = afThreadCallback->masterVolume_l();
2171 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002172 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002173 if (mOutput->audioHwDev->canSetMasterVolume()) {
2174 mMasterVolume = 1.0;
2175 }
2176
2177 if (mOutput->audioHwDev->canSetMasterMute()) {
2178 mMasterMute = false;
2179 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002180 mIsMsdDevice = strcmp(
2181 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002182 }
2183
Eric Laurentf1f22e72021-07-13 14:04:14 +02002184 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2185 mMixerChannelMask = mixerConfig->channel_mask;
2186 }
2187
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002188 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002189
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002190 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002191 && mMixerChannelMask != mChannelMask) {
2192 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2193 mChannelMask, mMixerChannelMask);
2194 }
2195
Andy Hungc8fddf32018-08-08 18:32:37 -07002196 // TODO: We may also match on address as well as device type for
2197 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002198 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002199 // TODO: This property should be ensure that only contains one single device type.
2200 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2201 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002202 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2203 : AUDIO_DEVICE_NONE));
2204 }
2205
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002206 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2207 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002208 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002209 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002210 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002211 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002212 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2213 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002214 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2215 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002216}
2217
Andy Hungee58e4a2023-07-07 13:47:37 -07002218PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002219{
Andy Hung583043b2023-07-17 17:05:00 -07002220 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002221 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002222 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002223 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002224 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002225}
2226
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002227// Thread virtuals
2228
Andy Hungee58e4a2023-07-07 13:47:37 -07002229void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002230{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002231 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002232 ALOGE("The stream is not open yet"); // This should not happen.
2233 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002234 // Callbacks take strong or weak pointers as a parameter.
2235 // Since PlaybackThread passes itself as a callback handler, it can only
2236 // be done outside of the constructor. Creating weak and especially strong
2237 // pointers to a refcounted object in its own constructor is strongly
2238 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2239 // Even if a function takes a weak pointer, it is possible that it will
2240 // need to convert it to a strong pointer down the line.
2241 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2242 mOutput->stream->setCallback(this) == OK) {
2243 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002244 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002245 }
2246
jiabinf6eb4c32020-02-25 14:06:25 -08002247 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002248 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002249 }
2250 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002251 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002252 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002253}
2254
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002255// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002256void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002257{
2258 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002259 status_t result = mOutput->stream->exit();
2260 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002261}
2262
Andy Hungee58e4a2023-07-07 13:47:37 -07002263void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002264{
Eric Laurent81784c32012-11-19 14:55:58 -08002265 String8 result;
2266
Marco Nelissenb2208842014-02-07 14:00:50 -08002267 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002268 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2269 const stream_type_t *st = &mStreamTypes[i];
2270 if (i > 0) {
2271 result.appendFormat(", ");
2272 }
2273 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2274 if (st->mute) {
2275 result.append("M");
2276 }
2277 }
2278 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002279 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002280 result.clear();
2281
Eric Laurent81784c32012-11-19 14:55:58 -08002282 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2283 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002284 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002285 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002286
2287 size_t numtracks = mTracks.size();
2288 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002289 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002290 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002291 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002292 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002293 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002294 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002295 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002296 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002297 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002298 if (track != 0) {
2299 bool active = mActiveTracks.indexOf(track) >= 0;
2300 if (active) {
2301 numactiveseen++;
2302 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002303 result.append(prefix);
2304 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002305 }
2306 }
2307 } else {
2308 result.append("\n");
2309 }
2310 if (numactiveseen != numactive) {
2311 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002312 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002313 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002314 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002315 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002316 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002317 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002318 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002319 result.append(prefix);
2320 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002321 }
2322 }
2323 }
2324
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002325 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002326}
2327
Andy Hungee58e4a2023-07-07 13:47:37 -07002328void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002329{
Andy Hung04cb8f72020-03-20 13:44:33 -07002330 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002331 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002332 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2333 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002334 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2335 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2336 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2337 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002338 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002339 dprintf(fd, " Total writes: %d\n", mNumWrites);
2340 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2341 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002342 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002343 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002344 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002345 AudioStreamOut *output = mOutput;
2346 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002347 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002348 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002349 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2350 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2351 if (mPipeSink.get() != nullptr) {
2352 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2353 }
2354 if (output != nullptr) {
2355 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002356 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358}
2359
Andy Hungc5007f82023-08-29 14:26:09 -07002360// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002361sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002362 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002363 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002364 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002365 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002366 audio_format_t format,
2367 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002368 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002369 size_t *pNotificationFrameCount,
2370 uint32_t notificationsPerBuffer,
2371 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002372 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002373 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002374 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002375 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002376 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002378 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002379 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002380 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002381 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002382 bool isBitPerfect,
2383 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002384{
Glenn Kasten74935e42013-12-19 08:56:45 -08002385 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002386 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002387 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002388 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002389 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002390 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002391 uint32_t sampleRate;
2392
2393 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2394 lStatus = BAD_VALUE;
2395 goto Exit;
2396 }
Eric Laurent21da6472017-11-09 16:29:26 -08002397
2398 if (*pSampleRate == 0) {
2399 *pSampleRate = mSampleRate;
2400 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002401 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002402
2403 // special case for FAST flag considered OK if fast mixer is present
2404 if (hasFastMixer()) {
2405 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2406 }
2407
2408 // Check if requested flags are compatible with output stream flags
2409 if ((*flags & outputFlags) != *flags) {
2410 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2411 *flags, outputFlags);
2412 *flags = (audio_output_flags_t)(*flags & outputFlags);
2413 }
Eric Laurent81784c32012-11-19 14:55:58 -08002414
jiabinc658e452022-10-21 20:52:21 +00002415 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002416 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002417 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002418 if (chain.get() != nullptr) {
2419 // Bit-perfect is required according to the configuration and preferred mixer
2420 // attributes, but it is not in the output flag from the client's request. Explicitly
2421 // adding bit-perfect flag to check the compatibility
2422 audio_output_flags_t flagsToCheck =
2423 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2424 chain->checkOutputFlagCompatibility(&flagsToCheck);
2425 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2426 ALOGE("%s cannot create track as there is data-processing effect attached to "
2427 "given session id(%d)", __func__, sessionId);
2428 lStatus = BAD_VALUE;
2429 goto Exit;
2430 }
2431 *flags = flagsToCheck;
2432 }
2433 }
2434
Eric Laurent81784c32012-11-19 14:55:58 -08002435 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002436 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002437 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002438 // PCM data
2439 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002440 // TODO: extract as a data library function that checks that a computationally
2441 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002442 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002443 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2444 (channelMask == AUDIO_CHANNEL_OUT_MONO
2445 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002446 // hardware sample rate
2447 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // normal mixer has an associated fast mixer
2449 hasFastMixer() &&
2450 // there are sufficient fast track slots available
2451 (mFastTrackAvailMask != 0)
2452 // FIXME test that MixerThread for this fast track has a capable output HAL
2453 // FIXME add a permission test also?
2454 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002455 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2456 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002457 // read the fast track multiplier property the first time it is needed
2458 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2459 if (ok != 0) {
2460 ALOGE("%s pthread_once failed: %d", __func__, ok);
2461 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002462 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002463 }
Eric Laurent4c415062016-06-17 16:14:16 -07002464
2465 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002466 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002467 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002468 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002469 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002470 AUDIO_SESSION_OUTPUT_STAGE,
2471 AUDIO_SESSION_OUTPUT_MIX,
2472 sessionId,
2473 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002474 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002475 if (chain.get() != nullptr) {
2476 audio_output_flags_t old = *flags;
2477 chain->checkOutputFlagCompatibility(flags);
2478 if (old != *flags) {
2479 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2480 (int)session, (int)old, (int)*flags);
2481 }
Eric Laurent4c415062016-06-17 16:14:16 -07002482 }
2483 }
2484 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002485 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002486 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2487 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002488 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002489 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002490 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002491 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002492 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002493 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002494 audio_is_linear_pcm(format), channelMask, sampleRate,
2495 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002496 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002497 }
2498 }
Eric Laurent21da6472017-11-09 16:29:26 -08002499
2500 if (!audio_has_proportional_frames(format)) {
2501 if (sharedBuffer != 0) {
2502 // Same comment as below about ignoring frameCount parameter for set()
2503 frameCount = sharedBuffer->size();
2504 } else if (frameCount == 0) {
2505 frameCount = mNormalFrameCount;
2506 }
2507 if (notificationFrameCount != frameCount) {
2508 notificationFrameCount = frameCount;
2509 }
2510 } else if (sharedBuffer != 0) {
2511 // FIXME: Ensure client side memory buffers need
2512 // not have additional alignment beyond sample
2513 // (e.g. 16 bit stereo accessed as 32 bit frame).
2514 size_t alignment = audio_bytes_per_sample(format);
2515 if (alignment & 1) {
2516 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2517 alignment = 1;
2518 }
2519 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2520 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2521 if (channelCount > 1) {
2522 // More than 2 channels does not require stronger alignment than stereo
2523 alignment <<= 1;
2524 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002525 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002526 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002527 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002528 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002529 goto Exit;
2530 }
Eric Laurent21da6472017-11-09 16:29:26 -08002531
2532 // When initializing a shared buffer AudioTrack via constructors,
2533 // there's no frameCount parameter.
2534 // But when initializing a shared buffer AudioTrack via set(),
2535 // there _is_ a frameCount parameter. We silently ignore it.
2536 frameCount = sharedBuffer->size() / frameSize;
2537 } else {
2538 size_t minFrameCount = 0;
2539 // For fast tracks we try to respect the application's request for notifications per buffer.
2540 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2541 if (notificationsPerBuffer > 0) {
2542 // Avoid possible arithmetic overflow during multiplication.
2543 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2544 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2545 notificationsPerBuffer, mFrameCount);
2546 } else {
2547 minFrameCount = mFrameCount * notificationsPerBuffer;
2548 }
2549 }
2550 } else {
2551 // For normal PCM streaming tracks, update minimum frame count.
2552 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2553 // cover audio hardware latency.
2554 // This is probably too conservative, but legacy application code may depend on it.
2555 // If you change this calculation, also review the start threshold which is related.
2556 uint32_t latencyMs = latency_l();
2557 if (latencyMs == 0) {
2558 ALOGE("Error when retrieving output stream latency");
2559 lStatus = UNKNOWN_ERROR;
2560 goto Exit;
2561 }
2562
2563 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2564 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2565
Eric Laurent81784c32012-11-19 14:55:58 -08002566 }
Eric Laurent21da6472017-11-09 16:29:26 -08002567 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002568 frameCount = minFrameCount;
2569 }
Eric Laurent81784c32012-11-19 14:55:58 -08002570 }
Eric Laurent21da6472017-11-09 16:29:26 -08002571
2572 // Make sure that application is notified with sufficient margin before underrun.
2573 // The client can divide the AudioTrack buffer into sub-buffers,
2574 // and expresses its desire to server as the notification frame count.
2575 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2576 size_t maxNotificationFrames;
2577 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2578 // notify every HAL buffer, regardless of the size of the track buffer
2579 maxNotificationFrames = mFrameCount;
2580 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002581 // Triple buffer the notification period for a triple buffered mixer period;
2582 // otherwise, double buffering for the notification period is fine.
2583 //
2584 // TODO: This should be moved to AudioTrack to modify the notification period
2585 // on AudioTrack::setBufferSizeInFrames() changes.
2586 const int nBuffering =
2587 (uint64_t{frameCount} * mSampleRate)
2588 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2589
Eric Laurent21da6472017-11-09 16:29:26 -08002590 maxNotificationFrames = frameCount / nBuffering;
2591 // If client requested a fast track but this was denied, then use the smaller maximum.
2592 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2593 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2594 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2595 maxNotificationFrames = maxNotificationFramesFastDenied;
2596 }
2597 }
2598 }
2599 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2600 if (notificationFrameCount == 0) {
2601 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2602 maxNotificationFrames, frameCount);
2603 } else {
2604 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2605 notificationFrameCount, maxNotificationFrames, frameCount);
2606 }
2607 notificationFrameCount = maxNotificationFrames;
2608 }
2609 }
2610
Glenn Kasten74935e42013-12-19 08:56:45 -08002611 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002612 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002613
Glenn Kastenc3df8382014-03-13 15:05:25 -07002614 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002615 case BIT_PERFECT:
2616 if (isBitPerfect) {
2617 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2618 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2619 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2620 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2621 mChannelMask);
2622 lStatus = BAD_VALUE;
2623 goto Exit;
2624 }
2625 }
2626 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002627
2628 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002629 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002630 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002631 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2632 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002633 sampleRate, format, channelMask, mOutput, mFormat);
2634 lStatus = BAD_VALUE;
2635 goto Exit;
2636 }
2637 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002638 break;
2639
2640 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002642 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2643 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644 sampleRate, format, channelMask, mOutput, mFormat);
2645 lStatus = BAD_VALUE;
2646 goto Exit;
2647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002648 break;
2649
2650 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002651 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002652 ALOGE("createTrack_l() Bad parameter: format %#x \""
2653 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 format, mOutput, mFormat);
2655 lStatus = BAD_VALUE;
2656 goto Exit;
2657 }
Andy Hungcd044842014-08-07 11:04:34 -07002658 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002659 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2660 lStatus = BAD_VALUE;
2661 goto Exit;
2662 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002663 break;
2664
Eric Laurent81784c32012-11-19 14:55:58 -08002665 }
2666
2667 lStatus = initCheck();
2668 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002669 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002670 goto Exit;
2671 }
2672
Andy Hungc5007f82023-08-29 14:26:09 -07002673 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002674 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002675
2676 // all tracks in same audio session must share the same routing strategy otherwise
2677 // conflicts will happen when tracks are moved from one output to another by audio policy
2678 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002679 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002680 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002681 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002682 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002683 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002684 if (sessionId == t->sessionId() && strategy != actual) {
2685 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2686 strategy, actual);
2687 lStatus = BAD_VALUE;
2688 goto Exit;
2689 }
2690 }
2691 }
2692
yucliuc9c49cd2020-07-13 16:25:21 -07002693 // Set DIRECT flag if current thread is DirectOutputThread. This can
2694 // happen when the playback is rerouted to direct output thread by
2695 // dynamic audio policy.
2696 // Do NOT report the flag changes back to client, since the client
2697 // doesn't explicitly request a direct flag.
2698 audio_output_flags_t trackFlags = *flags;
2699 if (mType == DIRECT) {
2700 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2701 }
jiabin94ed47c2023-07-27 23:34:20 +00002702 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002703
Andy Hung8d31fd22023-06-26 19:20:57 -07002704 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002705 channelMask, frameCount,
2706 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002707 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002708 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002709 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002710
Glenn Kasten03003332013-08-06 15:40:54 -07002711 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2712 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002713 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002714 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002715 goto Exit;
2716 }
2717 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002718 {
Andy Hung972bec12023-08-31 16:13:39 -07002719 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002720 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002721 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002722 }
2723 }
Eric Laurent81784c32012-11-19 14:55:58 -08002724
Andy Hung116bc262023-06-20 18:56:17 -07002725 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002726 if (chain != 0) {
2727 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2728 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002729 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002730 chain->incTrackCnt();
2731 }
2732
Eric Laurent05067782016-06-01 18:27:28 -07002733 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002734 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2735 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2736 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002737 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002738 }
2739 }
2740
2741 lStatus = NO_ERROR;
2742
2743Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002744 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002745 return track;
2746}
2747
Andy Hung1bc088a2018-02-09 15:57:31 -08002748template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002749ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002750{
Andy Hungc0691382018-09-12 18:01:57 -07002751 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002752 const ssize_t index = mTracks.remove(track);
2753 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002754 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002755 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002756 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002757 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002758 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002760 }
2761 return index;
2762}
2763
Andy Hungee58e4a2023-07-07 13:47:37 -07002764uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002765{
2766 return latency;
2767}
2768
Andy Hungee58e4a2023-07-07 13:47:37 -07002769uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002770{
Andy Hung972bec12023-08-31 16:13:39 -07002771 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002772 return latency_l();
2773}
Andy Hungee58e4a2023-07-07 13:47:37 -07002774uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002775NO_THREAD_SAFETY_ANALYSIS
2776// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002777{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002778 uint32_t latency;
2779 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2780 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002781 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002782 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002783}
2784
Andy Hungee58e4a2023-07-07 13:47:37 -07002785void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002786{
Andy Hung972bec12023-08-31 16:13:39 -07002787 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002788 // Don't apply master volume in SW if our HAL can do it for us.
2789 if (mOutput && mOutput->audioHwDev &&
2790 mOutput->audioHwDev->canSetMasterVolume()) {
2791 mMasterVolume = 1.0;
2792 } else {
2793 mMasterVolume = value;
2794 }
2795}
2796
Andy Hungee58e4a2023-07-07 13:47:37 -07002797void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002798{
2799 mMasterBalance.store(balance);
2800}
2801
Andy Hungee58e4a2023-07-07 13:47:37 -07002802void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002804 if (isDuplicating()) {
2805 return;
2806 }
Andy Hung972bec12023-08-31 16:13:39 -07002807 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002808 // Don't apply master mute in SW if our HAL can do it for us.
2809 if (mOutput && mOutput->audioHwDev &&
2810 mOutput->audioHwDev->canSetMasterMute()) {
2811 mMasterMute = false;
2812 } else {
2813 mMasterMute = muted;
2814 }
2815}
2816
Andy Hungee58e4a2023-07-07 13:47:37 -07002817void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002818{
Andy Hung972bec12023-08-31 16:13:39 -07002819 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002820 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002821 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002822}
2823
Andy Hungee58e4a2023-07-07 13:47:37 -07002824void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002825{
Andy Hung972bec12023-08-31 16:13:39 -07002826 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002827 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002828 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002829}
2830
Andy Hungee58e4a2023-07-07 13:47:37 -07002831float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002832{
Andy Hung972bec12023-08-31 16:13:39 -07002833 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002834 return mStreamTypes[stream].volume;
2835}
2836
Andy Hungee58e4a2023-07-07 13:47:37 -07002837void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002838{
2839 mOutput->stream->setVolume(left, right);
2840}
2841
Andy Hungc5007f82023-08-29 14:26:09 -07002842// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002843status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002844{
2845 status_t status = ALREADY_EXISTS;
2846
Eric Laurent81784c32012-11-19 14:55:58 -08002847 if (mActiveTracks.indexOf(track) < 0) {
2848 // the track is newly added, make sure it fills up all its
2849 // buffers before playing. This is to ensure the client will
2850 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002851 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002852 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002853 // Because the track is not on the ActiveTracks,
2854 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002855 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002856 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002857 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002859 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002861 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002862 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002863 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864 }
2865 return INVALID_OPERATION;
2866 }
2867 // abort if start is rejected by audio policy manager
2868 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002869 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2870 // current playback thread is reopened, which may happen when clients set preferred
2871 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2872 // immediately.
2873 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 }
2875#ifdef ADD_BATTERY_DATA
2876 // to track the speaker usage
2877 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2878#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002879 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 }
2881
Eric Laurent51716182016-02-29 18:00:56 -08002882 // set retry count for buffer fill
2883 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002884 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002885 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002886 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002887 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002888 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002889 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002890 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002891 track->retryCount() = kMaxTrackStartupRetries;
2892 track->fillingStatus() =
2893 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002894 }
2895
Andy Hung116bc262023-06-20 18:56:17 -07002896 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002897 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2898 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2899 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002900 // Unlock due to VibratorService will lock for this call and will
2901 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002902 mutex().unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002903 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002904 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002905 std::optional<media::AudioVibratorInfo> vibratorInfo;
2906 {
2907 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2908 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002909 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002910 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002911 }
Andy Hungc5007f82023-08-29 14:26:09 -07002912 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002913 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002914 if (vibratorInfo) {
2915 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2916 }
2917
jiabin57303cc2018-12-18 15:45:57 -08002918 // Haptic playback should be enabled by vibrator service.
2919 if (track->getHapticPlaybackEnabled()) {
2920 // Disable haptic playback of all active track to ensure only
2921 // one track playing haptic if current track should play haptic.
2922 for (const auto &t : mActiveTracks) {
2923 t->setHapticPlaybackEnabled(false);
2924 }
jiabin245cdd92018-12-07 17:55:15 -08002925 }
jiabine70bc7f2020-06-30 22:07:55 -07002926
2927 // Set haptic intensity for effect
2928 if (chain != nullptr) {
2929 chain->setHapticIntensity_l(track->id(), intensity);
2930 }
jiabin245cdd92018-12-07 17:55:15 -08002931 }
2932
Andy Hung8d31fd22023-06-26 19:20:57 -07002933 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002934 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002935
2936 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2937 // all key changes are complete. It is possible that the threadLoop will begin
2938 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002939 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002940
Eric Laurentd0107bc2013-06-11 14:38:48 -07002941 if (chain != 0) {
2942 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2943 track->sessionId());
2944 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002945 }
2946
Andy Hungc2b11cb2020-04-22 09:04:01 -07002947 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002948 status = NO_ERROR;
2949 }
2950
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002951 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002952 return status;
2953}
2954
Andy Hungee58e4a2023-07-07 13:47:37 -07002955bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002956{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002957 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002958 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002959 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002960 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002961 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002962 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002963 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002964 if (track->isPausePending()) {
2965 track->pauseAck();
2966 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002967 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002968 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002969
2970 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002971}
2972
Andy Hungee58e4a2023-07-07 13:47:37 -07002973void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002974{
2975 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002976
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002977 String8 result;
2978 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002979 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002980
Eric Laurent81784c32012-11-19 14:55:58 -08002981 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002982 {
Andy Hung972bec12023-08-31 16:13:39 -07002983 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002984 mAudioTrackCallbacks.erase(track);
2985 }
Eric Laurent81784c32012-11-19 14:55:58 -08002986 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002987 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002988 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002989 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2990 mFastTrackAvailMask |= 1 << index;
2991 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002992 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002993 }
Andy Hung116bc262023-06-20 18:56:17 -07002994 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002995 if (chain != 0) {
2996 chain->decTrackCnt();
2997 }
2998}
2999
Andy Hungee58e4a2023-07-07 13:47:37 -07003000String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003001{
Andy Hung972bec12023-08-31 16:13:39 -07003002 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003003 String8 out_s8;
3004 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3005 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003006 }
Andy Hung920f6572022-10-06 12:09:49 -07003007 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003008}
3009
Andy Hungee58e4a2023-07-07 13:47:37 -07003010status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003011 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003012 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003013 return NO_INIT;
3014 }
3015 return mOutput->stream->selectPresentation(presentationId, programId);
3016}
3017
Andy Hungab65b182023-09-06 19:41:47 -07003018void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003019 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003020 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003021 sp<AudioIoDescriptor> desc;
3022 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003023 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003024 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003025 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003026 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003027 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3028 mSampleRate, mFormat, mChannelMask,
3029 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3030 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003031 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003032 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003033 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003034 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003035 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003036 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003037 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003038 break;
3039 }
Andy Hungab65b182023-09-06 19:41:47 -07003040 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003041}
3042
Andy Hungee58e4a2023-07-07 13:47:37 -07003043void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003044{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003045 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003046}
3047
Andy Hungee58e4a2023-07-07 13:47:37 -07003048void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003049{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003050 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003051}
3052
Andy Hungee58e4a2023-07-07 13:47:37 -07003053void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003054{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003055 mCallbackThread->setAsyncError();
3056}
3057
Andy Hungee58e4a2023-07-07 13:47:37 -07003058void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003059 const std::basic_string<uint8_t>& metadataBs)
3060{
Andy Hungee58e4a2023-07-07 13:47:37 -07003061 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003062 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003063 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003064 if (playbackThread == nullptr) {
3065 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3066 return;
3067 }
3068
jiabinf6eb4c32020-02-25 14:06:25 -08003069 audio_utils::metadata::Data metadata =
3070 audio_utils::metadata::dataFromByteString(metadataBs);
3071 if (metadata.empty()) {
3072 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3073 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3074 (int)metadataBs.size());
3075 return;
3076 }
3077
3078 audio_utils::metadata::ByteString metaDataStr =
3079 audio_utils::metadata::byteStringFromData(metadata);
3080 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003081 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003082 for (const auto& callbackPair : mAudioTrackCallbacks) {
3083 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003084 }
3085 }).detach();
3086}
3087
Andy Hungee58e4a2023-07-07 13:47:37 -07003088void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003089{
Andy Hung972bec12023-08-31 16:13:39 -07003090 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003091 // reject out of sequence requests
3092 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3093 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003094 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003095 }
3096}
3097
Andy Hungee58e4a2023-07-07 13:47:37 -07003098void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099{
Andy Hung972bec12023-08-31 16:13:39 -07003100 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003101 // reject out of sequence requests
3102 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003103 // Register discontinuity when HW drain is completed because that can cause
3104 // the timestamp frame position to reset to 0 for direct and offload threads.
3105 // (Out of sequence requests are ignored, since the discontinuity would be handled
3106 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003107 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003108 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003109 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110 }
3111}
3112
Andy Hungee58e4a2023-07-07 13:47:37 -07003113void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003114NO_THREAD_SAFETY_ANALYSIS
3115// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003116{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003117 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003118 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3119 mSampleRate = audioConfig.sample_rate;
3120 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003121 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003122 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003123 }
Andy Hung81994d62023-07-20 21:44:14 -07003124 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003125 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3126 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003127 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003128
3129 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3130 mMixerChannelMask = mChannelMask;
3131 }
3132
Andy Hunge5412692014-05-16 11:25:07 -07003133 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003134 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003135
Eric Laurentf1f22e72021-07-13 14:04:14 +02003136 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3137
Phil Burkca5e6142015-07-14 09:42:29 -07003138 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003139 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003140 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003141 // Get format from the shim, which will be different than the HAL format
3142 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003143 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003144 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003145 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003146 }
Andy Hung81994d62023-07-20 21:44:14 -07003147 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003148 LOG_FATAL("HAL format %#x not supported for mixed output",
3149 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003150 }
Phil Burk062e67a2015-02-11 13:40:50 -08003151 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003152 result = mOutput->stream->getBufferSize(&mBufferSize);
3153 LOG_ALWAYS_FATAL_IF(result != OK,
3154 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003155 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003156 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003157 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003158 mFrameCount);
3159 }
3160
Eric Laurentd1f69b02014-12-15 14:33:13 -08003161 mHwSupportsPause = false;
3162 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003163 bool supportsPause = false, supportsResume = false;
3164 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3165 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003166 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003167 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003168 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003169 } else if (supportsResume) {
3170 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003171 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003172 }
3173 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003174 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3175 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3176 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003177
Andy Hungfbfc3952015-01-15 13:33:51 -08003178 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3179 // For best precision, we use float instead of the associated output
3180 // device format (typically PCM 16 bit).
3181
3182 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3183 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3184 mBufferSize = mFrameSize * mFrameCount;
3185
3186 // TODO: We currently use the associated output device channel mask and sample rate.
3187 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3188 // (if a valid mask) to avoid premature downmix.
3189 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3190 // instead of the output device sample rate to avoid loss of high frequency information.
3191 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3192 }
3193
Andy Hung09a50072014-02-27 14:30:47 -08003194 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003195 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003196 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003197 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3198 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003199 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3200 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003201
Eric Laurent81784c32012-11-19 14:55:58 -08003202 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3203 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3204 maxNormalFrameCount = maxNormalFrameCount & ~15;
3205 if (maxNormalFrameCount < minNormalFrameCount) {
3206 maxNormalFrameCount = minNormalFrameCount;
3207 }
3208 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3209 if (multiplier <= 1.0) {
3210 multiplier = 1.0;
3211 } else if (multiplier <= 2.0) {
3212 if (2 * mFrameCount <= maxNormalFrameCount) {
3213 multiplier = 2.0;
3214 } else {
3215 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3216 }
3217 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003218 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003219 }
3220 }
3221 mNormalFrameCount = multiplier * mFrameCount;
3222 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003223 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003224 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3225 }
Andy Hungab65b182023-09-06 19:41:47 -07003226 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3227 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003228
Andy Hung08fb1742015-05-31 23:22:10 -07003229 // Check if we want to throttle the processing to no more than 2x normal rate
3230 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003231 mThreadThrottleTimeMs = 0;
3232 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003233 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3234
Andy Hung010a1a12014-03-13 13:57:33 -07003235 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3236 // Originally this was int16_t[] array, need to remove legacy implications.
3237 free(mSinkBuffer);
3238 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003239
Andy Hung5b10a202014-03-13 13:59:29 -07003240 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3241 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3242 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003243 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003244
Andy Hung69aed5f2014-02-25 17:24:40 -08003245 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3246 // drives the output.
3247 free(mMixerBuffer);
3248 mMixerBuffer = NULL;
3249 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003250 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003251 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003252 * audio_bytes_per_sample(mMixerBufferFormat);
3253 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3254 }
Andy Hung98ef9782014-03-04 14:46:50 -08003255 free(mEffectBuffer);
3256 mEffectBuffer = NULL;
3257 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003258 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003259 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003260 * audio_bytes_per_sample(mEffectBufferFormat);
3261 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3262 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003263
Eric Laurentb62d0362021-10-26 17:40:18 +02003264 if (mType == SPATIALIZER) {
3265 free(mPostSpatializerBuffer);
3266 mPostSpatializerBuffer = nullptr;
3267 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3268 * audio_bytes_per_sample(mEffectBufferFormat);
3269 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3270 }
3271
Mikhail Naganov55773032020-10-01 15:08:13 -07003272 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3273 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003274 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3275 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003276 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003277
Eric Laurent81784c32012-11-19 14:55:58 -08003278 // force reconfiguration of effect chains and engines to take new buffer size and audio
3279 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003280 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003281 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3282 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003283 // create a copy of mEffectChains as calling moveEffectChain_ll()
3284 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003285 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003286 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003287 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003288 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003289 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003290
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003291 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003292 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003293 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003294 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003295 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3296 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3297 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3298 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3299 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3300 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3301 (int32_t)mHapticChannelMask)
3302 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3303 (int32_t)mHapticChannelCount)
3304 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003305 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003306 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3307 (int32_t)mFrameCount) // sic - added HAL
3308 ;
3309 uint32_t latencyMs;
3310 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3311 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3312 }
3313 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003314}
3315
Andy Hungee58e4a2023-07-07 13:47:37 -07003316ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003317{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003318 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003319 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003320 }
3321 StreamOutHalInterface::SourceMetadata metadata;
Eric Laurent4eb45d02023-12-20 12:07:17 +01003322 if (com_android_media_audio_stereo_spatialization()) {
3323 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3324 for (const sp<IAfTrack>& track : mActiveTracks) {
3325 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3326 allSessionsMetadata[track->sessionId()];
3327 auto backInserter = std::back_inserter(sessionMetadata);
3328 // No track is invalid as this is called after prepareTrack_l in the same
3329 // critical section
3330 track->copyMetadataTo(backInserter);
3331 }
3332 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3333 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3334 metadata.tracks.insert(metadata.tracks.end(),
3335 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3336 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3337 chain->sendMetadata_l(sessionTrackMetadata, {});
3338 }
3339 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3340 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3341 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3342 }
3343 }
3344 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3345 chain->sendMetadata_l(metadata.tracks, {});
3346 }
3347 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3348 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3349 }
3350 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3351 chain->sendMetadata_l(metadata.tracks, {});
3352 }
3353 } else {
3354 auto backInserter = std::back_inserter(metadata.tracks);
3355 for (const sp<IAfTrack>& track : mActiveTracks) {
3356 // No track is invalid as this is called after prepareTrack_l in the same
3357 // critical section
3358 track->copyMetadataTo(backInserter);
3359 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003360 }
Kevin Rocard12381092018-04-11 09:19:59 -07003361 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003362 MetadataUpdate change;
3363 change.playbackMetadataUpdate = metadata.tracks;
3364 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003365}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003366
Andy Hungee58e4a2023-07-07 13:47:37 -07003367void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003368 const StreamOutHalInterface::SourceMetadata& metadata)
3369{
3370 mOutput->stream->updateSourceMetadata(metadata);
3371};
3372
Andy Hungee58e4a2023-07-07 13:47:37 -07003373status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003374 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003375{
3376 if (halFrames == NULL || dspFrames == NULL) {
3377 return BAD_VALUE;
3378 }
Andy Hung972bec12023-08-31 16:13:39 -07003379 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003380 if (initCheck() != NO_ERROR) {
3381 return INVALID_OPERATION;
3382 }
Andy Hung818e7a32016-02-16 18:08:07 -08003383 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003384 *halFrames = framesWritten;
3385
3386 if (isSuspended()) {
3387 // return an estimation of rendered frames when the output is suspended
3388 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003389 *dspFrames = (uint32_t)
3390 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003391 return NO_ERROR;
3392 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003393 status_t status;
3394 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003395 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003396 *dspFrames = (size_t)frames;
3397 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003398 }
3399}
3400
Andy Hungee58e4a2023-07-07 13:47:37 -07003401product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003402{
3403 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3404 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3405 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003406 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003407 }
3408 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003409 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003410 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003411 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003412 }
3413 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003414 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003415}
3416
3417
Andy Hungee58e4a2023-07-07 13:47:37 -07003418AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003419{
Andy Hung972bec12023-08-31 16:13:39 -07003420 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003421 return mOutput;
3422}
3423
Andy Hungee58e4a2023-07-07 13:47:37 -07003424AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003425{
Andy Hung972bec12023-08-31 16:13:39 -07003426 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003427 AudioStreamOut *output = mOutput;
3428 mOutput = NULL;
3429 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3430 // must push a NULL and wait for ack
3431 mOutputSink.clear();
3432 mPipeSink.clear();
3433 mNormalSink.clear();
3434 return output;
3435}
3436
Andy Hungc5007f82023-08-29 14:26:09 -07003437// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003438sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003439{
3440 if (mOutput == NULL) {
3441 return NULL;
3442 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003443 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003444}
3445
Andy Hungee58e4a2023-07-07 13:47:37 -07003446uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003447{
3448 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3449}
3450
Andy Hungee58e4a2023-07-07 13:47:37 -07003451status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003452{
3453 if (!isValidSyncEvent(event)) {
3454 return BAD_VALUE;
3455 }
3456
Andy Hung972bec12023-08-31 16:13:39 -07003457 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003458
3459 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003460 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003461 if (event->triggerSession() == track->sessionId()) {
3462 (void) track->setSyncEvent(event);
3463 return NO_ERROR;
3464 }
3465 }
3466
3467 return NAME_NOT_FOUND;
3468}
3469
Andy Hungee58e4a2023-07-07 13:47:37 -07003470bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003471{
3472 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3473}
3474
Andy Hungee58e4a2023-07-07 13:47:37 -07003475void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003476 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003477{
Andy Hungfe726a62018-09-27 15:17:25 -07003478 // Miscellaneous track cleanup when removed from the active list,
3479 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003480#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003481 for (const auto& track : tracksToRemove) {
3482 if (track->isExternalTrack()) {
3483 // to track the speaker usage
3484 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003485 }
3486 }
Andy Hungfe726a62018-09-27 15:17:25 -07003487#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003488}
3489
Andy Hungee58e4a2023-07-07 13:47:37 -07003490void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003491{
3492 if (!mMasterMute) {
3493 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003494 if (mOutDeviceTypeAddrs.empty()) {
3495 ALOGD("ro.audio.silent is ignored since no output device is set");
3496 return;
3497 }
Andy Hungab65b182023-09-06 19:41:47 -07003498 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003499 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3500 return;
3501 }
Eric Laurent81784c32012-11-19 14:55:58 -08003502 if (property_get("ro.audio.silent", value, "0") > 0) {
3503 char *endptr;
3504 unsigned long ul = strtoul(value, &endptr, 0);
3505 if (*endptr == '\0' && ul != 0) {
3506 ALOGD("Silence is golden");
3507 // The setprop command will not allow a property to be changed after
3508 // the first time it is set, so we don't have to worry about un-muting.
3509 setMasterMute_l(true);
3510 }
3511 }
3512 }
3513}
3514
3515// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003516ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003517{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003518 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003519 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003521 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003522
3523 // If an NBAIO sink is present, use it to write the normal mixer's submix
3524 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003525
Andy Hung010a1a12014-03-13 13:57:33 -07003526 const size_t count = mBytesRemaining / mFrameSize;
3527
Simon Wilson2d590962012-11-29 15:18:50 -08003528 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003529 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003530 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003531 if (screenState != mScreenState) {
3532 mScreenState = screenState;
3533 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3534 if (pipe != NULL) {
3535 pipe->setAvgFrames((mScreenState & 1) ?
3536 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3537 }
3538 }
Andy Hung010a1a12014-03-13 13:57:33 -07003539 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003540 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003541
Eric Laurent81784c32012-11-19 14:55:58 -08003542 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003543 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003544
Andy Hung8946a282018-04-19 20:04:56 -07003545#ifdef TEE_SINK
3546 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3547#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003548 } else {
3549 bytesWritten = framesWritten;
3550 }
3551 // otherwise use the HAL / AudioStreamOut directly
3552 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003553 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003554
Eric Laurentbfb1b832013-01-07 09:53:42 -08003555 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003556 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3557 mWriteAckSequence += 2;
3558 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003560 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003561 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003562 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003563 // FIXME We should have an implementation of timestamps for direct output threads.
3564 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003565 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003566 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003567
Eric Laurentbfb1b832013-01-07 09:53:42 -08003568 if (mUseAsyncWrite &&
3569 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3570 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003571 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003572 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003573 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003574 }
Eric Laurent81784c32012-11-19 14:55:58 -08003575 }
3576
Eric Laurent81784c32012-11-19 14:55:58 -08003577 mNumWrites++;
3578 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003579 if (mStandby) {
3580 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003581 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003582 mStandby = false;
3583 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584 return bytesWritten;
3585}
3586
Andy Hungc5007f82023-08-29 14:26:09 -07003587// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003588void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003589 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003590{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003591 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003592 if (outputSink != nullptr) {
3593 outputSink->startMelComputation(processor);
3594 }
Vlad Popab042ee62022-10-20 18:05:00 +02003595}
3596
Andy Hungc5007f82023-08-29 14:26:09 -07003597// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003598void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003599{
3600 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003601 if (outputSink != nullptr) {
3602 outputSink->stopMelComputation();
3603 }
Vlad Popab042ee62022-10-20 18:05:00 +02003604}
3605
Andy Hungee58e4a2023-07-07 13:47:37 -07003606void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003607{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003608 bool supportsDrain = false;
3609 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3611 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003612 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3613 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003615 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003616 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003617 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003618 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003619 }
3620}
3621
Andy Hungee58e4a2023-07-07 13:47:37 -07003622void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623{
Eric Laurent275e8e92014-11-30 15:14:47 -08003624 {
Andy Hung972bec12023-08-31 16:13:39 -07003625 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003626 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003627 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003628 track->invalidate();
3629 }
Andy Hungdae27702016-10-31 14:01:16 -07003630 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3631 // After we exit there are no more track changes sent to BatteryNotifier
3632 // because that requires an active threadLoop.
3633 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3634 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003635 }
Eric Laurent81784c32012-11-19 14:55:58 -08003636}
3637
3638/*
3639The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003640 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003641 - mActiveSleepTimeUs from activeSleepTimeUs()
3642 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003643 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3644 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003645 - maxPeriod from frame count and sample rate (MIXER only)
3646
3647The parameters that affect these derived values are:
3648 - frame count
3649 - frame size
3650 - sample rate
3651 - device type: A2DP or not
3652 - device latency
3653 - format: PCM or not
3654 - active sleep time
3655 - idle sleep time
3656*/
3657
Andy Hungee58e4a2023-07-07 13:47:37 -07003658void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003659{
Andy Hung25c2dac2014-02-27 14:56:00 -08003660 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003661 mActiveSleepTimeUs = activeSleepTimeUs();
3662 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003663
Andy Hung8fe87eb2023-07-20 21:31:38 -07003664 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003665
Eric Laurent42537be2016-01-08 17:16:42 -08003666 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3667 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003668 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003669 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3670 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3671 }
3672 }
Eric Laurent81784c32012-11-19 14:55:58 -08003673}
3674
Andy Hungee58e4a2023-07-07 13:47:37 -07003675bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003676{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003677 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003678 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003679 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003680 size_t size = mTracks.size();
3681 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003682 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003683 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003684 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003685 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003686 }
3687 }
Eric Laurent13084622016-05-17 10:51:49 -07003688 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003689}
3690
Andy Hungee58e4a2023-07-07 13:47:37 -07003691void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003692{
Andy Hung972bec12023-08-31 16:13:39 -07003693 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003694 invalidateTracks_l(streamType);
3695}
3696
Andy Hungee58e4a2023-07-07 13:47:37 -07003697void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003698 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003699 invalidateTracks_l(portIds);
3700}
3701
Andy Hungee58e4a2023-07-07 13:47:37 -07003702bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003703 bool trackMatch = false;
3704 const size_t size = mTracks.size();
3705 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003706 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003707 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3708 t->invalidate();
3709 portIds.erase(t->portId());
3710 trackMatch = true;
3711 }
3712 if (portIds.empty()) {
3713 break;
3714 }
3715 }
3716 return trackMatch;
3717}
3718
jiabinf042b9b2021-05-07 23:46:28 +00003719// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003720IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003721 audio_port_handle_t trackPortId) {
3722 for (size_t i = 0; i < mTracks.size(); i++) {
3723 if (mTracks[i]->portId() == trackPortId) {
3724 return mTracks[i].get();
3725 }
3726 }
3727 return nullptr;
3728}
3729
Andy Hungee58e4a2023-07-07 13:47:37 -07003730status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003731{
Glenn Kastend848eb42016-03-08 13:42:11 -08003732 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003733 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003734 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003735
Andy Hungd3639922022-04-28 18:00:49 -07003736 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003737 if (!audio_is_global_session(session)) {
3738 // player sessions on a spatializer output will use a dedicated input buffer and
3739 // will either output multi channel to mEffectBuffer if the track is spatilaized
3740 // or stereo to mPostSpatializerBuffer if not spatialized.
3741 uint32_t channelMask;
3742 bool isSessionSpatialized =
3743 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3744 if (isSessionSpatialized) {
3745 channelMask = mMixerChannelMask;
3746 } else {
3747 channelMask = mChannelMask;
3748 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003749 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003750 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003751 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003752 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003753 &halInBuffer);
3754 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003755
Andy Hung583043b2023-07-17 17:05:00 -07003756 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003757 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3758 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3759 &halOutBuffer);
3760 if (result != OK) return result;
3761
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003762 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003763
Mikhail Naganov022b9952017-01-04 16:36:51 -08003764 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3765 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003766 } else {
3767 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3768 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3769 // mPostSpatializerBuffer as output buffer
3770 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003771 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003772 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3773 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003774 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003775 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3776 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003777
Eric Laurentb62d0362021-10-26 17:40:18 +02003778 if (session == AUDIO_SESSION_DEVICE) {
3779 halInBuffer = halOutBuffer;
3780 }
3781 }
3782 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003783 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003784 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3785 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3786 &halInBuffer);
3787 if (result != OK) return result;
3788 halOutBuffer = halInBuffer;
3789 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3790 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003791 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003792 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003793 // Only one effect chain can be present in direct output thread and it uses
3794 // the sink buffer as input
3795 if (mType != DIRECT) {
3796 size_t numSamples = mNormalFrameCount
3797 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3798 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003799 const status_t allocateStatus =
3800 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003801 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003802 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003803 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003804
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003805 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003806 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3807 buffer, session);
3808 }
3809 }
3810 }
3811
3812 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003813 // Attach all tracks with same session ID to this chain.
3814 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003815 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003816 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003817 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3818 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003819 track->setMainBuffer(buffer);
3820 chain->incTrackCnt();
3821 }
3822 }
3823
3824 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003825 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003826 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003827 ALOGV("addEffectChain_l() activating track %p on session %d",
3828 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003829 chain->incActiveTrackCnt();
3830 }
3831 }
3832 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003833
Eric Laurentaaa44472014-09-12 17:41:50 -07003834 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003835 chain->setInBuffer(halInBuffer);
3836 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003837 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3838 // chains list in order to be processed last as it contains output device effects.
3839 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3840 // processing effects specific to an output stream before effects applied to all streams
3841 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003842 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3843 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003844 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003845 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003846 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003847 // Effect chain for other sessions are inserted at beginning of effect
3848 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003849 // sessions is not important.
3850 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003851 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3852 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003853 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003854 size_t size = mEffectChains.size();
3855 size_t i = 0;
3856 for (i = 0; i < size; i++) {
3857 if (mEffectChains[i]->sessionId() < session) {
3858 break;
3859 }
3860 }
3861 mEffectChains.insertAt(chain, i);
3862 checkSuspendOnAddEffectChain_l(chain);
3863
3864 return NO_ERROR;
3865}
3866
Andy Hungee58e4a2023-07-07 13:47:37 -07003867size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003868{
Glenn Kastend848eb42016-03-08 13:42:11 -08003869 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003870
3871 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3872
3873 for (size_t i = 0; i < mEffectChains.size(); i++) {
3874 if (chain == mEffectChains[i]) {
3875 mEffectChains.removeAt(i);
3876 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003877 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003878 if (session == track->sessionId()) {
3879 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3880 chain.get(), session);
3881 chain->decActiveTrackCnt();
3882 }
3883 }
3884
3885 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003886 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003887 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003888 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003889 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003890 chain->decTrackCnt();
3891 }
3892 }
3893 break;
3894 }
3895 }
3896 return mEffectChains.size();
3897}
3898
Andy Hungee58e4a2023-07-07 13:47:37 -07003899status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003900 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003901{
Andy Hung972bec12023-08-31 16:13:39 -07003902 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003903 return attachAuxEffect_l(track, EffectId);
3904}
3905
Andy Hungee58e4a2023-07-07 13:47:37 -07003906status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003907 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003908{
3909 status_t status = NO_ERROR;
3910
3911 if (EffectId == 0) {
3912 track->setAuxBuffer(0, NULL);
3913 } else {
3914 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003915 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003916 if (effect != 0) {
3917 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3918 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3919 } else {
3920 status = INVALID_OPERATION;
3921 }
3922 } else {
3923 status = BAD_VALUE;
3924 }
3925 }
3926 return status;
3927}
3928
Andy Hungee58e4a2023-07-07 13:47:37 -07003929void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003930{
3931 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003932 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003933 if (track->auxEffectId() == effectId) {
3934 attachAuxEffect_l(track, 0);
3935 }
3936 }
3937}
3938
Andy Hungee58e4a2023-07-07 13:47:37 -07003939bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003940NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003941{
Andy Hung78d8d952023-05-30 18:10:23 -07003942 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003943
Andy Hung077d62e2023-10-03 10:49:34 -07003944 if (mType == SPATIALIZER) {
3945 const pid_t tid = getTid();
3946 if (tid == -1) { // odd: we are here, we must be a running thread.
3947 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3948 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003949 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3950 if (priorityBoost > 0) {
3951 stream()->setHalThreadPriority(priorityBoost);
3952 }
Andy Hung077d62e2023-10-03 10:49:34 -07003953 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003954 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3955 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3956 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3957 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3958 // only on ARC.
3959 const pid_t tid = getTid();
3960 if (tid == -1) {
3961 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3962 } else {
3963 const status_t status = requestPriority(getpid(),
3964 tid,
3965 kPriorityPlaybackThreadArc,
3966 false /* isForApp */,
3967 true /* asynchronous */);
3968 if (status != OK) {
3969 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
3970 status);
3971 } else {
3972 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
3973 }
3974 }
Andy Hung077d62e2023-10-03 10:49:34 -07003975 }
3976
Andy Hung8d31fd22023-06-26 19:20:57 -07003977 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003978
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003979 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003980 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003981
3982 // MIXER
3983 nsecs_t lastWarning = 0;
3984
3985 // DUPLICATING
3986 // FIXME could this be made local to while loop?
3987 writeFrames = 0;
3988
3989 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003990 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003991
Andy Hungd3639922022-04-28 18:00:49 -07003992 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003993 sleepTimeShift = 0;
3994 }
3995
3996 CpuStats cpuStats;
3997 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3998
3999 acquireWakeLock();
4000
Glenn Kasteneef598c2017-04-03 14:41:13 -07004001 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4002 // thread associated with this PlaybackThread.
4003 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4004 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004005 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4006 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004007 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004008 const char *logString = NULL;
4009
rago1bb90822017-05-02 18:31:48 -07004010 // Estimated time for next buffer to be written to hal. This is used only on
4011 // suspended mode (for now) to help schedule the wait time until next iteration.
4012 nsecs_t timeLoopNextNs = 0;
4013
Eric Laurent664539d2013-09-23 18:24:31 -07004014 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004015
Andy Hung2dbffc22018-08-08 18:50:41 -07004016 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004017
Eric Laurentb3f315a2021-07-13 15:09:05 +02004018 sendCheckOutputStageEffectsEvent();
4019
Andy Hung446f4df2019-02-21 12:26:41 -08004020 // loopCount is used for statistics and diagnostics.
4021 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004022 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004023 // Log merge requests are performed during AudioFlinger binder transactions, but
4024 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004025 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004026
Eric Laurent81784c32012-11-19 14:55:58 -08004027 cpuStats.sample(myName);
4028
Andy Hung116bc262023-06-20 18:56:17 -07004029 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004030 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004031 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004032 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004033
Andy Hung2dbffc22018-08-08 18:50:41 -07004034 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4035 //
Andy Hungc5007f82023-08-29 14:26:09 -07004036 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004037 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004038 // Here, we try for the AF lock, but do not block on it as the latency
4039 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004040 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004041 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004042 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004043 status_t status = INVALID_OPERATION;
4044 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004045 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004046 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004047 && swPatches.size() > 0) {
4048 status = swPatches[0].getLatencyMs_l(&latencyMs);
4049 downstreamPatchHandle = swPatches[0].getPatchHandle();
4050 }
4051 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004052 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004053 lastDownstreamPatchHandle = downstreamPatchHandle;
4054 }
4055 if (status == OK) {
4056 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004057 // latency of 5 seconds).
4058 const double minLatency = 0., maxLatency = 5000.;
4059 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004060 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004061 } else {
4062 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004063 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004064 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004065 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004066 }
Andy Hung583043b2023-07-17 17:05:00 -07004067 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004068 }
4069 } else {
4070 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4071 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004072 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004073 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4074 }
4075 }
4076
Eric Laurentb3f315a2021-07-13 15:09:05 +02004077 if (mCheckOutputStageEffects.exchange(false)) {
4078 checkOutputStageEffects();
4079 }
4080
Vlad Popa7e81cea2023-01-19 16:34:16 +01004081 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004082 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004083
Andy Hungc5007f82023-08-29 14:26:09 -07004084 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004085
Eric Laurent021cf962014-05-13 10:18:14 -07004086 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004087 if (mCheckOutputStageEffects.load()) {
4088 continue;
4089 }
Eric Laurent10351942014-05-08 18:49:52 -07004090
Andy Hungc5007f82023-08-29 14:26:09 -07004091 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004092 if (logString != NULL) {
4093 mNBLogWriter->logTimestamp();
4094 mNBLogWriter->log(logString);
4095 logString = NULL;
4096 }
4097
Dean Wheatley12473e92021-03-18 23:00:55 +11004098 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004099
Eric Laurent81784c32012-11-19 14:55:58 -08004100 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004101 if (mSignalPending) {
4102 // A signal was raised while we were unlocked
4103 mSignalPending = false;
4104 } else if (waitingAsyncCallback_l()) {
4105 if (exitPending()) {
4106 break;
4107 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004108 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004109 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004110 releaseWakeLock_l();
4111 released = true;
4112 }
Andy Hung10cbff12017-02-21 17:30:14 -08004113
4114 const int64_t waitNs = computeWaitTimeNs_l();
4115 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004116 std::cv_status cvstatus =
4117 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4118 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004119 mSignalPending = true; // if timeout recheck everything
4120 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004122 if (released) {
4123 acquireWakeLock_l();
4124 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004125 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4126 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004127
4128 continue;
4129 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004130 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004131 isSuspended()) {
4132 // put audio hardware into standby after short delay
4133 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004134
4135 threadLoop_standby();
4136
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004137 // This is where we go into standby
4138 if (!mStandby) {
4139 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004140 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004141 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004142 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004143 }
Andy Hungd0979812019-02-21 15:51:44 -08004144 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004145 }
4146
Eric Tan39ec8d62018-07-24 09:49:29 -07004147 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004148 // we're about to wait, flush the binder command buffer
4149 IPCThreadState::self()->flushCommands();
4150
4151 clearOutputTracks();
4152
4153 if (exitPending()) {
4154 break;
4155 }
4156
4157 releaseWakeLock_l();
4158 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004159 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004160 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004161 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004162 acquireWakeLock_l();
4163
4164 mMixerStatus = MIXER_IDLE;
4165 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4166 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004168 checkSilentMode_l();
4169
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004170 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4171 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004172 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004173 sleepTimeShift = 0;
4174 }
4175
4176 continue;
4177 }
4178 }
Eric Laurent81784c32012-11-19 14:55:58 -08004179 // mMixerStatusIgnoringFastTracks is also updated internally
4180 mMixerStatus = prepareTracks_l(&tracksToRemove);
4181
Andy Hungab65b182023-09-06 19:41:47 -07004182 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004183
Vlad Popa7e81cea2023-01-19 16:34:16 +01004184 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004185
Eric Laurent81784c32012-11-19 14:55:58 -08004186 // prevent any changes in effect chain list and in each effect chain
4187 // during mixing and effect process as the audio buffers could be deleted
4188 // or modified if an effect is created or deleted
4189 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004190
4191 // Determine which session to pick up haptic data.
4192 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004193 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004194 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004195 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004196 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004197 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004198 if (effectChain != nullptr
4199 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004200 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004201 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004202 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004203 break;
4204 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004205 if (activeHapticSessionId == AUDIO_SESSION_NONE
4206 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004207 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004208 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004209 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004210 }
4211 }
4212 }
4213
Andy Hungc1646382019-04-30 16:12:10 -07004214 // Acquire a local copy of active tracks with lock (release w/o lock).
4215 //
4216 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4217 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4218 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4219 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004220
4221 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004222
Jiabin Huangfb476842022-12-06 03:18:10 +00004223 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004224 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004225 }
4226
Eric Laurent19952e12023-04-20 10:08:29 +02004227 // signal actual start of output stream when the render position reported by the kernel
4228 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004229 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4230 && (mKernelPositionOnStandby
4231 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004232 mHalStarted = true;
Andy Hungc5007f82023-08-29 14:26:09 -07004233 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004234 }
Andy Hungc5007f82023-08-29 14:26:09 -07004235 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004236
Eric Laurentbfb1b832013-01-07 09:53:42 -08004237 if (mBytesRemaining == 0) {
4238 mCurrentWriteLength = 0;
4239 if (mMixerStatus == MIXER_TRACKS_READY) {
4240 // threadLoop_mix() sets mCurrentWriteLength
4241 threadLoop_mix();
4242 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4243 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004244 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004245 // must be written to HAL
4246 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004247 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004248 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004249
4250 // Tally underrun frames as we are inserting 0s here.
4251 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004252 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004253 && !track->isStopped()
4254 && !track->isPaused()
4255 && !track->isTerminated()) {
4256 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4257 __func__, track->id(), track->getTrackStateAsString(),
4258 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004259 track->audioTrackServerProxy()->tallyUnderrunFrames(
4260 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004261 }
4262 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004263 }
4264 }
Andy Hung98ef9782014-03-04 14:46:50 -08004265 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004266 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004267 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004268 // or mSinkBuffer (if there are no effects and there is no data already copied to
4269 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004270 //
4271 // This is done pre-effects computation; if effects change to
4272 // support higher precision, this needs to move.
4273 //
4274 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004275 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004276 uint32_t mixerChannelCount = mEffectBufferValid ?
4277 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004278 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004279 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4280 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4281
David Li88ee0902022-06-22 10:01:21 +08004282 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4283 // do these processes after effects are applied.
4284 if (!mEffectBufferValid) {
4285 // mono blend occurs for mixer threads only (not direct or offloaded)
4286 // and is handled here if we're going directly to the sink.
4287 if (requireMonoBlend()) {
4288 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4289 mNormalFrameCount, true /*limit*/);
4290 }
Andy Hung2ddee192015-12-18 17:34:44 -08004291
David Li88ee0902022-06-22 10:01:21 +08004292 if (!hasFastMixer()) {
4293 // Balance must take effect after mono conversion.
4294 // We do it here if there is no FastMixer.
4295 // mBalance detects zero balance within the class for speed
4296 // (not needed here).
4297 mBalance.setBalance(mMasterBalance.load());
4298 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4299 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004300 }
4301
Andy Hung98ef9782014-03-04 14:46:50 -08004302 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004303 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004304
4305 // If we're going directly to the sink and there are haptic channels,
4306 // we should adjust channels as the sample data is partially interleaved
4307 // in this case.
4308 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4309 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4310 mChannelCount + mHapticChannelCount,
4311 audio_bytes_per_sample(format),
4312 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4313 }
Andy Hung98ef9782014-03-04 14:46:50 -08004314 }
4315
Eric Laurentbfb1b832013-01-07 09:53:42 -08004316 mBytesRemaining = mCurrentWriteLength;
4317 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004318 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4319 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4320 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4321 mBytesWritten += mBytesRemaining;
4322 mFramesWritten += framesRemaining;
4323 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324 mBytesRemaining = 0;
4325 }
Eric Laurent81784c32012-11-19 14:55:58 -08004326
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004328 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004329 for (size_t i = 0; i < effectChains.size(); i ++) {
4330 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004331 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004332 if (activeHapticSessionId != AUDIO_SESSION_NONE
4333 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004334 // Haptic data is active in this case, copy it directly from
4335 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004336 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4337 audio_channel_count_from_out_mask(mMixerChannelMask) :
4338 mChannelCount;
4339 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4340 hapticSessionChannelCount = mChannelCount;
4341 }
4342
jiabin47affe52019-04-04 18:02:07 -07004343 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004344 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004345 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004346 memcpy_by_audio_format(
4347 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004348 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004349 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004350 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004351 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004352 }
Eric Laurent81784c32012-11-19 14:55:58 -08004353 }
4354 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004355 // Process effect chains for offloaded thread even if no audio
4356 // was read from audio track: process only updates effect state
4357 // and thus does have to be synchronized with audio writes but may have
4358 // to be called while waiting for async write callback
4359 if (mType == OFFLOAD) {
4360 for (size_t i = 0; i < effectChains.size(); i ++) {
4361 effectChains[i]->process_l();
4362 }
4363 }
Eric Laurent81784c32012-11-19 14:55:58 -08004364
Andy Hung98ef9782014-03-04 14:46:50 -08004365 // Only if the Effects buffer is enabled and there is data in the
4366 // Effects buffer (buffer valid), we need to
4367 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004368 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004369 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004370 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004371 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004372 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004373 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004374 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004375 }
4376
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004377 if (!hasFastMixer()) {
4378 // Balance must take effect after mono conversion.
4379 // We do it here if there is no FastMixer.
4380 // mBalance detects zero balance within the class for speed (not needed here).
4381 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004382 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004383 }
4384
Eric Laurentb62d0362021-10-26 17:40:18 +02004385 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4386 // mPostSpatializerBuffer if the haptics track is spatialized.
4387 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4388 // For other thread types, the haptics channels are already in mEffectBuffer.
4389 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4390 const size_t srcBufferSize = mNormalFrameCount *
4391 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4392 mEffectBufferFormat);
4393 const size_t dstBufferSize = mNormalFrameCount
4394 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4395
4396 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4397 mEffectBufferFormat,
4398 (uint8_t*)mEffectBuffer + srcBufferSize,
4399 mEffectBufferFormat,
4400 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004401 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004402 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4403 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4404 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4405 // Clamp PCM float values more than this distance from 0 to insulate
4406 // a HAL which doesn't handle NaN correctly.
4407 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4408 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4409 static_cast<const float*>(effectBuffer),
4410 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4411 } else {
4412 memcpy_by_audio_format(mSinkBuffer, mFormat,
4413 effectBuffer, mEffectBufferFormat, framesToCopy);
4414 }
jiabin245cdd92018-12-07 17:55:15 -08004415 // The sample data is partially interleaved when haptic channels exist,
4416 // we need to adjust channels here.
4417 if (mHapticChannelCount > 0) {
4418 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4419 mChannelCount + mHapticChannelCount,
4420 audio_bytes_per_sample(mFormat),
4421 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4422 }
Andy Hung98ef9782014-03-04 14:46:50 -08004423 }
4424
Eric Laurent81784c32012-11-19 14:55:58 -08004425 // enable changes in effect chain
4426 unlockEffectChains(effectChains);
4427
Vlad Popafce10862023-02-03 10:37:07 +01004428 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004429 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004430 metadataUpdate.playbackMetadataUpdate);
4431 }
4432
Eric Laurentbfb1b832013-01-07 09:53:42 -08004433 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004434 // mSleepTimeUs == 0 means we must write to audio hardware
4435 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004436 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004437 // writePeriodNs is updated >= 0 when ret > 0.
4438 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004439 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004440 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004441 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004442 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004443 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004444 if (ret < 0) {
4445 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004446 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004447 mBytesWritten += ret;
4448 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004449 const int64_t frames = ret / mFrameSize;
4450 mFramesWritten += frames;
4451
4452 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4453 // process information relating to write time.
4454 if (audio_has_proportional_frames(mFormat)) {
4455 // we are in a continuous mixing cycle
4456 if (mMixerStatus == MIXER_TRACKS_READY &&
4457 loopCount == lastLoopCountWritten + 1) {
4458
4459 const double jitterMs =
4460 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4461 {frames, writePeriodNs},
4462 {0, 0} /* lastTimestamp */, mSampleRate);
4463 const double processMs =
4464 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4465
Andy Hung972bec12023-08-31 16:13:39 -07004466 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004467 mIoJitterMs.add(jitterMs);
4468 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004469
4470 if (mPipeSink.get() != nullptr) {
4471 // Using the Monopipe availableToWrite, we estimate the current
4472 // buffer size.
4473 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4474 const ssize_t
4475 availableToWrite = mPipeSink->availableToWrite();
4476 const size_t pipeFrames = monoPipe->maxFrames();
4477 const size_t
4478 remainingFrames = pipeFrames - max(availableToWrite, 0);
4479 mMonopipePipeDepthStats.add(remainingFrames);
4480 }
Andy Hung446f4df2019-02-21 12:26:41 -08004481 }
4482
4483 // write blocked detection
4484 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004485 if ((mType == MIXER || mType == SPATIALIZER)
4486 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004487 mNumDelayedWrites++;
4488 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4489 ATRACE_NAME("underrun");
4490 ALOGW("write blocked for %lld msecs, "
4491 "%d delayed writes, thread %d",
4492 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4493 mNumDelayedWrites, mId);
4494 lastWarning = lastIoEndNs;
4495 }
4496 }
4497 }
4498 // update timing info.
4499 mLastIoBeginNs = lastIoBeginNs;
4500 mLastIoEndNs = lastIoEndNs;
4501 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004502 }
4503 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4504 (mMixerStatus == MIXER_DRAIN_ALL)) {
4505 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004506 }
Andy Hungd3639922022-04-28 18:00:49 -07004507 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004508
4509 if (mThreadThrottle
4510 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004511 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004512 // Limit MixerThread data processing to no more than twice the
4513 // expected processing rate.
4514 //
4515 // This helps prevent underruns with NuPlayer and other applications
4516 // which may set up buffers that are close to the minimum size, or use
4517 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4518 //
4519 // The throttle smooths out sudden large data drains from the device,
4520 // e.g. when it comes out of standby, which often causes problems with
4521 // (1) mixer threads without a fast mixer (which has its own warm-up)
4522 // (2) minimum buffer sized tracks (even if the track is full,
4523 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004524 //
4525 // Total time spent in last processing cycle equals time spent in
4526 // 1. threadLoop_write, as well as time spent in
4527 // 2. threadLoop_mix (significant for heavy mixing, especially
4528 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004529
Andy Hung446f4df2019-02-21 12:26:41 -08004530 // it's OK if deltaMs is an overestimate.
4531
4532 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004533
Ivan Lozanoea04d392017-11-07 14:37:07 -08004534 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004535 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004536 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004537
Andy Hung08fb1742015-05-31 23:22:10 -07004538 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004539 // notify of throttle start on verbose log
4540 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4541 "mixer(%p) throttle begin:"
4542 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004543 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004544 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004545 // Throttle must be attributed to the previous mixer loop's write time
4546 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004547 // This also ensures proper timing statistics.
4548 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004549 } else {
4550 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4551 if (diff > 0) {
4552 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004553 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004554 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004555 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004556 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004557 outDeviceTypes_l(),
4558 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004559 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004560 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4561 }
Andy Hung08fb1742015-05-31 23:22:10 -07004562 }
4563 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564 }
Eric Laurent81784c32012-11-19 14:55:58 -08004565
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004567 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004568 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004569 // suspended requires accurate metering of sleep time.
4570 if (isSuspended()) {
4571 // advance by expected sleepTime
4572 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4573 const nsecs_t nowNs = systemTime();
4574
4575 // compute expected next time vs current time.
4576 // (negative deltas are treated as delays).
4577 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4578 if (deltaNs < -kMaxNextBufferDelayNs) {
4579 // Delays longer than the max allowed trigger a reset.
4580 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4581 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4582 timeLoopNextNs = nowNs + deltaNs;
4583 } else if (deltaNs < 0) {
4584 // Delays within the max delay allowed: zero the delta/sleepTime
4585 // to help the system catch up in the next iteration(s)
4586 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4587 deltaNs = 0;
4588 }
4589 // update sleep time (which is >= 0)
4590 mSleepTimeUs = deltaNs / 1000;
4591 }
Eric Laurente93cc032016-05-05 10:15:10 -07004592 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004593 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004594 }
Glenn Kastene7754022014-10-31 12:11:26 -07004595 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004596 }
Eric Laurent81784c32012-11-19 14:55:58 -08004597 }
4598
4599 // Finally let go of removed track(s), without the lock held
4600 // since we can't guarantee the destructors won't acquire that
4601 // same lock. This will also mutate and push a new fast mixer state.
4602 threadLoop_removeTracks(tracksToRemove);
4603 tracksToRemove.clear();
4604
4605 // FIXME I don't understand the need for this here;
4606 // it was in the original code but maybe the
4607 // assignment in saveOutputTracks() makes this unnecessary?
4608 clearOutputTracks();
4609
4610 // Effect chains will be actually deleted here if they were removed from
4611 // mEffectChains list during mixing or effects processing
4612 effectChains.clear();
4613
4614 // FIXME Note that the above .clear() is no longer necessary since effectChains
4615 // is now local to this block, but will keep it for now (at least until merge done).
4616 }
4617
Eric Laurentbfb1b832013-01-07 09:53:42 -08004618 threadLoop_exit();
4619
Eric Laurentcf817a22014-08-04 20:36:31 -07004620 if (!mStandby) {
4621 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004622 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004623 }
4624
4625 releaseWakeLock();
4626
4627 ALOGV("Thread %p type %d exiting", this, mType);
4628 return false;
4629}
4630
Andy Hungee58e4a2023-07-07 13:47:37 -07004631void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004632{
Dean Wheatley12473e92021-03-18 23:00:55 +11004633 if (mStandby) {
4634 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4635 return;
4636 } else if (mHwPaused) {
4637 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4638 return;
4639 }
4640
4641 // Gather the framesReleased counters for all active tracks,
4642 // and associate with the sink frames written out. We need
4643 // this to convert the sink timestamp to the track timestamp.
4644 bool kernelLocationUpdate = false;
4645 ExtendedTimestamp timestamp; // use private copy to fetch
4646
4647 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4648 // HAL may be draining some small duration buffered data for fade out.
4649 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4650 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4651 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4652 mSampleRate);
4653
Andy Hungab65b182023-09-06 19:41:47 -07004654 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004655 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4656 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4657 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4658 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4659 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4660 = correctedTimestamp.mFrames;
4661 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4662 = correctedTimestamp.mTimeNs;
4663 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4664 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4665 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4666
4667 // Note: Downstream latency only added if timestamp correction enabled.
4668 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4669 const int64_t newPosition =
4670 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4671 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4672 // prevent retrograde
4673 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4674 newPosition,
4675 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4676 - mSuspendedFrames));
4677 }
4678 }
4679
4680 // We always fetch the timestamp here because often the downstream
4681 // sink will block while writing.
4682
4683 // We keep track of the last valid kernel position in case we are in underrun
4684 // and the normal mixer period is the same as the fast mixer period, or there
4685 // is some error from the HAL.
4686 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4687 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4688 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4689 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4690 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4691
4692 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4693 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4694 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4695 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4696 }
4697
4698 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4699 kernelLocationUpdate = true;
4700 } else {
4701 ALOGVV("getTimestamp error - no valid kernel position");
4702 }
4703
4704 // copy over kernel info
4705 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4706 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4707 + mSuspendedFrames; // add frames discarded when suspended
4708 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4709 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4710 } else {
4711 mTimestampVerifier.error();
4712 }
4713
4714 // mFramesWritten for non-offloaded tracks are contiguous
4715 // even after standby() is called. This is useful for the track frame
4716 // to sink frame mapping.
4717 bool serverLocationUpdate = false;
4718 if (mFramesWritten != mLastFramesWritten) {
4719 serverLocationUpdate = true;
4720 mLastFramesWritten = mFramesWritten;
4721 }
4722 // Only update timestamps if there is a meaningful change.
4723 // Either the kernel timestamp must be valid or we have written something.
4724 if (kernelLocationUpdate || serverLocationUpdate) {
4725 if (serverLocationUpdate) {
4726 // use the time before we called the HAL write - it is a bit more accurate
4727 // to when the server last read data than the current time here.
4728 //
4729 // If we haven't written anything, mLastIoBeginNs will be -1
4730 // and we use systemTime().
4731 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4732 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004733 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004734 }
4735
Andy Hung8d31fd22023-06-26 19:20:57 -07004736 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004737 if (!t->isFastTrack()) {
4738 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004739 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004740 mFramesWritten,
4741 mSampleRate,
4742 mTimestamp);
4743 }
4744 }
4745 }
4746
4747 if (audio_has_proportional_frames(mFormat)) {
4748 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4749 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4750 mLatencyMs.add(latencyMs);
4751 }
4752 }
4753#if 0
4754 // logFormat example
4755 if (z % 100 == 0) {
4756 timespec ts;
4757 clock_gettime(CLOCK_MONOTONIC, &ts);
4758 LOGT("This is an integer %d, this is a float %f, this is my "
4759 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4760 LOGT("A deceptive null-terminated string %\0");
4761 }
4762 ++z;
4763#endif
4764}
4765
Andy Hungc5007f82023-08-29 14:26:09 -07004766// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004767void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004768NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004769{
Andy Hung6c498e92023-12-05 17:28:17 -08004770 if (tracksToRemove.empty()) return;
4771
4772 // Block all incoming TrackHandle requests until we are finished with the release.
4773 setThreadBusy_l(true);
4774
Andy Hungfe726a62018-09-27 15:17:25 -07004775 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004776 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004777 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004778 if (chain != 0) {
4779 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4780 __func__, track->id(), chain.get(), track->sessionId());
4781 chain->decActiveTrackCnt();
4782 }
Andy Hung6c498e92023-12-05 17:28:17 -08004783
Andy Hungfe726a62018-09-27 15:17:25 -07004784 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004785 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004786 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004787 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004788 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004789 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004790 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004791 }
Andy Hung6c498e92023-12-05 17:28:17 -08004792 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004793 }
jiabineb3bda02020-06-30 14:07:03 -07004794 if (mHapticChannelCount > 0 &&
4795 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4796 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004797 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004798 // Unlock due to VibratorService will lock for this call and will
4799 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004800 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004801 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004802
4803 // When the track is stop, set the haptic intensity as MUTE
4804 // for the HapticGenerator effect.
4805 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004806 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004807 }
jiabin245cdd92018-12-07 17:55:15 -08004808 }
Andy Hung6c498e92023-12-05 17:28:17 -08004809
4810 // Under lock, the track is removed from the active tracks list.
4811 //
4812 // Once the track is no longer active, the TrackHandle may directly
4813 // modify it as the threadLoop() is no longer responsible for its maintenance.
4814 // Do not modify the track from threadLoop after the mutex is unlocked
4815 // if it is not active.
4816 mActiveTracks.remove(track);
4817
4818 if (track->isTerminated()) {
4819 // remove from our tracks vector
4820 removeTrack_l(track);
4821 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004822 }
Andy Hung6c498e92023-12-05 17:28:17 -08004823
4824 // Allow incoming TrackHandle requests. We still hold the mutex,
4825 // so pending TrackHandle requests will occur after we unlock it.
4826 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004827}
Eric Laurent81784c32012-11-19 14:55:58 -08004828
Andy Hungee58e4a2023-07-07 13:47:37 -07004829status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004830{
4831 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004832 ExtendedTimestamp ets;
4833 status_t status = mNormalSink->getTimestamp(ets);
4834 if (status == NO_ERROR) {
4835 status = ets.getBestTimestamp(&timestamp);
4836 }
4837 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004838 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004839 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004840 collectTimestamps_l();
4841 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4842 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004843 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004844 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4845 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4846 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4847 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4848 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004849 }
4850 return INVALID_OPERATION;
4851}
Eric Laurent1c333e22014-05-20 10:48:17 -07004852
Eric Laurenteab90452019-06-24 15:17:46 -07004853// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4854// still applied by the mixer.
4855// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4856// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4857// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004858status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004859{
4860 status_t result = NO_ERROR;
4861 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4862 if (*volume != mLeftVolFloat) {
4863 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004864 // HAL can return INVALID_OPERATION if operation is not supported.
4865 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004866 "Error when setting output stream volume: %d", result);
4867 if (result == NO_ERROR) {
4868 mLeftVolFloat = *volume;
4869 }
4870 }
4871 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4872 // remove stream volume contribution from software volume.
4873 if (mLeftVolFloat == *volume) {
4874 *volume = 1.0f;
4875 }
4876 }
4877 return result;
4878}
4879
Andy Hungee58e4a2023-07-07 13:47:37 -07004880status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004881 audio_patch_handle_t *handle)
4882{
Andy Hungf60abce2016-08-26 11:37:54 -07004883 status_t status;
4884 if (property_get_bool("af.patch_park", false /* default_value */)) {
4885 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4886 // or if HAL does not properly lock against access.
4887 AutoPark<FastMixer> park(mFastMixer);
4888 status = PlaybackThread::createAudioPatch_l(patch, handle);
4889 } else {
4890 status = PlaybackThread::createAudioPatch_l(patch, handle);
4891 }
Eric Laurentb0463942022-12-20 16:31:10 +01004892
4893 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004894 return status;
4895}
4896
Andy Hungee58e4a2023-07-07 13:47:37 -07004897status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004898 audio_patch_handle_t *handle)
4899{
4900 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004901
4902 // store new device and send to effects
4903 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004904 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004905 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004906 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4907 && !mOutput->audioHwDev->supportsAudioPatches(),
4908 "Enumerated device type(%#x) must not be used "
4909 "as it does not support audio patches",
4910 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004911 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004912 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4913 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004914 }
4915
François Gaffie0c280aa2018-07-25 10:02:15 +02004916 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004917#ifdef ADD_BATTERY_DATA
4918 // when changing the audio output device, call addBatteryData to notify
4919 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004920 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004921 uint32_t params = 0;
4922 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004923 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004924 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004925 }
4926
Eric Laurent054d9d32015-04-24 08:48:48 -07004927 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004928 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004929 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4930 }
4931
4932 if (params != 0) {
4933 addBatteryData(params);
4934 }
4935 }
4936#endif
4937
4938 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004939 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004940 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004941
jiabinc52b1ff2019-10-31 17:20:42 -07004942 // mPatch.num_sinks is not set when the thread is created so that
4943 // the first patch creation triggers an ioConfigChanged callback
4944 bool configChanged = (mPatch.num_sinks == 0) ||
4945 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004946 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004947 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004948 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004949
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004950 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004951 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4952 status = hwDevice->createAudioPatch(patch->num_sources,
4953 patch->sources,
4954 patch->num_sinks,
4955 patch->sinks,
4956 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004957 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004958 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004959 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004960 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004961 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004962
4963 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004964 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004965 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004966 // also dispatch to active AudioTracks for MediaMetrics
4967 for (const auto &track : mActiveTracks) {
4968 track->logEndInterval();
4969 track->logBeginInterval(patchSinksAsString);
4970 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004971
Eric Laurente8726fe2015-06-26 09:39:24 -07004972 if (configChanged) {
4973 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4974 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004975 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004976 mActiveTracks.setHasChanged();
4977
Eric Laurent1c333e22014-05-20 10:48:17 -07004978 return status;
4979}
4980
Andy Hungee58e4a2023-07-07 13:47:37 -07004981status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004982{
Andy Hungf60abce2016-08-26 11:37:54 -07004983 status_t status;
4984 if (property_get_bool("af.patch_park", false /* default_value */)) {
4985 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4986 // or if HAL does not properly lock against access.
4987 AutoPark<FastMixer> park(mFastMixer);
4988 status = PlaybackThread::releaseAudioPatch_l(handle);
4989 } else {
4990 status = PlaybackThread::releaseAudioPatch_l(handle);
4991 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004992 return status;
4993}
4994
Andy Hungee58e4a2023-07-07 13:47:37 -07004995status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004996{
4997 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004998
jiabinc52b1ff2019-10-31 17:20:42 -07004999 mPatch = audio_patch{};
5000 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005001
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005002 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005003 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5004 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005005 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005006 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005007 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005008 // Force meteadata update after a route change
5009 mActiveTracks.setHasChanged();
5010
Eric Laurent1c333e22014-05-20 10:48:17 -07005011 return status;
5012}
5013
Andy Hungee58e4a2023-07-07 13:47:37 -07005014void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005015{
Andy Hung972bec12023-08-31 16:13:39 -07005016 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005017 mTracks.add(track);
5018}
5019
Andy Hungee58e4a2023-07-07 13:47:37 -07005020void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005021{
Andy Hung972bec12023-08-31 16:13:39 -07005022 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005023 destroyTrack_l(track);
5024}
5025
Andy Hungee58e4a2023-07-07 13:47:37 -07005026void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005027{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005028 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005029 config->role = AUDIO_PORT_ROLE_SOURCE;
5030 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5031 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005032 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5033 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5034 config->flags.output = mOutput->flags;
5035 }
Eric Laurent83b88082014-06-20 18:31:16 -07005036}
5037
Eric Laurent81784c32012-11-19 14:55:58 -08005038// ----------------------------------------------------------------------------
5039
Andy Hungee58e4a2023-07-07 13:47:37 -07005040/* static */
5041sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005042 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005043 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005044 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005045}
5046
Andy Hung583043b2023-07-17 17:05:00 -07005047MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005048 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005049 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005050 // mAudioMixer below
5051 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005052 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005053 mFastMixerFutex(0),
5054 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005055 // mOutputSink below
5056 // mPipeSink below
5057 // mNormalSink below
5058{
Andy Hung583043b2023-07-17 17:05:00 -07005059 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005060 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005061 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005062 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005063 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5064 mNormalFrameCount);
5065 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5066
Andy Hungfbfc3952015-01-15 13:33:51 -08005067 if (type == DUPLICATING) {
5068 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5069 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5070 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5071 return;
5072 }
Eric Laurent81784c32012-11-19 14:55:58 -08005073 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005074 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005075 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005076 const NBAIO_Format offers[1] = {Format_from_SR_C(
5077 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005078#if !LOG_NDEBUG
5079 ssize_t index =
5080#else
5081 (void)
5082#endif
5083 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005084 ALOG_ASSERT(index == 0);
5085
5086 // initialize fast mixer depending on configuration
5087 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005088 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005090 } else {
5091 switch (kUseFastMixer) {
5092 case FastMixer_Never:
5093 initFastMixer = false;
5094 break;
5095 case FastMixer_Always:
5096 initFastMixer = true;
5097 break;
5098 case FastMixer_Static:
5099 case FastMixer_Dynamic:
5100 initFastMixer = mFrameCount < mNormalFrameCount;
5101 break;
5102 }
5103 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5104 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5105 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005106 }
5107 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005108 audio_format_t fastMixerFormat;
5109 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5110 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5111 } else {
5112 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5113 }
5114 if (mFormat != fastMixerFormat) {
5115 // change our Sink format to accept our intermediate precision
5116 mFormat = fastMixerFormat;
5117 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005118 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005119 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5120 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5121 }
Eric Laurent81784c32012-11-19 14:55:58 -08005122
5123 // create a MonoPipe to connect our submix to FastMixer
5124 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005125
Andy Hung1258c1a2014-05-23 21:22:17 -07005126 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005127 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005128 format.mFormat = fastMixerFormat;
5129 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5130
Eric Laurent81784c32012-11-19 14:55:58 -08005131 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5132 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5133 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5134 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005135 const NBAIO_Format offersFast[1] = {format};
5136 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005137#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005138 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005139#else
5140 (void)
5141#endif
Andy Hung920f6572022-10-06 12:09:49 -07005142 monoPipe->negotiate(offersFast, std::size(offersFast),
5143 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005144 ALOG_ASSERT(index == 0);
5145 monoPipe->setAvgFrames((mScreenState & 1) ?
5146 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5147 mPipeSink = monoPipe;
5148
Eric Laurent81784c32012-11-19 14:55:58 -08005149 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005150 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005151 FastMixerStateQueue *sq = mFastMixer->sq();
5152#ifdef STATE_QUEUE_DUMP
5153 sq->setObserverDump(&mStateQueueObserverDump);
5154 sq->setMutatorDump(&mStateQueueMutatorDump);
5155#endif
5156 FastMixerState *state = sq->begin();
5157 FastTrack *fastTrack = &state->mFastTracks[0];
5158 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5159 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5160 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005161 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5162 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5163 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005164 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005165 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005166 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005167 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005168 fastTrack->mGeneration++;
5169 state->mFastTracksGen++;
5170 state->mTrackMask = 1;
5171 // fast mixer will use the HAL output sink
5172 state->mOutputSink = mOutputSink.get();
5173 state->mOutputSinkGen++;
5174 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005175 // specify sink channel mask when haptic channel mask present as it can not
5176 // be calculated directly from channel count
5177 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005178 ? AUDIO_CHANNEL_NONE
5179 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005180 state->mCommand = FastMixerState::COLD_IDLE;
5181 // already done in constructor initialization list
5182 //mFastMixerFutex = 0;
5183 state->mColdFutexAddr = &mFastMixerFutex;
5184 state->mColdGen++;
5185 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005186 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005187 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005188 sq->end();
5189 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5190
Eric Tan0513b5d2018-09-17 10:32:48 -07005191 NBLog::thread_info_t info;
5192 info.id = mId;
5193 info.type = NBLog::FASTMIXER;
5194 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5195
Eric Laurent81784c32012-11-19 14:55:58 -08005196 // start the fast mixer
5197 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5198 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005199 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005200 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005201
5202#ifdef AUDIO_WATCHDOG
5203 // create and start the watchdog
5204 mAudioWatchdog = new AudioWatchdog();
5205 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5206 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5207 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005208 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005209#endif
Andy Hung8946a282018-04-19 20:04:56 -07005210 } else {
5211#ifdef TEE_SINK
5212 // Only use the MixerThread tee if there is no FastMixer.
5213 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5214 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5215#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005216 }
5217
5218 switch (kUseFastMixer) {
5219 case FastMixer_Never:
5220 case FastMixer_Dynamic:
5221 mNormalSink = mOutputSink;
5222 break;
5223 case FastMixer_Always:
5224 mNormalSink = mPipeSink;
5225 break;
5226 case FastMixer_Static:
5227 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5228 break;
5229 }
5230}
5231
Andy Hungee58e4a2023-07-07 13:47:37 -07005232MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005233{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005234 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005235 FastMixerStateQueue *sq = mFastMixer->sq();
5236 FastMixerState *state = sq->begin();
5237 if (state->mCommand == FastMixerState::COLD_IDLE) {
5238 int32_t old = android_atomic_inc(&mFastMixerFutex);
5239 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005240 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005241 }
5242 }
5243 state->mCommand = FastMixerState::EXIT;
5244 sq->end();
5245 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5246 mFastMixer->join();
5247 // Though the fast mixer thread has exited, it's state queue is still valid.
5248 // We'll use that extract the final state which contains one remaining fast track
5249 // corresponding to our sub-mix.
5250 state = sq->begin();
5251 ALOG_ASSERT(state->mTrackMask == 1);
5252 FastTrack *fastTrack = &state->mFastTracks[0];
5253 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5254 delete fastTrack->mBufferProvider;
5255 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005256 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005257#ifdef AUDIO_WATCHDOG
5258 if (mAudioWatchdog != 0) {
5259 mAudioWatchdog->requestExit();
5260 mAudioWatchdog->requestExitAndWait();
5261 mAudioWatchdog.clear();
5262 }
5263#endif
5264 }
Andy Hung583043b2023-07-17 17:05:00 -07005265 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005266 delete mAudioMixer;
5267}
5268
Andy Hungee58e4a2023-07-07 13:47:37 -07005269void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005270 PlaybackThread::onFirstRef();
5271
Andy Hung972bec12023-08-31 16:13:39 -07005272 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005273 if (mOutput != nullptr && mOutput->stream != nullptr) {
5274 status_t status = mOutput->stream->setLatencyModeCallback(this);
5275 if (status != INVALID_OPERATION) {
5276 updateHalSupportedLatencyModes_l();
5277 }
5278 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5279 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5280 mBluetoothLatencyModesEnabled.store(
5281 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5282 }
5283}
Eric Laurent81784c32012-11-19 14:55:58 -08005284
Andy Hungee58e4a2023-07-07 13:47:37 -07005285uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005286{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005287 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005288 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5289 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5290 }
5291 return latency;
5292}
5293
Andy Hungee58e4a2023-07-07 13:47:37 -07005294ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005295{
5296 // FIXME we should only do one push per cycle; confirm this is true
5297 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005298 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005299 FastMixerStateQueue *sq = mFastMixer->sq();
5300 FastMixerState *state = sq->begin();
5301 if (state->mCommand != FastMixerState::MIX_WRITE &&
5302 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5303 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005304
5305 // FIXME workaround for first HAL write being CPU bound on some devices
5306 ATRACE_BEGIN("write");
5307 mOutput->write((char *)mSinkBuffer, 0);
5308 ATRACE_END();
5309
Eric Laurent81784c32012-11-19 14:55:58 -08005310 int32_t old = android_atomic_inc(&mFastMixerFutex);
5311 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005312 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005313 }
5314#ifdef AUDIO_WATCHDOG
5315 if (mAudioWatchdog != 0) {
5316 mAudioWatchdog->resume();
5317 }
5318#endif
5319 }
5320 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005321#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005322 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005323 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005324#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005325 sq->end();
5326 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5327 if (kUseFastMixer == FastMixer_Dynamic) {
5328 mNormalSink = mPipeSink;
5329 }
5330 } else {
5331 sq->end(false /*didModify*/);
5332 }
5333 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005335}
5336
Andy Hungee58e4a2023-07-07 13:47:37 -07005337void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005338{
5339 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005340 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005341 FastMixerStateQueue *sq = mFastMixer->sq();
5342 FastMixerState *state = sq->begin();
5343 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005344 // Report any frames trapped in the Monopipe
5345 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5346 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5347 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5348 "monoPipeWritten:%lld monoPipeLeft:%lld",
5349 (long long)mFramesWritten, (long long)mSuspendedFrames,
5350 (long long)mPipeSink->framesWritten(), pipeFrames);
5351 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5352
Eric Laurent81784c32012-11-19 14:55:58 -08005353 state->mCommand = FastMixerState::COLD_IDLE;
5354 state->mColdFutexAddr = &mFastMixerFutex;
5355 state->mColdGen++;
5356 mFastMixerFutex = 0;
5357 sq->end();
5358 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5359 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5360 if (kUseFastMixer == FastMixer_Dynamic) {
5361 mNormalSink = mOutputSink;
5362 }
5363#ifdef AUDIO_WATCHDOG
5364 if (mAudioWatchdog != 0) {
5365 mAudioWatchdog->pause();
5366 }
5367#endif
5368 } else {
5369 sq->end(false /*didModify*/);
5370 }
5371 }
5372 PlaybackThread::threadLoop_standby();
5373}
5374
Andy Hungee58e4a2023-07-07 13:47:37 -07005375bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376{
5377 return false;
5378}
5379
Andy Hungee58e4a2023-07-07 13:47:37 -07005380bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005381{
5382 return !mStandby;
5383}
5384
Andy Hungee58e4a2023-07-07 13:47:37 -07005385bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005386{
Andy Hung972bec12023-08-31 16:13:39 -07005387 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388 return waitingAsyncCallback_l();
5389}
5390
Eric Laurent81784c32012-11-19 14:55:58 -08005391// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005392void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005393{
Andy Hung8d672e02023-09-15 18:19:28 -07005394 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5395 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005396 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005398 // discard any pending drain or write ack by incrementing sequence
5399 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5400 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005402 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5403 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005404 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005405 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005406 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005407}
5408
Andy Hungee58e4a2023-07-07 13:47:37 -07005409void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005410{
5411 ALOGV("signal playback thread");
5412 broadcast_l();
5413}
5414
Andy Hungee58e4a2023-07-07 13:47:37 -07005415void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005416{
5417 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5418 invalidateTracks((audio_stream_type_t)i);
5419 }
5420}
5421
Andy Hungee58e4a2023-07-07 13:47:37 -07005422void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005423{
Eric Laurent81784c32012-11-19 14:55:58 -08005424 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005425 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005426 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005427 // increase sleep time progressively when application underrun condition clears.
5428 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5429 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5430 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005431 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005432 sleepTimeShift--;
5433 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005434 mSleepTimeUs = 0;
5435 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005436 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005437
Eric Laurent81784c32012-11-19 14:55:58 -08005438}
5439
Andy Hungee58e4a2023-07-07 13:47:37 -07005440void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005441{
5442 // If no tracks are ready, sleep once for the duration of an output
5443 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005444 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005445 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005446 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5447 // Using the Monopipe availableToWrite, we estimate the
5448 // sleep time to retry for more data (before we underrun).
5449 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5450 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5451 const size_t pipeFrames = monoPipe->maxFrames();
5452 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5453 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5454 const size_t framesDelay = std::min(
5455 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5456 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5457 pipeFrames, framesLeft, framesDelay);
5458 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5459 } else {
5460 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5461 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5462 mSleepTimeUs = kMinThreadSleepTimeUs;
5463 }
5464 // reduce sleep time in case of consecutive application underruns to avoid
5465 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5466 // duration we would end up writing less data than needed by the audio HAL if
5467 // the condition persists.
5468 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5469 sleepTimeShift++;
5470 }
Eric Laurent81784c32012-11-19 14:55:58 -08005471 }
5472 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005473 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005474 }
5475 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005476 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5477 // before effects processing or output.
5478 if (mMixerBufferValid) {
5479 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005480 if (mType == SPATIALIZER) {
5481 memset(mSinkBuffer, 0, mSinkBufferSize);
5482 }
Andy Hung98ef9782014-03-04 14:46:50 -08005483 } else {
5484 memset(mSinkBuffer, 0, mSinkBufferSize);
5485 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005486 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005487 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5488 "anticipated start");
5489 }
5490 // TODO add standby time extension fct of effect tail
5491}
5492
Andy Hungc5007f82023-08-29 14:26:09 -07005493// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005494PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005495 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005496{
Andy Hungc0691382018-09-12 18:01:57 -07005497 // clean up deleted track ids in AudioMixer before allocating new tracks
5498 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5499 // for each trackId, destroy it in the AudioMixer
5500 if (mAudioMixer->exists(trackId)) {
5501 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005502 }
5503 });
Andy Hungc0691382018-09-12 18:01:57 -07005504 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005505
5506 mixer_state mixerStatus = MIXER_IDLE;
5507 // find out which tracks need to be processed
5508 size_t count = mActiveTracks.size();
5509 size_t mixedTracks = 0;
5510 size_t tracksWithEffect = 0;
5511 // counts only _active_ fast tracks
5512 size_t fastTracks = 0;
5513 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5514
5515 float masterVolume = mMasterVolume;
5516 bool masterMute = mMasterMute;
5517
5518 if (masterMute) {
5519 masterVolume = 0;
5520 }
5521 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005522 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005523 if (chain != 0) {
5524 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005525 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005526 masterVolume = (float)((v + (1 << 23)) >> 24);
5527 chain.clear();
5528 }
5529
5530 // prepare a new state to push
5531 FastMixerStateQueue *sq = NULL;
5532 FastMixerState *state = NULL;
5533 bool didModify = false;
5534 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005535 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005536 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005537 sq = mFastMixer->sq();
5538 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005539 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005540 }
5541
Andy Hung69aed5f2014-02-25 17:24:40 -08005542 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005543 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005544
Andy Hungbd3b2b02018-05-21 10:53:11 -07005545 // DeferredOperations handles statistics after setting mixerStatus.
5546 class DeferredOperations {
5547 public:
Andy Hungea840382020-05-05 21:50:17 -07005548 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5549 : mMixerStatus(mixerStatus)
5550 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005551
5552 // when leaving scope, tally frames properly.
5553 ~DeferredOperations() {
5554 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5555 // because that is when the underrun occurs.
5556 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005557 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005558 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005559 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005560 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005561 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005562 }
5563 }
Andy Hungea840382020-05-05 21:50:17 -07005564 // send the max underrun frames for this mixer period
5565 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005566 }
5567
5568 // tallyUnderrunFrames() is called to update the track counters
5569 // with the number of underrun frames for a particular mixer period.
5570 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005571 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005572 mUnderrunFrames.emplace_back(track, underrunFrames);
5573 }
5574
5575 private:
5576 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005577 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005578 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005579 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005580 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005581
jiabin245cdd92018-12-07 17:55:15 -08005582 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005583 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005584 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005585
5586 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005587 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005588
5589 // process fast tracks
5590 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005591 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5592 "%s(%d): FastTrack(%d) present without FastMixer",
5593 __func__, id(), track->id());
5594
jiabin245cdd92018-12-07 17:55:15 -08005595 if (track->getHapticPlaybackEnabled()) {
5596 noFastHapticTrack = false;
5597 }
Eric Laurent81784c32012-11-19 14:55:58 -08005598
5599 // It's theoretically possible (though unlikely) for a fast track to be created
5600 // and then removed within the same normal mix cycle. This is not a problem, as
5601 // the track never becomes active so it's fast mixer slot is never touched.
5602 // The converse, of removing an (active) track and then creating a new track
5603 // at the identical fast mixer slot within the same normal mix cycle,
5604 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005605 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005606 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005607 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5608 FastTrack *fastTrack = &state->mFastTracks[j];
5609
5610 // Determine whether the track is currently in underrun condition,
5611 // and whether it had a recent underrun.
5612 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5613 FastTrackUnderruns underruns = ftDump->mUnderruns;
5614 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005615 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005616 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005617 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005618 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005619 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005620 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005621 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005622 // don't count underruns that occur while stopping or pausing
5623 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005624 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005625 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5626 recentUnderruns > 0) {
5627 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005628 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005629 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005630 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005631 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005632
5633 // This is similar to the state machine for normal tracks,
5634 // with a few modifications for fast tracks.
5635 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005636 switch (track->state()) {
5637 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005638 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005639 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005640 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005641 }
5642 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005643 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005644 // ramp down is not yet implemented
5645 track->setPaused();
5646 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005647 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005648 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005649 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005650 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005651 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005652 if (recentFull > 0 || recentPartial > 0) {
5653 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005654 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005655 }
5656 if (recentUnderruns == 0) {
5657 // no recent underruns: stay active
5658 break;
5659 }
5660 // there has recently been an underrun of some kind
5661 if (track->sharedBuffer() == 0) {
5662 // were any of the recent underruns "empty" (no frames available)?
5663 if (recentEmpty == 0) {
5664 // no, then ignore the partial underruns as they are allowed indefinitely
5665 break;
5666 }
5667 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005668 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005669 break;
5670 }
5671 // indicate to client process that the track was disabled because of underrun;
5672 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005673 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005674 // remove from active list, but state remains ACTIVE [confusing but true]
5675 isActive = false;
5676 break;
5677 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005678 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005679 case IAfTrackBase::STOPPING_2:
5680 case IAfTrackBase::PAUSED:
5681 case IAfTrackBase::STOPPED:
5682 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005683 // Check for presentation complete if track is inactive
5684 // We have consumed all the buffers of this track.
5685 // This would be incomplete if we auto-paused on underrun
5686 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005687 uint32_t latency = 0;
5688 status_t result = mOutput->stream->getLatency(&latency);
5689 ALOGE_IF(result != OK,
5690 "Error when retrieving output stream latency: %d", result);
5691 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005692 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005693 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5694 // track stays in active list until presentation is complete
5695 break;
5696 }
5697 }
5698 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005699 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005700 }
5701 if (track->isStopped()) {
5702 // Can't reset directly, as fast mixer is still polling this track
5703 // track->reset();
5704 // So instead mark this track as needing to be reset after push with ack
5705 resetMask |= 1 << i;
5706 }
5707 isActive = false;
5708 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005709 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005710 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005711 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005712 }
5713
5714 if (isActive) {
5715 // was it previously inactive?
5716 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005717 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5718 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005719 fastTrack->mBufferProvider = eabp;
5720 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005721 fastTrack->mChannelMask = track->channelMask();
5722 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005723 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005724 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005725 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005726 fastTrack->mGeneration++;
5727 state->mTrackMask |= 1 << j;
5728 didModify = true;
5729 // no acknowledgement required for newly active tracks
5730 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005731 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005732 float volume;
5733 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5734 volume = 0.f;
5735 } else {
5736 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5737 }
5738
5739 handleVoipVolume_l(&volume);
5740
Eric Laurent81784c32012-11-19 14:55:58 -08005741 // cache the combined master volume and stream type volume for fast mixer; this
5742 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005743 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005744 proxy->framesReleased()).first;
5745 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005746 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005747 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005748 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5749 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5750
Andy Hung583043b2023-07-17 17:05:00 -07005751 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005752 /*muteState=*/{masterVolume == 0.f,
5753 mStreamTypes[track->streamType()].volume == 0.f,
5754 mStreamTypes[track->streamType()].mute,
5755 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005756 vlf == 0.f && vrf == 0.f,
5757 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005758
5759 vlf *= volume;
5760 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005761
jiabin76d94692022-12-15 21:51:21 +00005762 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005763 ++fastTracks;
5764 } else {
5765 // was it previously active?
5766 if (state->mTrackMask & (1 << j)) {
5767 fastTrack->mBufferProvider = NULL;
5768 fastTrack->mGeneration++;
5769 state->mTrackMask &= ~(1 << j);
5770 didModify = true;
5771 // If any fast tracks were removed, we must wait for acknowledgement
5772 // because we're about to decrement the last sp<> on those tracks.
5773 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5774 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005775 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5776 // AudioTrack may start (which may not be with a start() but with a write()
5777 // after underrun) and immediately paused or released. In that case the
5778 // FastTrack state hasn't had time to update.
5779 // TODO Remove the ALOGW when this theory is confirmed.
5780 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005781 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005782 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005783 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005784 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005785 }
5786 tracksToRemove->add(track);
5787 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005788 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005789 }
jiabin245cdd92018-12-07 17:55:15 -08005790 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5791 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5792 didModify = true;
5793 }
Eric Laurent81784c32012-11-19 14:55:58 -08005794 continue;
5795 }
5796
5797 { // local variable scope to avoid goto warning
5798
5799 audio_track_cblk_t* cblk = track->cblk();
5800
5801 // The first time a track is added we wait
5802 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005803 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005804
5805 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005806 // use the trackId as the AudioMixer name.
5807 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005808 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005809 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005810 track->channelMask(),
5811 track->format(),
5812 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005813 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005814 ALOGW("%s(): AudioMixer cannot create track(%d)"
5815 " mask %#x, format %#x, sessionId %d",
5816 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005817 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005818 tracksToRemove->add(track);
5819 track->invalidate(); // consider it dead.
5820 continue;
5821 }
5822 }
5823
Eric Laurent81784c32012-11-19 14:55:58 -08005824 // make sure that we have enough frames to mix one full buffer.
5825 // enforce this condition only once to enable draining the buffer in case the client
5826 // app does not call stop() and relies on underrun to stop:
5827 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5828 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005829 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005830 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5831 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005832
5833 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005834 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005835 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5836 // add frames already consumed but not yet released by the resampler
5837 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005838 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005839
Eric Laurent81784c32012-11-19 14:55:58 -08005840 uint32_t minFrames = 1;
5841 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5842 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005843 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005844 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005845
5846 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005847 if (ATRACE_ENABLED()) {
5848 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005849 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005850 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005851 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005852 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005853 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005854 !track->isPaused() && !track->isTerminated())
5855 {
Andy Hungc0691382018-09-12 18:01:57 -07005856 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005857
5858 mixedTracks++;
5859
Shunkai Yaof4847652024-01-12 00:25:20 +00005860 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005861 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005862 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005863 if (track->mainBuffer() != mSinkBuffer &&
5864 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005865 if (mEffectBufferEnabled) {
5866 mEffectBufferValid = true; // Later can set directly.
5867 }
Eric Laurent81784c32012-11-19 14:55:58 -08005868 chain = getEffectChain_l(track->sessionId());
5869 // Delegate volume control to effect in track effect chain if needed
5870 if (chain != 0) {
5871 tracksWithEffect++;
5872 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005873 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005874 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005875 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005876 }
5877 }
5878
5879
5880 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005881 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005882 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005883 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5884 if (track->state() == IAfTrackBase::RESUMING) {
5885 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005886 // If a new track is paused immediately after start, do not ramp on resume.
5887 if (cblk->mServer != 0) {
5888 param = AudioMixer::RAMP_VOLUME;
5889 }
Eric Laurent81784c32012-11-19 14:55:58 -08005890 }
Andy Hungc0691382018-09-12 18:01:57 -07005891 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005892 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005893 // FIXME should not make a decision based on mServer
5894 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005895 // If the track is stopped before the first frame was mixed,
5896 // do not apply ramp
5897 param = AudioMixer::RAMP_VOLUME;
5898 }
5899
5900 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005901 uint32_t vl, vr; // in U8.24 integer format
5902 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005903 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005904 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005905 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005906 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005907 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005908 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005909
Eric Laurenteab90452019-06-24 15:17:46 -07005910 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5911 v = 0;
5912 }
5913
5914 handleVoipVolume_l(&v);
5915
5916 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005917 vl = vr = 0;
5918 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005919 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005920 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005921 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005922 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5923 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005924 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005925 if (vlf > GAIN_FLOAT_UNITY) {
5926 ALOGV("Track left volume out of range: %.3g", vlf);
5927 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005928 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005929 if (vrf > GAIN_FLOAT_UNITY) {
5930 ALOGV("Track right volume out of range: %.3g", vrf);
5931 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005932 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005933
Andy Hung583043b2023-07-17 17:05:00 -07005934 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005935 /*muteState=*/{masterVolume == 0.f,
5936 mStreamTypes[track->streamType()].volume == 0.f,
5937 mStreamTypes[track->streamType()].mute,
5938 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005939 vlf == 0.f && vrf == 0.f,
5940 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005941
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005942 // now apply the master volume and stream type volume and shaper volume
5943 vlf *= v * vh;
5944 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005945 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005946 // then derive vl and vr as U8.24 versions for the effect chain
5947 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5948 vl = (uint32_t) (scaleto8_24 * vlf);
5949 vr = (uint32_t) (scaleto8_24 * vrf);
5950 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005951 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005952 // send level comes from shared memory and so may be corrupt
5953 if (sendLevel > MAX_GAIN_INT) {
5954 ALOGV("Track send level out of range: %04X", sendLevel);
5955 sendLevel = MAX_GAIN_INT;
5956 }
Andy Hung6be49402014-05-30 10:42:03 -07005957 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5958 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005960
jiabin76d94692022-12-15 21:51:21 +00005961 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005962
Eric Laurent81784c32012-11-19 14:55:58 -08005963 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00005964 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005965 // Do not ramp volume if volume is controlled by effect
5966 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005967 // Update remaining floating point volume levels
5968 vlf = (float)vl / (1 << 24);
5969 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005970 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005971 } else {
5972 // force no volume ramp when volume controller was just disabled or removed
5973 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005974 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005975 param = AudioMixer::VOLUME;
5976 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005977 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005978 }
5979
Eric Laurent81784c32012-11-19 14:55:58 -08005980 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005981 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005982 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005983
Andy Hungc0691382018-09-12 18:01:57 -07005984 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5985 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5986 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005987 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005988 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005989 AudioMixer::TRACK,
5990 AudioMixer::FORMAT, (void *)track->format());
5991 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005992 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005993 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005994 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005995
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005996 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005997 mAudioMixer->setParameter(
5998 trackId,
5999 AudioMixer::TRACK,
6000 AudioMixer::MIXER_CHANNEL_MASK,
6001 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6002 } else {
6003 mAudioMixer->setParameter(
6004 trackId,
6005 AudioMixer::TRACK,
6006 AudioMixer::MIXER_CHANNEL_MASK,
6007 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6008 }
6009
Glenn Kastene3aa6592012-12-04 12:22:46 -08006010 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006011 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006012 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006013 if (reqSampleRate == 0) {
6014 reqSampleRate = mSampleRate;
6015 } else if (reqSampleRate > maxSampleRate) {
6016 reqSampleRate = maxSampleRate;
6017 }
Eric Laurent81784c32012-11-19 14:55:58 -08006018 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006019 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006020 AudioMixer::RESAMPLE,
6021 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006022 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006023
Andy Hung8edb8dc2015-03-26 19:13:55 -07006024 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006025 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006026 AudioMixer::TIMESTRETCH,
6027 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006028 // cast away constness for this generic API.
6029 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006030
Andy Hung69aed5f2014-02-25 17:24:40 -08006031 /*
6032 * Select the appropriate output buffer for the track.
6033 *
Andy Hung98ef9782014-03-04 14:46:50 -08006034 * Tracks with effects go into their own effects chain buffer
6035 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006036 *
6037 * Other tracks can use mMixerBuffer for higher precision
6038 * channel accumulation. If this buffer is enabled
6039 * (mMixerBufferEnabled true), then selected tracks will accumulate
6040 * into it.
6041 *
6042 */
6043 if (mMixerBufferEnabled
6044 && (track->mainBuffer() == mSinkBuffer
6045 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006046 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006047 mAudioMixer->setParameter(
6048 trackId,
6049 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006050 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006051 mAudioMixer->setParameter(
6052 trackId,
6053 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006054 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006055 } else {
6056 mAudioMixer->setParameter(
6057 trackId,
6058 AudioMixer::TRACK,
6059 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6060 mAudioMixer->setParameter(
6061 trackId,
6062 AudioMixer::TRACK,
6063 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6064 // TODO: override track->mainBuffer()?
6065 mMixerBufferValid = true;
6066 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006067 } else {
6068 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006069 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006070 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006071 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006072 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006073 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006074 AudioMixer::TRACK,
6075 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6076 }
Eric Laurent81784c32012-11-19 14:55:58 -08006077 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006078 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006079 AudioMixer::TRACK,
6080 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006081 mAudioMixer->setParameter(
6082 trackId,
6083 AudioMixer::TRACK,
6084 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006085 mAudioMixer->setParameter(
6086 trackId,
6087 AudioMixer::TRACK,
6088 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07006089 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006090 mAudioMixer->setParameter(
6091 trackId,
6092 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006093 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006094
6095 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006096 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006097
6098 // If one track is ready, set the mixer ready if:
6099 // - the mixer was not ready during previous round OR
6100 // - no other track is not ready
6101 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6102 mixerStatus != MIXER_TRACKS_ENABLED) {
6103 mixerStatus = MIXER_TRACKS_READY;
6104 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006105
6106 // Enable the next few lines to instrument a test for underrun log handling.
6107 // TODO: Remove when we have a better way of testing the underrun log.
6108#if 0
6109 static int i;
6110 if ((++i & 0xf) == 0) {
6111 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6112 }
6113#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006114 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006115 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006116 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006117 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6118 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006119 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006120 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006121 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006122
Eric Laurent81784c32012-11-19 14:55:58 -08006123 // clear effect chain input buffer if an active track underruns to avoid sending
6124 // previous audio buffer again to effects
6125 chain = getEffectChain_l(track->sessionId());
6126 if (chain != 0) {
6127 chain->clearInputBuffer();
6128 }
6129
Andy Hungc0691382018-09-12 18:01:57 -07006130 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006131 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6132 track->isStopped() || track->isPaused()) {
6133 // We have consumed all the buffers of this track.
6134 // Remove it from the list of active tracks.
6135 // TODO: use actual buffer filling status instead of latency when available from
6136 // audio HAL
6137 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006138 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006139 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6140 if (track->isStopped()) {
6141 track->reset();
6142 }
6143 tracksToRemove->add(track);
6144 }
6145 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006146 // No buffers for this track. Give it a few chances to
6147 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006148 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006149 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6150 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006151 tracksToRemove->add(track);
6152 // indicate to client process that the track was disabled because of underrun;
6153 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006154 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006155 // If one track is not ready, mark the mixer also not ready if:
6156 // - the mixer was ready during previous round OR
6157 // - no other track is ready
6158 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6159 mixerStatus != MIXER_TRACKS_READY) {
6160 mixerStatus = MIXER_TRACKS_ENABLED;
6161 }
6162 }
Andy Hungc0691382018-09-12 18:01:57 -07006163 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006164 }
6165
6166 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006167
6168 }
6169
jiabin245cdd92018-12-07 17:55:15 -08006170 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6171 // When there is no fast track playing haptic and FastMixer exists,
6172 // enabling the first FastTrack, which provides mixed data from normal
6173 // tracks, to play haptic data.
6174 FastTrack *fastTrack = &state->mFastTracks[0];
6175 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6176 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6177 didModify = true;
6178 }
6179 }
6180
Eric Laurent81784c32012-11-19 14:55:58 -08006181 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006182 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006183 if (didModify) {
6184 state->mFastTracksGen++;
6185 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6186 if (kUseFastMixer == FastMixer_Dynamic &&
6187 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6188 state->mCommand = FastMixerState::COLD_IDLE;
6189 state->mColdFutexAddr = &mFastMixerFutex;
6190 state->mColdGen++;
6191 mFastMixerFutex = 0;
6192 if (kUseFastMixer == FastMixer_Dynamic) {
6193 mNormalSink = mOutputSink;
6194 }
6195 // If we go into cold idle, need to wait for acknowledgement
6196 // so that fast mixer stops doing I/O.
6197 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6198 pauseAudioWatchdog = true;
6199 }
Eric Laurent81784c32012-11-19 14:55:58 -08006200 }
6201 if (sq != NULL) {
6202 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006203 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6204 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6205 // when bringing the output sink into standby.)
6206 //
6207 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6208 //
6209 // This occurs with BT suspend when we idle the FastMixer with
6210 // active tracks, which may be added or removed.
6211 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006212 }
6213#ifdef AUDIO_WATCHDOG
6214 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6215 mAudioWatchdog->pause();
6216 }
6217#endif
6218
6219 // Now perform the deferred reset on fast tracks that have stopped
6220 while (resetMask != 0) {
6221 size_t i = __builtin_ctz(resetMask);
6222 ALOG_ASSERT(i < count);
6223 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006224 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006225 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6226 track->reset();
6227 }
6228
Andy Hung80d03d22018-04-10 10:32:11 -07006229 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6230 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6231 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6232 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6233 // See also the implementation of destroyTrack_l().
6234 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006235 const int trackId = track->id();
6236 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6237 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006238 }
6239 }
6240
Eric Laurent81784c32012-11-19 14:55:58 -08006241 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006242 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006243
Eric Laurentb3f315a2021-07-13 15:09:05 +02006244 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6245 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006246 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006247 }
6248
6249 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006250 // as long as there are effects we should clear the effects buffer, to avoid
6251 // passing a non-clean buffer to the effect chain
6252 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006253 if (mType == SPATIALIZER) {
6254 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6255 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006256 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006257 // sink or mix buffer must be cleared if all tracks are connected to an
6258 // effect chain as in this case the mixer will not write to the sink or mix buffer
6259 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006260 // always clear sink buffer for spatializer output as the output of the spatializer
6261 // effect will be accumulated into it
6262 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6263 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006264 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006265 if (mMixerBufferValid) {
6266 memset(mMixerBuffer, 0, mMixerBufferSize);
6267 // TODO: In testing, mSinkBuffer below need not be cleared because
6268 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6269 // after mixing.
6270 //
6271 // To enforce this guarantee:
6272 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6273 // (mixedTracks == 0 && fastTracks > 0))
6274 // must imply MIXER_TRACKS_READY.
6275 // Later, we may clear buffers regardless, and skip much of this logic.
6276 }
Andy Hung98ef9782014-03-04 14:46:50 -08006277 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006278 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006279 }
6280
6281 // if any fast tracks, then status is ready
6282 mMixerStatusIgnoringFastTracks = mixerStatus;
6283 if (fastTracks > 0) {
6284 mixerStatus = MIXER_TRACKS_READY;
6285 }
6286 return mixerStatus;
6287}
6288
Andy Hungc5007f82023-08-29 14:26:09 -07006289// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006290uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006291{
6292 uint32_t trackCount = 0;
6293 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006294 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006295 trackCount++;
6296 }
6297 }
6298 return trackCount;
6299}
6300
Andy Hungee58e4a2023-07-07 13:47:37 -07006301bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006302{
Brian Lindahl65e90012022-07-27 18:01:07 +02006303 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6304 // could falsely detect that the frame position has stalled due to underrun because we haven't
6305 // given the Audio HAL enough time to update.
6306 const nsecs_t nowNs = systemTime();
6307 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6308 return mLatchedValue;
6309 }
6310 mPreviousNs = nowNs;
6311 mLatchedValue = false;
6312 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006313 uint64_t position = 0;
6314 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006315 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006316 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006317 if (position != mPreviousPosition) {
6318 mPreviousPosition = position;
6319 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006320 }
6321 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006322 return mLatchedValue;
6323}
6324
Andy Hungee58e4a2023-07-07 13:47:37 -07006325void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006326{
6327 mLatchedValue = true;
6328 mPreviousPosition = 0;
6329 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006330}
6331
Andy Hungc5007f82023-08-29 14:26:09 -07006332// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006333bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006334 audio_channel_mask_t channelMask, audio_format_t format,
6335 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006336{
Andy Hung1bc088a2018-02-09 15:57:31 -08006337 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6338 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006339 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006340 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006341 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006342 ALOGW("%s: invalid format: %#x", __func__, format);
6343 return false;
6344 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006345 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006346 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6347 return false;
6348 }
6349 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006350}
6351
Andy Hungc5007f82023-08-29 14:26:09 -07006352// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006353bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006354 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006355{
Eric Laurent81784c32012-11-19 14:55:58 -08006356 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006357 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006358
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006359 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006360
Eric Laurent10351942014-05-08 18:49:52 -07006361 AudioParameter param = AudioParameter(keyValuePair);
6362 int value;
6363 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6364 reconfig = true;
6365 }
6366 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006367 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006368 status = BAD_VALUE;
6369 } else {
6370 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006371 reconfig = true;
6372 }
Eric Laurent10351942014-05-08 18:49:52 -07006373 }
6374 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006375 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006376 status = BAD_VALUE;
6377 } else {
6378 // no need to save value, since it's constant
6379 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006380 }
Eric Laurent10351942014-05-08 18:49:52 -07006381 }
6382 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6383 // do not accept frame count changes if tracks are open as the track buffer
6384 // size depends on frame count and correct behavior would not be guaranteed
6385 // if frame count is changed after track creation
6386 if (!mTracks.isEmpty()) {
6387 status = INVALID_OPERATION;
6388 } else {
6389 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006390 }
Eric Laurent10351942014-05-08 18:49:52 -07006391 }
6392 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006393 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006394 }
Eric Laurent81784c32012-11-19 14:55:58 -08006395
Eric Laurent10351942014-05-08 18:49:52 -07006396 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006397 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006398 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006399 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6400 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006401 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006402 mThreadMetrics.logEndInterval();
6403 mThreadSnapshot.onEnd();
6404 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006405 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006406 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006407 }
Eric Laurent10351942014-05-08 18:49:52 -07006408 if (status == NO_ERROR && reconfig) {
6409 readOutputParameters_l();
6410 delete mAudioMixer;
6411 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006412 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006413 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006414 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006415 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006416 track->channelMask(),
6417 track->format(),
6418 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006419 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006420 "%s(): AudioMixer cannot create track(%d)"
6421 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006422 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006423 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006424 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006425 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006426 }
Eric Laurent81784c32012-11-19 14:55:58 -08006427 }
6428
Dean Wheatley68918102021-03-19 22:09:19 +11006429 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006430}
6431
6432
Andy Hungee58e4a2023-07-07 13:47:37 -07006433void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006434{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006435 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006436 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006437 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006438 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006439 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6440 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6441 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006442 if (hasFastMixer()) {
6443 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6444
6445 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6446 // while we are dumping it. It may be inconsistent, but it won't mutate!
6447 // This is a large object so we place it on the heap.
6448 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006449 const std::unique_ptr<FastMixerDumpState> copy =
6450 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006451 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006452
6453#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006454 // Similar for state queue
6455 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6456 observerCopy.dump(fd);
6457 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6458 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006459#endif
6460
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006461#ifdef AUDIO_WATCHDOG
6462 if (mAudioWatchdog != 0) {
6463 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6464 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6465 wdCopy.dump(fd);
6466 }
6467#endif
6468
6469 } else {
6470 dprintf(fd, " No FastMixer\n");
6471 }
Eric Laurent90cea102023-05-15 15:08:27 +02006472
6473 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6474 mBluetoothLatencyModesEnabled ? "" : "not ");
6475 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6476 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6477 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006478}
6479
Andy Hungee58e4a2023-07-07 13:47:37 -07006480uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006481{
6482 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6483}
6484
Andy Hungee58e4a2023-07-07 13:47:37 -07006485uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006486{
6487 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6488}
6489
Andy Hungee58e4a2023-07-07 13:47:37 -07006490void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006491{
6492 PlaybackThread::cacheParameters_l();
6493
6494 // FIXME: Relaxed timing because of a certain device that can't meet latency
6495 // Should be reduced to 2x after the vendor fixes the driver issue
6496 // increase threshold again due to low power audio mode. The way this warning
6497 // threshold is calculated and its usefulness should be reconsidered anyway.
6498 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6499}
6500
Andy Hungee58e4a2023-07-07 13:47:37 -07006501void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006502 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006503}
6504
Andy Hungee58e4a2023-07-07 13:47:37 -07006505void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006506 // Only handle latency mode if:
6507 // - mBluetoothLatencyModesEnabled is true
6508 // - the HAL supports latency modes
6509 // - the selected device is Bluetooth LE or A2DP
6510 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6511 return;
6512 }
6513 if (mOutDeviceTypeAddrs.size() != 1
6514 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6515 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6516 return;
6517 }
6518
6519 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6520 if (mSupportedLatencyModes.size() == 1) {
6521 // If the HAL only support one latency mode currently, confirm the choice
6522 latencyMode = mSupportedLatencyModes[0];
6523 } else if (mSupportedLatencyModes.size() > 1) {
6524 // Request low latency if:
6525 // - At least one active track is either:
6526 // - a fast track with gaming usage or
6527 // - a track with acessibility usage
6528 for (const auto& track : mActiveTracks) {
6529 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6530 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6531 latencyMode = AUDIO_LATENCY_MODE_LOW;
6532 break;
6533 }
6534 }
6535 }
6536
6537 if (latencyMode != mSetLatencyMode) {
6538 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6539 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6540 __func__, mId, toString(latencyMode).c_str(), status);
6541 if (status == NO_ERROR) {
6542 mSetLatencyMode = latencyMode;
6543 }
6544 }
6545}
6546
Andy Hungee58e4a2023-07-07 13:47:37 -07006547void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006548
6549 if (mOutput == nullptr || mOutput->stream == nullptr) {
6550 return;
6551 }
6552 std::vector<audio_latency_mode_t> latencyModes;
6553 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6554 if (status != NO_ERROR) {
6555 latencyModes.clear();
6556 }
6557 if (latencyModes != mSupportedLatencyModes) {
6558 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6559 __func__, mId, status, toString(latencyModes).c_str());
6560 mSupportedLatencyModes.swap(latencyModes);
6561 sendHalLatencyModesChangedEvent_l();
6562 }
6563}
6564
Andy Hungee58e4a2023-07-07 13:47:37 -07006565status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006566 std::vector<audio_latency_mode_t>* modes) {
6567 if (modes == nullptr) {
6568 return BAD_VALUE;
6569 }
Andy Hung972bec12023-08-31 16:13:39 -07006570 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006571 *modes = mSupportedLatencyModes;
6572 return NO_ERROR;
6573}
6574
Andy Hungee58e4a2023-07-07 13:47:37 -07006575void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006576 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006577 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006578 if (modes != mSupportedLatencyModes) {
6579 ALOGD("%s: thread(%d) supported latency modes: %s",
6580 __func__, mId, toString(modes).c_str());
6581 mSupportedLatencyModes.swap(modes);
6582 sendHalLatencyModesChangedEvent_l();
6583 }
6584}
6585
Andy Hungee58e4a2023-07-07 13:47:37 -07006586status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006587 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6588 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6589 return INVALID_OPERATION;
6590 }
6591 mBluetoothLatencyModesEnabled.store(enabled);
6592 return NO_ERROR;
6593}
6594
Eric Laurent81784c32012-11-19 14:55:58 -08006595// ----------------------------------------------------------------------------
6596
Andy Hungee58e4a2023-07-07 13:47:37 -07006597/* static */
6598sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006599 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006600 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6601 const audio_offload_info_t& offloadInfo) {
6602 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006603 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006604}
6605
Andy Hung583043b2023-07-17 17:05:00 -07006606DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006607 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6608 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006609 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006610 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006611{
Andy Hung583043b2023-07-17 17:05:00 -07006612 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006613}
6614
Andy Hungee58e4a2023-07-07 13:47:37 -07006615DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006616{
6617}
6618
Andy Hungee58e4a2023-07-07 13:47:37 -07006619void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006620{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006621 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006622 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6623 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6624}
6625
Andy Hungee58e4a2023-07-07 13:47:37 -07006626void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006627{
Andy Hung972bec12023-08-31 16:13:39 -07006628 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006629 if (mMasterBalance != balance) {
6630 mMasterBalance.store(balance);
6631 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6632 broadcast_l();
6633 }
6634}
6635
Andy Hungee58e4a2023-07-07 13:47:37 -07006636void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006637{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006638 float left, right;
6639
Andy Hung333ab962019-05-28 20:23:35 -07006640 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006641 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006642
Andy Hung398ffa22022-12-13 19:19:53 -08006643 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6644 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6645
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006646 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6647 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006648
6649 const int64_t volumeShaperFrames =
6650 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6651 const auto [shaperVolume, shaperActive] =
6652 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006653 mVolumeShaperActive = shaperActive;
6654
Vlad Popae2f5aef2022-07-25 16:00:20 +02006655 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6656 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6657 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6658
6659 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6660
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006661 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006662 left = right = 0;
6663 } else {
6664 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006665 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006666
Glenn Kastenc56f3422014-03-21 17:53:17 -07006667 if (left > GAIN_FLOAT_UNITY) {
6668 left = GAIN_FLOAT_UNITY;
6669 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006670 if (right > GAIN_FLOAT_UNITY) {
6671 right = GAIN_FLOAT_UNITY;
6672 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006673 left *= v;
6674 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006675 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006676 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6677 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6678 right *= mMasterBalanceRight;
6679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006680 }
6681
Andy Hung583043b2023-07-17 17:05:00 -07006682 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006683 /*muteState=*/{mMasterMute,
6684 mStreamTypes[track->streamType()].volume == 0.f,
6685 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006686 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006687 clientVolumeMute,
6688 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006689
Eric Laurentbfb1b832013-01-07 09:53:42 -08006690 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006691 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006692 if (left != mLeftVolFloat || right != mRightVolFloat) {
6693 mLeftVolFloat = left;
6694 mRightVolFloat = right;
6695
Eric Laurentbfb1b832013-01-07 09:53:42 -08006696 // Delegate volume control to effect in track effect chain if needed
6697 // only one effect chain can be present on DirectOutputThread, so if
6698 // there is one, the track is connected to it
6699 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006700 // if effect chain exists, volume is handled by it.
6701 // Convert volumes from float to 8.24
6702 uint32_t vl = (uint32_t)(left * (1 << 24));
6703 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006704 // Direct/Offload effect chains set output volume in setVolume().
6705 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006706 } else {
6707 // otherwise we directly set the volume.
6708 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006709 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006710 }
6711 }
6712}
6713
Andy Hungee58e4a2023-07-07 13:47:37 -07006714void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006715{
Andy Hung8d31fd22023-06-26 19:20:57 -07006716 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6717 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006718
Eric Laurent0f0631e2015-07-06 18:01:25 -07006719 if (previousTrack != 0 && latestTrack != 0) {
6720 if (mType == DIRECT) {
6721 if (previousTrack.get() != latestTrack.get()) {
6722 mFlushPending = true;
6723 }
6724 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006725 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6726 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006727 mFlushPending = true;
6728 }
6729 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006730 } else if (previousTrack == 0) {
6731 // there could be an old track added back during track transition for direct
6732 // output, so always issues flush to flush data of the previous track if it
6733 // was already destroyed with HAL paused, then flush can resume the playback
6734 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006735 }
6736 PlaybackThread::onAddNewTrack_l();
6737}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006738
Andy Hungee58e4a2023-07-07 13:47:37 -07006739PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006740 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006741)
6742{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006743 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006744 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006745 bool doHwPause = false;
6746 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006747
6748 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006749 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006750 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006751 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006752 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006753 continue;
6754 }
6755
Andy Hung8d31fd22023-06-26 19:20:57 -07006756 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006757#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006758 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006759#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006760 // Only consider last track started for volume and mixer state control.
6761 // In theory an older track could underrun and restart after the new one starts
6762 // but as we only care about the transition phase between two tracks on a
6763 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006764 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006765 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006766
Kuowei Li23666472021-01-20 10:23:25 +08006767 if (track->isPausePending()) {
6768 track->pauseAck();
6769 // It is possible a track might have been flushed or stopped.
6770 // Other operations such as flush pending might occur on the next prepare.
6771 if (track->isPausing()) {
6772 track->setPaused();
6773 }
6774 // Always perform pause, as an immediate flush will change
6775 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006776 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006777 doHwPause = true;
6778 mHwPaused = true;
6779 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006780 } else if (track->isFlushPending()) {
6781 track->flushAck();
6782 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006783 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006784 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006785 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006786 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006787 if (last) {
6788 mLeftVolFloat = mRightVolFloat = -1.0;
6789 if (mHwPaused) {
6790 doHwResume = true;
6791 mHwPaused = false;
6792 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006793 }
6794 }
6795
Eric Laurent81784c32012-11-19 14:55:58 -08006796 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006797 // for all its buffers to be filled before processing it.
6798 // Allow draining the buffer in case the client
6799 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006800 // hence the test on (track->retryCount() > 1).
6801 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006802 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6803 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006804 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006805
6806 // target retry count that we will use is based on the time we wait for retries.
6807 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6808 // the retry threshold is when we accept any size for PCM data. This is slightly
6809 // smaller than the retry count so we can push small bits of data without a glitch.
6810 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006811 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006812 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006813 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006814 minFrames = mNormalFrameCount;
6815 } else {
6816 minFrames = 1;
6817 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006818
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006819 const size_t framesReady = track->framesReady();
6820 const int trackId = track->id();
6821 if (ATRACE_ENABLED()) {
6822 std::string traceName("nRdy");
6823 traceName += std::to_string(trackId);
6824 ATRACE_INT(traceName.c_str(), framesReady);
6825 }
6826 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006827 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006828 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006829 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006830
Andy Hung8d31fd22023-06-26 19:20:57 -07006831 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6832 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006833 if (last) {
6834 // make sure processVolume_l() will apply new volume even if 0
6835 mLeftVolFloat = mRightVolFloat = -1.0;
6836 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006837 if (!mHwSupportsPause) {
6838 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006839 }
6840 }
6841
6842 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006843 processVolume_l(track, last);
6844 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006845 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006846 if (previousTrack != 0) {
6847 if (track != previousTrack.get()) {
6848 // Flush any data still being written from last track
6849 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006850 // Invalidate previous track to force a seek when resuming.
6851 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006852 }
6853 }
6854 mPreviousTrack = track;
6855
Eric Laurentd595b7c2013-04-03 17:27:56 -07006856 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006857 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006858 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006859 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006860 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006861 doHwResume = true;
6862 mHwPaused = false;
6863 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006864 }
Eric Laurent81784c32012-11-19 14:55:58 -08006865 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006866 // clear effect chain input buffer if the last active track started underruns
6867 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006868 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006869 mEffectChains[0]->clearInputBuffer();
6870 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006871 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006872 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006873 if (last && mHwPaused) {
6874 doHwResume = true;
6875 mHwPaused = false;
6876 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006877 }
6878 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6879 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006880 // We have consumed all the buffers of this track.
6881 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006882 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006883 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006884 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006885 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006886 if (presComplete) {
6887 mOutput->presentationComplete();
6888 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006889 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006890 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006891 }
Eric Laurent81784c32012-11-19 14:55:58 -08006892 if (track->isStopped()) {
6893 track->reset();
6894 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006895 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006896 }
6897 } else {
6898 // No buffers for this track. Give it a few chances to
6899 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006900 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006901 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006902 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006903 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006904 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006905 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006906 } else {
6907 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6908 tracksToRemove->add(track);
6909 // indicate to client process that the track was disabled because of
6910 // underrun; it will then automatically call start() when data is available
6911 track->disable();
6912 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6913 // unlike mixerthread, HAL can be paused for direct output
6914 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6915 "minFrames = %u, mFormat = %#x",
6916 framesReady, minFrames, mFormat);
6917 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6918 doHwPause = true;
6919 mHwPaused = true;
6920 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006921 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006922 } else if (last) {
6923 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006924 }
6925 }
6926 }
6927 }
6928
Eric Laurentd1f69b02014-12-15 14:33:13 -08006929 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006930 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006931 for (size_t i = 0; i < mTracks.size(); i++) {
6932 if (mTracks[i]->isFlushPending()) {
6933 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006934 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006935 }
6936 }
6937 }
6938
6939 // make sure the pause/flush/resume sequence is executed in the right order.
6940 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6941 // before flush and then resume HW. This can happen in case of pause/flush/resume
6942 // if resume is received before pause is executed.
6943 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006944 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006945 status_t result = mOutput->stream->pause();
6946 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006947 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006948 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006949 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006950 flushHw_l();
6951 }
6952 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006953 status_t result = mOutput->stream->resume();
6954 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006955 }
Eric Laurent81784c32012-11-19 14:55:58 -08006956 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006957 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006958
6959 return mixerStatus;
6960}
6961
Andy Hungee58e4a2023-07-07 13:47:37 -07006962void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006963{
Eric Laurent81784c32012-11-19 14:55:58 -08006964 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006965 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006966 // output audio to hardware
6967 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006968 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006969 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006970 status_t status = mActiveTrack->getNextBuffer(&buffer);
6971 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006972 // no need to pad with 0 for compressed audio
6973 if (audio_has_proportional_frames(mFormat)) {
6974 memset(curBuf, 0, frameCount * mFrameSize);
6975 }
Eric Laurent81784c32012-11-19 14:55:58 -08006976 break;
6977 }
6978 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6979 frameCount -= buffer.frameCount;
6980 curBuf += buffer.frameCount * mFrameSize;
6981 mActiveTrack->releaseBuffer(&buffer);
6982 }
Andy Hung2098f272014-02-27 14:00:06 -08006983 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006984 mSleepTimeUs = 0;
6985 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006986 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006987}
6988
Andy Hungee58e4a2023-07-07 13:47:37 -07006989void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006990{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006991 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006992 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006993 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006994 return;
6995 }
Andy Hung85ba3332021-04-27 17:40:26 -07006996 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6997 mSleepTimeUs = mActiveSleepTimeUs;
6998 } else {
6999 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007000 }
Andy Hung85ba3332021-04-27 17:40:26 -07007001 // Note: In S or later, we do not write zeroes for
7002 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007003}
7004
Andy Hungee58e4a2023-07-07 13:47:37 -07007005void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007006{
7007 {
Andy Hung972bec12023-08-31 16:13:39 -07007008 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007009 for (size_t i = 0; i < mTracks.size(); i++) {
7010 if (mTracks[i]->isFlushPending()) {
7011 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007012 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007013 }
7014 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007015 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007016 flushHw_l();
7017 }
7018 }
7019 PlaybackThread::threadLoop_exit();
7020}
7021
7022// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007023bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007024{
7025 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007026 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007027
7028 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
7029 // after a timeout and we will enter standby then.
7030 if (mTracks.size() > 0) {
7031 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07007032 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07007033 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007034 }
7035
Eric Laurent5cff4032015-05-26 13:49:58 -07007036 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08007037}
7038
Andy Hungc5007f82023-08-29 14:26:09 -07007039// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007040bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007041 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007042{
7043 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007044 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007045
Eric Laurent10351942014-05-08 18:49:52 -07007046 AudioParameter param = AudioParameter(keyValuePair);
7047 int value;
7048 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007049 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007050 }
Eric Laurent10351942014-05-08 18:49:52 -07007051 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7052 // do not accept frame count changes if tracks are open as the track buffer
7053 // size depends on frame count and correct behavior would not be garantied
7054 // if frame count is changed after track creation
7055 if (!mTracks.isEmpty()) {
7056 status = INVALID_OPERATION;
7057 } else {
7058 reconfig = true;
7059 }
7060 }
7061 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007062 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007063 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007064 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007065 if (!mStandby) {
7066 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007067 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007068 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007069 }
Eric Laurent10351942014-05-08 18:49:52 -07007070 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007071 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007072 }
7073 if (status == NO_ERROR && reconfig) {
7074 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007075 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007076 }
7077 }
7078
Dean Wheatley68918102021-03-19 22:09:19 +11007079 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007080}
7081
Andy Hungee58e4a2023-07-07 13:47:37 -07007082uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007083{
7084 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007085 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007086 time = PlaybackThread::activeSleepTimeUs();
7087 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007088 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007089 }
7090 return time;
7091}
7092
Andy Hungee58e4a2023-07-07 13:47:37 -07007093uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007094{
7095 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007096 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007097 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7098 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007099 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007100 }
7101 return time;
7102}
7103
Andy Hungee58e4a2023-07-07 13:47:37 -07007104uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007105{
7106 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007107 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007108 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7109 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007110 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007111 }
7112 return time;
7113}
7114
Andy Hungee58e4a2023-07-07 13:47:37 -07007115void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007116{
7117 PlaybackThread::cacheParameters_l();
7118
7119 // use shorter standby delay as on normal output to release
7120 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007121 // no delay on outputs with HW A/V sync
7122 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007123 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007124 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007125 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007126 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007127 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007128 }
Eric Laurent81784c32012-11-19 14:55:58 -08007129}
7130
Andy Hungee58e4a2023-07-07 13:47:37 -07007131void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007132{
ziyangch8f194f12021-12-01 13:48:04 -08007133 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007134 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007135 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007136 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007137 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007138 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007139 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007140}
7141
Andy Hungee58e4a2023-07-07 13:47:37 -07007142int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007143 // If a VolumeShaper is active, we must wake up periodically to update volume.
7144 const int64_t NS_PER_MS = 1000000;
7145 return mVolumeShaperActive ?
7146 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7147}
7148
Eric Laurent81784c32012-11-19 14:55:58 -08007149// ----------------------------------------------------------------------------
7150
Andy Hungee58e4a2023-07-07 13:47:37 -07007151AsyncCallbackThread::AsyncCallbackThread(
7152 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007153 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007154 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007155 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007156 mDrainSequence(0),
7157 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007158{
7159}
7160
Andy Hungee58e4a2023-07-07 13:47:37 -07007161void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007162{
7163 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7164}
7165
Andy Hungee58e4a2023-07-07 13:47:37 -07007166bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007167{
7168 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007169 uint32_t writeAckSequence;
7170 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007171 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007172
7173 {
Andy Hungc5007f82023-08-29 14:26:09 -07007174 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007175 while (!((mWriteAckSequence & 1) ||
7176 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007177 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007178 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007179 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007180 }
7181
Eric Laurentbfb1b832013-01-07 09:53:42 -08007182 if (exitPending()) {
7183 break;
7184 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007185 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7186 mWriteAckSequence, mDrainSequence);
7187 writeAckSequence = mWriteAckSequence;
7188 mWriteAckSequence &= ~1;
7189 drainSequence = mDrainSequence;
7190 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007191 asyncError = mAsyncError;
7192 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007193 }
7194 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007195 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007196 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007197 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007198 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007199 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007200 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007201 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007202 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007203 if (asyncError) {
7204 playbackThread->onAsyncError();
7205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007206 }
7207 }
7208 }
7209 return false;
7210}
7211
Andy Hungee58e4a2023-07-07 13:47:37 -07007212void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007213{
7214 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007215 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007216 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007217 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007218}
7219
Andy Hungee58e4a2023-07-07 13:47:37 -07007220void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007221{
Andy Hung972bec12023-08-31 16:13:39 -07007222 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007223 // bit 0 is cleared
7224 mWriteAckSequence = sequence << 1;
7225}
7226
Andy Hungee58e4a2023-07-07 13:47:37 -07007227void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007228{
Andy Hung972bec12023-08-31 16:13:39 -07007229 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007230 // ignore unexpected callbacks
7231 if (mWriteAckSequence & 2) {
7232 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007233 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007234 }
7235}
7236
Andy Hungee58e4a2023-07-07 13:47:37 -07007237void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007238{
Andy Hung972bec12023-08-31 16:13:39 -07007239 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007240 // bit 0 is cleared
7241 mDrainSequence = sequence << 1;
7242}
7243
Andy Hungee58e4a2023-07-07 13:47:37 -07007244void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007245{
Andy Hung972bec12023-08-31 16:13:39 -07007246 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007247 // ignore unexpected callbacks
7248 if (mDrainSequence & 2) {
7249 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007250 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007251 }
7252}
7253
Andy Hungee58e4a2023-07-07 13:47:37 -07007254void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007255{
Andy Hung972bec12023-08-31 16:13:39 -07007256 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007257 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007258 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007259}
7260
Eric Laurentbfb1b832013-01-07 09:53:42 -08007261
7262// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007263
7264/* static */
7265sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007266 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007267 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7268 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007269 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007270}
7271
Andy Hung583043b2023-07-17 17:05:00 -07007272OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007273 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7274 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007275 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007276 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007277{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007278 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007279 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007280 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007281}
7282
Andy Hungee58e4a2023-07-07 13:47:37 -07007283void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007284{
7285 if (mFlushPending || mHwPaused) {
7286 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007287 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007288 flushHw_l();
7289 } else {
7290 mMixerStatus = MIXER_DRAIN_ALL;
7291 threadLoop_drain();
7292 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007293 if (mUseAsyncWrite) {
7294 ALOG_ASSERT(mCallbackThread != 0);
7295 mCallbackThread->exit();
7296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007297 PlaybackThread::threadLoop_exit();
7298}
7299
Andy Hungee58e4a2023-07-07 13:47:37 -07007300PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007301 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007302)
7303{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007304 size_t count = mActiveTracks.size();
7305
7306 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007307 bool doHwPause = false;
7308 bool doHwResume = false;
7309
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007310 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007311
Eric Laurentbfb1b832013-01-07 09:53:42 -08007312 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007313 for (const sp<IAfTrack>& t : mActiveTracks) {
7314 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007315#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007316 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007317#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007318 // Only consider last track started for volume and mixer state control.
7319 // In theory an older track could underrun and restart after the new one starts
7320 // but as we only care about the transition phase between two tracks on a
7321 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007322 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007323 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007324
Haynes Mathew George7844f672014-01-15 12:32:55 -08007325 if (track->isInvalid()) {
7326 ALOGW("An invalidated track shouldn't be in active list");
7327 tracksToRemove->add(track);
7328 continue;
7329 }
7330
Andy Hung8d31fd22023-06-26 19:20:57 -07007331 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007332 ALOGW("An idle track shouldn't be in active list");
7333 continue;
7334 }
7335
Kuowei Li23666472021-01-20 10:23:25 +08007336 if (track->isPausePending()) {
7337 track->pauseAck();
7338 // It is possible a track might have been flushed or stopped.
7339 // Other operations such as flush pending might occur on the next prepare.
7340 if (track->isPausing()) {
7341 track->setPaused();
7342 }
7343 // Always perform pause if last, as an immediate flush will change
7344 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007345 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007346 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007347 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 mHwPaused = true;
7349 }
7350 // If we were part way through writing the mixbuffer to
7351 // the HAL we must save this until we resume
7352 // BUG - this will be wrong if a different track is made active,
7353 // in that case we want to discard the pending data in the
7354 // mixbuffer and tell the client to present it again when the
7355 // track is resumed
7356 mPausedWriteLength = mCurrentWriteLength;
7357 mPausedBytesRemaining = mBytesRemaining;
7358 mBytesRemaining = 0; // stop writing
7359 }
7360 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007361 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007362 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007363 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007364 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007365 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007366 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007367 track->flushAck();
7368 if (last) {
7369 mFlushPending = true;
7370 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007371 } else if (track->isResumePending()){
7372 track->resumeAck();
7373 if (last) {
7374 if (mPausedBytesRemaining) {
7375 // Need to continue write that was interrupted
7376 mCurrentWriteLength = mPausedWriteLength;
7377 mBytesRemaining = mPausedBytesRemaining;
7378 mPausedBytesRemaining = 0;
7379 }
7380 if (mHwPaused) {
7381 doHwResume = true;
7382 mHwPaused = false;
7383 // threadLoop_mix() will handle the case that we need to
7384 // resume an interrupted write
7385 }
7386 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007387 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007388
Eric Laurent3df841a2016-07-15 15:15:40 -07007389 mLeftVolFloat = mRightVolFloat = -1.0;
7390
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007391 // Do not handle new data in this iteration even if track->framesReady()
7392 mixerStatus = MIXER_TRACKS_ENABLED;
7393 }
7394 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007395 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007396 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007397 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7398 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007399 if (last) {
7400 // make sure processVolume_l() will apply new volume even if 0
7401 mLeftVolFloat = mRightVolFloat = -1.0;
7402 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007403 }
7404
7405 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007406 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007407 if (previousTrack != 0) {
7408 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007409 // Flush any data still being written from last track
7410 mBytesRemaining = 0;
7411 if (mPausedBytesRemaining) {
7412 // Last track was paused so we also need to flush saved
7413 // mixbuffer state and invalidate track so that it will
7414 // re-submit that unwritten data when it is next resumed
7415 mPausedBytesRemaining = 0;
7416 // Invalidate is a bit drastic - would be more efficient
7417 // to have a flag to tell client that some of the
7418 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007419 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007420 }
7421 // flush data already sent to the DSP if changing audio session as audio
7422 // comes from a different source. Also invalidate previous track to force a
7423 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007424 if (previousTrack->sessionId() != track->sessionId()) {
7425 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007426 }
7427 }
7428 }
7429 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007430 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007431 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007432 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007433 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007434 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007435 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007436 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007437 mixerStatus = MIXER_TRACKS_READY;
7438 }
7439 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007440 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007441 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007442 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007443 // Hardware buffer can hold a large amount of audio so we must
7444 // wait for all current track's data to drain before we say
7445 // that the track is stopped.
7446 if (mBytesRemaining == 0) {
7447 // Only start draining when all data in mixbuffer
7448 // has been written
7449 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007450 track->setState(IAfTrackBase::STOPPING_2);
7451 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007452 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7453 if (last && !mStandby) {
7454 // do not modify drain sequence if we are already draining. This happens
7455 // when resuming from pause after drain.
7456 if ((mDrainSequence & 1) == 0) {
7457 mSleepTimeUs = 0;
7458 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7459 mixerStatus = MIXER_DRAIN_TRACK;
7460 mDrainSequence += 2;
7461 }
7462 if (mHwPaused) {
7463 // It is possible to move from PAUSED to STOPPING_1 without
7464 // a resume so we must ensure hardware is running
7465 doHwResume = true;
7466 mHwPaused = false;
7467 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007468 }
7469 }
Eric Laurente93cc032016-05-05 10:15:10 -07007470 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007471 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007472 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007473 }
7474 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007475 // Drain has completed or we are in standby, signal presentation complete
7476 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007477 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007478 mOutput->presentationComplete();
7479 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007480 track->reset();
7481 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007482 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007483 if (!mUseAsyncWrite) {
7484 // If we don't get explicit drain notification we must
7485 // register discontinuity regardless of whether this is
7486 // the previous (!last) or the upcoming (last) track
7487 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007488 mTimestampVerifier.discontinuity(
7489 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007490 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007491 }
7492 } else {
7493 // No buffers for this track. Give it a few chances to
7494 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007495 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007496 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007497 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007498 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007499 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007500 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007501 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7502 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007503 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007504 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007505 // it will then automatically call start() when data is available
7506 track->disable();
7507 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007508 } else if (last){
7509 mixerStatus = MIXER_TRACKS_ENABLED;
7510 }
7511 }
7512 }
7513 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007514 if (track->isReady()) { // check ready to prevent premature start.
7515 processVolume_l(track, last);
7516 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007517 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007518
Eric Laurentea0fade2013-10-04 16:23:48 -07007519 // make sure the pause/flush/resume sequence is executed in the right order.
7520 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7521 // before flush and then resume HW. This can happen in case of pause/flush/resume
7522 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007523 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007524 status_t result = mOutput->stream->pause();
7525 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007526 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007527 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007528 if (mFlushPending) {
7529 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007530 }
Eric Laurentfd477972013-10-25 18:10:40 -07007531 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007532 status_t result = mOutput->stream->resume();
7533 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007534 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007535
Eric Laurentbfb1b832013-01-07 09:53:42 -08007536 // remove all the tracks that need to be...
7537 removeTracks_l(*tracksToRemove);
7538
7539 return mixerStatus;
7540}
7541
Eric Laurentbfb1b832013-01-07 09:53:42 -08007542// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007543bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007544{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007545 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7546 mWriteAckSequence, mDrainSequence);
7547 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007548 return true;
7549 }
7550 return false;
7551}
7552
Andy Hungee58e4a2023-07-07 13:47:37 -07007553bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007554{
Andy Hung972bec12023-08-31 16:13:39 -07007555 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007556 return waitingAsyncCallback_l();
7557}
7558
Andy Hungee58e4a2023-07-07 13:47:37 -07007559void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007560{
Eric Laurente659ef42014-09-29 13:06:46 -07007561 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007562 // Flush anything still waiting in the mixbuffer
7563 mCurrentWriteLength = 0;
7564 mBytesRemaining = 0;
7565 mPausedWriteLength = 0;
7566 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007567 // reset bytes written count to reflect that DSP buffers are empty after flush.
7568 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007569
Eric Laurentbfb1b832013-01-07 09:53:42 -08007570 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007571 // discard any pending drain or write ack by incrementing sequence
7572 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7573 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007574 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007575 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7576 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007577 }
7578}
7579
Andy Hungee58e4a2023-07-07 13:47:37 -07007580void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007581{
Andy Hung972bec12023-08-31 16:13:39 -07007582 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007583 if (PlaybackThread::invalidateTracks_l(streamType)) {
7584 mFlushPending = true;
7585 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007586}
7587
Andy Hungee58e4a2023-07-07 13:47:37 -07007588void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007589 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007590 if (PlaybackThread::invalidateTracks_l(portIds)) {
7591 mFlushPending = true;
7592 }
7593}
7594
Eric Laurentbfb1b832013-01-07 09:53:42 -08007595// ----------------------------------------------------------------------------
7596
Andy Hungee58e4a2023-07-07 13:47:37 -07007597/* static */
7598sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007599 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007600 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007601 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007602}
7603
Andy Hung583043b2023-07-17 17:05:00 -07007604DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007605 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007606 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007607 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007608 mWaitTimeMs(UINT_MAX)
7609{
7610 addOutputTrack(mainThread);
7611}
7612
Andy Hungee58e4a2023-07-07 13:47:37 -07007613DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007614{
7615 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7616 mOutputTracks[i]->destroy();
7617 }
7618}
7619
Andy Hungee58e4a2023-07-07 13:47:37 -07007620void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007621{
7622 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007623 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007624 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007625 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007626 if (mMixerBufferValid) {
7627 memset(mMixerBuffer, 0, mMixerBufferSize);
7628 } else {
7629 memset(mSinkBuffer, 0, mSinkBufferSize);
7630 }
Eric Laurent81784c32012-11-19 14:55:58 -08007631 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007632 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007633 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007634 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007635 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007636}
7637
Andy Hungee58e4a2023-07-07 13:47:37 -07007638void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007639{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007640 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007641 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007642 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007643 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007644 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007645 }
7646 } else if (mBytesWritten != 0) {
7647 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7648 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007649 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007650 } else {
7651 // flush remaining overflow buffers in output tracks
7652 writeFrames = 0;
7653 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007654 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007655 }
7656}
7657
Andy Hungee58e4a2023-07-07 13:47:37 -07007658ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007659{
7660 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007661 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7662
7663 // Consider the first OutputTrack for timestamp and frame counting.
7664
7665 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7666 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7667 // we always claim success.
7668 if (i == 0) {
7669 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7670 ALOGD_IF(correction != 0 && writeFrames != 0,
7671 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7672 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7673 mFramesWritten -= correction;
7674 }
7675
7676 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007677 }
Andy Hungcf10d742020-04-28 15:38:24 -07007678 if (mStandby) {
7679 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007680 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007681 mStandby = false;
7682 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007683 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007684}
7685
Andy Hungee58e4a2023-07-07 13:47:37 -07007686void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007687{
7688 // DuplicatingThread implements standby by stopping all tracks
7689 for (size_t i = 0; i < outputTracks.size(); i++) {
7690 outputTracks[i]->stop();
7691 }
7692}
7693
Andy Hung8a5abfd2023-12-07 19:35:12 -08007694void DuplicatingThread::threadLoop_exit()
7695{
7696 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7697 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7698 // Do so here in the threadLoop_exit().
7699
7700 SortedVector <sp<IAfOutputTrack>> localTracks;
7701 {
7702 audio_utils::lock_guard l(mutex());
7703 localTracks = std::move(mOutputTracks);
7704 mOutputTracks.clear();
7705 }
7706 localTracks.clear();
7707 outputTracks.clear();
7708 PlaybackThread::threadLoop_exit();
7709}
7710
Andy Hungee58e4a2023-07-07 13:47:37 -07007711void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007712{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007713 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007714
7715 std::stringstream ss;
7716 const size_t numTracks = mOutputTracks.size();
7717 ss << " " << numTracks << " OutputTracks";
7718 if (numTracks > 0) {
7719 ss << ":";
7720 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007721 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007722 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007723 if (thread.get() != nullptr) {
7724 ss << thread.get() << ", " << thread->id();
7725 } else {
7726 ss << "null";
7727 }
7728 ss << ")";
7729 }
7730 }
7731 ss << "\n";
7732 std::string result = ss.str();
7733 write(fd, result.c_str(), result.size());
7734}
7735
Andy Hungee58e4a2023-07-07 13:47:37 -07007736void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007737{
7738 outputTracks = mOutputTracks;
7739}
7740
Andy Hungee58e4a2023-07-07 13:47:37 -07007741void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007742{
7743 outputTracks.clear();
7744}
7745
Andy Hungee58e4a2023-07-07 13:47:37 -07007746void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007747{
Andy Hung972bec12023-08-31 16:13:39 -07007748 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007749 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7750 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7751 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7752 const size_t frameCount =
7753 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7754 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7755 // from different OutputTracks and their associated MixerThreads (e.g. one may
7756 // nearly empty and the other may be dropping data).
7757
Svet Ganov33761132021-05-13 22:51:08 +00007758 // TODO b/182392769: use attribution source util, move to server edge
7759 AttributionSourceState attributionSource = AttributionSourceState();
7760 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007761 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007762 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007763 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007764 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007765 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007766 this,
7767 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007768 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007769 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007770 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007771 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007772 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7773 if (status != NO_ERROR) {
7774 ALOGE("addOutputTrack() initCheck failed %d", status);
7775 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007776 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007777 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7778 mOutputTracks.add(outputTrack);
7779 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7780 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007781}
7782
Andy Hungee58e4a2023-07-07 13:47:37 -07007783void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007784{
Andy Hung972bec12023-08-31 16:13:39 -07007785 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007786 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7787 if (mOutputTracks[i]->thread() == thread) {
7788 mOutputTracks[i]->destroy();
7789 mOutputTracks.removeAt(i);
7790 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007791 // NO_THREAD_SAFETY_ANALYSIS
7792 // Lambda workaround: as thread != this
7793 // we can safely call the remote thread getOutput.
7794 const bool equalOutput =
7795 [&](){ return thread->getOutput() == mOutput; }();
7796 if (equalOutput) {
7797 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007798 }
Eric Laurent81784c32012-11-19 14:55:58 -08007799 return;
7800 }
7801 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007802 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007803}
7804
Andy Hungc5007f82023-08-29 14:26:09 -07007805// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007806void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007807{
7808 mWaitTimeMs = UINT_MAX;
7809 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007810 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007811 if (strong != 0) {
7812 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7813 if (waitTimeMs < mWaitTimeMs) {
7814 mWaitTimeMs = waitTimeMs;
7815 }
7816 }
7817 }
7818}
7819
Andy Hungee58e4a2023-07-07 13:47:37 -07007820bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007821{
7822 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007823 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007824 if (thread == 0) {
7825 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7826 outputTracks[i].get());
7827 return false;
7828 }
Andy Hung87c693c2023-07-06 20:56:16 -07007829 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007830 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007831 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007832 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7833 thread.get());
7834 return false;
7835 }
7836 }
7837 return true;
7838}
7839
Andy Hungee58e4a2023-07-07 13:47:37 -07007840void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007841 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007842{
Kevin Rocard12381092018-04-11 09:19:59 -07007843 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7844 outputTrack->setMetadatas(metadata.tracks);
7845 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007846}
7847
Andy Hungee58e4a2023-07-07 13:47:37 -07007848uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007849{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007850 // return half the wait time in microseconds.
7851 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007852}
7853
Andy Hungee58e4a2023-07-07 13:47:37 -07007854void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007855{
7856 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7857 updateWaitTime_l();
7858
7859 MixerThread::cacheParameters_l();
7860}
7861
Eric Laurentb3f315a2021-07-13 15:09:05 +02007862// ----------------------------------------------------------------------------
7863
Andy Hungee58e4a2023-07-07 13:47:37 -07007864/* static */
7865sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007866 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007867 AudioStreamOut* output,
7868 audio_io_handle_t id,
7869 bool systemReady,
7870 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007871 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007872}
7873
Andy Hung583043b2023-07-17 17:05:00 -07007874SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007875 AudioStreamOut* output,
7876 audio_io_handle_t id,
7877 bool systemReady,
7878 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007879 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007880{
7881}
7882
Andy Hungee58e4a2023-07-07 13:47:37 -07007883void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007884 // if mSupportedLatencyModes is empty, the HAL stream does not support
7885 // latency mode control and we can exit.
7886 if (mSupportedLatencyModes.empty()) {
7887 return;
7888 }
7889 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7890 if (mSupportedLatencyModes.size() == 1) {
7891 // If the HAL only support one latency mode currently, confirm the choice
7892 latencyMode = mSupportedLatencyModes[0];
7893 } else if (mSupportedLatencyModes.size() > 1) {
7894 // Request low latency if:
7895 // - The low latency mode is requested by the spatializer controller
7896 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7897 // AND
7898 // - At least one active track is spatialized
7899 bool hasSpatializedActiveTrack = false;
7900 for (const auto& track : mActiveTracks) {
7901 if (track->isSpatialized()) {
7902 hasSpatializedActiveTrack = true;
7903 break;
7904 }
7905 }
7906 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7907 latencyMode = AUDIO_LATENCY_MODE_LOW;
7908 }
7909 }
7910
7911 if (latencyMode != mSetLatencyMode) {
7912 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007913 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7914 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007915 if (status == NO_ERROR) {
7916 mSetLatencyMode = latencyMode;
7917 }
7918 }
7919}
7920
Andy Hungee58e4a2023-07-07 13:47:37 -07007921status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007922 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7923 return BAD_VALUE;
7924 }
Andy Hung972bec12023-08-31 16:13:39 -07007925 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007926 mRequestedLatencyMode = mode;
7927 return NO_ERROR;
7928}
7929
Andy Hungee58e4a2023-07-07 13:47:37 -07007930void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007931NO_THREAD_SAFETY_ANALYSIS
7932// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007933{
7934 bool hasVirtualizer = false;
7935 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007936 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007937 {
Andy Hung972bec12023-08-31 16:13:39 -07007938 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007939 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007940 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007941 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007942 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7943 }
7944
7945 finalDownMixer = mFinalDownMixer;
7946 mFinalDownMixer.clear();
7947 }
7948
7949 if (hasVirtualizer) {
7950 if (finalDownMixer != nullptr) {
7951 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007952 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007953 }
7954 finalDownMixer.clear();
7955 } else if (!hasDownMixer) {
7956 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007957 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007958 EFFECT_UIID_DOWNMIX, &descriptors);
7959 if (status != NO_ERROR) {
7960 return;
7961 }
7962 ALOG_ASSERT(!descriptors.empty(),
7963 "%s getDescriptors() returned no error but empty list", __func__);
7964
7965 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7966 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007967 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007968
7969 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7970 ALOGW("%s error creating downmixer %d", __func__, status);
7971 finalDownMixer.clear();
7972 } else {
7973 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007974 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007975 }
7976 }
7977
7978 {
Andy Hung972bec12023-08-31 16:13:39 -07007979 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007980 mFinalDownMixer = finalDownMixer;
7981 }
7982}
7983
Andy Hunge2514462023-12-06 14:59:24 -08007984void SpatializerThread::threadLoop_exit()
7985{
7986 // The Spatializer EffectHandle must be released on the PlaybackThread
7987 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
7988 mFinalDownMixer.clear();
7989
7990 PlaybackThread::threadLoop_exit();
7991}
7992
Eric Laurent81784c32012-11-19 14:55:58 -08007993// ----------------------------------------------------------------------------
7994// Record
7995// ----------------------------------------------------------------------------
7996
Andy Hung583043b2023-07-17 17:05:00 -07007997sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007998 AudioStreamIn* input,
7999 audio_io_handle_t id,
8000 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008001 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008002}
8003
Andy Hung583043b2023-07-17 17:05:00 -07008004RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008005 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008006 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008007 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008008 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008009 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008010 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008011 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008012 mActiveTracks(&this->mLocalLog),
8013 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008014 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008015 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008016 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8017 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008018 // mFastCapture below
8019 , mFastCaptureFutex(0)
8020 // mInputSource
8021 // mPipeSink
8022 // mPipeSource
8023 , mPipeFramesP2(0)
8024 // mPipeMemory
8025 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008026 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008027 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008028{
Glenn Kastend7dca052015-03-05 16:05:54 -08008029 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008030 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008031
George Burgess IVa8f90c12020-05-14 11:27:19 -07008032 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008033 mIsMsdDevice = strcmp(
8034 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8035 }
8036
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008037 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008038
Andy Hungc8fddf32018-08-08 18:32:37 -07008039 // TODO: We may also match on address as well as device type for
8040 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008041 // TODO: This property should be ensure that only contains one single device type.
8042 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8043 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008044 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8045 : AUDIO_DEVICE_NONE));
8046
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008047 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008048 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008049 size_t numCounterOffers = 0;
8050 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008051#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008052 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008053#else
8054 (void)
8055#endif
8056 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008057 ALOG_ASSERT(index == 0);
8058
8059 // initialize fast capture depending on configuration
8060 bool initFastCapture;
8061 switch (kUseFastCapture) {
8062 case FastCapture_Never:
8063 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008064 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008065 break;
8066 case FastCapture_Always:
8067 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008068 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008069 break;
8070 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008071 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008072 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008073 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008074 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8075 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8076 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008077 break;
8078 // case FastCapture_Dynamic:
8079 }
8080
8081 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008082 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008083 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008084 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8085 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008086 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008087 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008088 const sp<MemoryDealer> roHeap(readOnlyHeap());
8089 sp<IMemory> pipeMemory;
8090 if ((roHeap == 0) ||
8091 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008092 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008093 ALOGE("not enough memory for pipe buffer size=%zu; "
8094 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8095 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8096 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008097 goto failed;
8098 }
8099 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8100 memset(pipeBuffer, 0, pipeSize);
8101 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008102 const NBAIO_Format offersFast[1] = {format};
8103 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008104 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008105 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008106 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008107 mPipeSink = pipe;
8108 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008109 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008110 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008111 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008112 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008113 mPipeSource = pipeReader;
8114 mPipeFramesP2 = pipeFramesP2;
8115 mPipeMemory = pipeMemory;
8116
8117 // create fast capture
8118 mFastCapture = new FastCapture();
8119 FastCaptureStateQueue *sq = mFastCapture->sq();
8120#ifdef STATE_QUEUE_DUMP
8121 // FIXME
8122#endif
8123 FastCaptureState *state = sq->begin();
8124 state->mCblk = NULL;
8125 state->mInputSource = mInputSource.get();
8126 state->mInputSourceGen++;
8127 state->mPipeSink = pipe;
8128 state->mPipeSinkGen++;
8129 state->mFrameCount = mFrameCount;
8130 state->mCommand = FastCaptureState::COLD_IDLE;
8131 // already done in constructor initialization list
8132 //mFastCaptureFutex = 0;
8133 state->mColdFutexAddr = &mFastCaptureFutex;
8134 state->mColdGen++;
8135 state->mDumpState = &mFastCaptureDumpState;
8136#ifdef TEE_SINK
8137 // FIXME
8138#endif
Andy Hung583043b2023-07-17 17:05:00 -07008139 mFastCaptureNBLogWriter =
8140 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008141 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8142 sq->end();
8143 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8144
8145 // start the fast capture
8146 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8147 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008148 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008149 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008150#ifdef AUDIO_WATCHDOG
8151 // FIXME
8152#endif
8153
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008154 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008155 }
Andy Hung8946a282018-04-19 20:04:56 -07008156#ifdef TEE_SINK
8157 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8158 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8159#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008160failed: ;
8161
8162 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008163}
8164
Andy Hungee58e4a2023-07-07 13:47:37 -07008165RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008166{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008167 if (mFastCapture != 0) {
8168 FastCaptureStateQueue *sq = mFastCapture->sq();
8169 FastCaptureState *state = sq->begin();
8170 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8171 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8172 if (old == -1) {
8173 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8174 }
8175 }
8176 state->mCommand = FastCaptureState::EXIT;
8177 sq->end();
8178 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8179 mFastCapture->join();
8180 mFastCapture.clear();
8181 }
Andy Hung583043b2023-07-17 17:05:00 -07008182 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8183 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008184 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008185}
8186
Andy Hungee58e4a2023-07-07 13:47:37 -07008187void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008188{
Glenn Kastend7dca052015-03-05 16:05:54 -08008189 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008190}
8191
Andy Hungee58e4a2023-07-07 13:47:37 -07008192void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008193{
8194 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008195 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008196 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008197 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008198 track->invalidate();
8199 }
8200 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008201 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008202}
8203
Andy Hungee58e4a2023-07-07 13:47:37 -07008204bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008205{
Eric Laurent81784c32012-11-19 14:55:58 -08008206 nsecs_t lastWarning = 0;
8207
8208 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008209
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008210reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008211 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008212 {
Andy Hung972bec12023-08-31 16:13:39 -07008213 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008214 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008215 }
8216
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008217 // used to request a deferred sleep, to be executed later while mutex is unlocked
8218 uint32_t sleepUs = 0;
8219
Andy Hung95c94a22023-10-20 16:41:18 -07008220 // timestamp correction enable is determined under lock, used in processing step.
8221 bool timestampCorrectionEnabled = false;
8222
Andy Hung446f4df2019-02-21 12:26:41 -08008223 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8224
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008225 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008226 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008227 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008228
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008229 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008230 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008231
Glenn Kasten735f45f2014-08-18 15:51:59 -07008232 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008233 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008234
Glenn Kasten735f45f2014-08-18 15:51:59 -07008235 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008236 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008237
Eric Laurent33403f02020-05-29 18:35:06 -07008238 bool silenceFastCapture = false;
8239
Andy Hungc5007f82023-08-29 14:26:09 -07008240 { // scope for mutex()
8241 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008242
Eric Laurent021cf962014-05-13 10:18:14 -07008243 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008244
Eric Laurent000a4192014-01-29 15:17:32 -08008245 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008246 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008247 if (exitPending()) {
8248 break;
8249 }
8250
Eric Laurent5c25d562016-07-13 17:17:45 -07008251 // sleep with mutex unlocked
8252 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008253 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008254 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008255 ATRACE_END();
8256 sleepUs = 0;
8257 continue;
8258 }
8259
Glenn Kasten2b806402013-11-20 16:37:38 -08008260 // if no active track(s), then standby and release wakelock
8261 size_t size = mActiveTracks.size();
8262 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008263 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008264 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008265 releaseWakeLock_l();
8266 ALOGV("RecordThread: loop stopping");
8267 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008268 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008269 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008270 goto reacquire_wakelock;
8271 }
8272
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008273 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008274 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008275 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008276
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008277 activeTrack = mActiveTracks[i];
8278 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008279 if (activeTrack->isFastTrack()) {
8280 ALOG_ASSERT(fastTrackToRemove == 0);
8281 fastTrackToRemove = activeTrack;
8282 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008283 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008284 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008285 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008286 continue;
8287 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008288
Andy Hung8d31fd22023-06-26 19:20:57 -07008289 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008290 switch (activeTrackState) {
8291
Andy Hung8d31fd22023-06-26 19:20:57 -07008292 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008293 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008294 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008295 if (activeTrack->isFastTrack()) {
8296 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8297 // Keep a ref on fast track to wait for FastCapture thread to get updated
8298 // state before potential track removal
8299 fastTrackToRemove = activeTrack;
8300 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008301 doBroadcast = true;
8302 size--;
8303 continue;
8304
Andy Hung8d31fd22023-06-26 19:20:57 -07008305 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008306 sleepUs = 10000;
8307 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008308 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008309 continue;
8310
Andy Hung8d31fd22023-06-26 19:20:57 -07008311 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008312 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008313 if (mStandby) {
8314 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008315 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008316 mStandby = false;
8317 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008318 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008319 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008320 break;
8321
Andy Hung8d31fd22023-06-26 19:20:57 -07008322 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008323 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008324 break;
8325
Andy Hung8d31fd22023-06-26 19:20:57 -07008326 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8327 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8328 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008329 default:
Andy Hungce685402018-10-05 17:23:27 -07008330 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8331 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008332 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008333
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008334 if (activeTrack->isFastTrack()) {
8335 ALOG_ASSERT(!mFastTrackAvail);
8336 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008337 // if the active fast track is silenced either:
8338 // 1) silence the whole capture from fast capture buffer if this is
8339 // the only active track
8340 // 2) invalidate this track: this will cause the client to reconnect and possibly
8341 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008342 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008343 if (activeTrack->isSilenced()) {
8344 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008345 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008346 } else {
8347 silenceFastCapture = true;
8348 }
8349 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008350 // Invalidate fast tracks if access to audio history is required as this is not
8351 // possible with fast tracks. Once the fast track has been invalidated, no new
8352 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8353 if (mMaxSharedAudioHistoryMs != 0) {
8354 invalidate = true;
8355 }
8356 if (invalidate) {
8357 activeTrack->invalidate();
8358 ALOG_ASSERT(fastTrackToRemove == 0);
8359 fastTrackToRemove = activeTrack;
8360 removeTrack_l(activeTrack);
8361 mActiveTracks.remove(activeTrack);
8362 size--;
8363 continue;
8364 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008365 fastTrack = activeTrack;
8366 }
Eric Laurent33403f02020-05-29 18:35:06 -07008367
8368 activeTracks.add(activeTrack);
8369 i++;
8370
Glenn Kasten9e982352013-08-14 14:39:50 -07008371 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008372
Andy Hungab65b182023-09-06 19:41:47 -07008373 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008374
Kevin Rocard069c2712018-03-29 19:09:14 -07008375 updateMetadata_l();
8376
Eric Laurent5c25d562016-07-13 17:17:45 -07008377 if (allStopped) {
8378 standbyIfNotAlreadyInStandby();
8379 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008380 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008381 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008382 }
8383
8384 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008385 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008386 if (sleepUs == 0) {
8387 sleepUs = kRecordThreadSleepUs;
8388 }
8389 continue;
8390 }
8391 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008392
Andy Hung95c94a22023-10-20 16:41:18 -07008393 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008394 lockEffectChains_l(effectChains);
8395 }
8396
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008397 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008398
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008399 size_t size = effectChains.size();
8400 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008401 // thread mutex is not locked, but effect chain is locked
8402 effectChains[i]->process_l();
8403 }
8404
Glenn Kasten735f45f2014-08-18 15:51:59 -07008405 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008406 if (mFastCapture != 0) {
8407 FastCaptureStateQueue *sq = mFastCapture->sq();
8408 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008409 bool didModify = false;
8410 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008411 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8412 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8413 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8414 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8415 if (old == -1) {
8416 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8417 }
8418 }
8419 state->mCommand = FastCaptureState::READ_WRITE;
8420#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008421 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008422 FastThreadDumpState::kSamplingNforLowRamDevice :
8423 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008424#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008425 didModify = true;
8426 }
8427 audio_track_cblk_t *cblkOld = state->mCblk;
8428 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8429 if (cblkNew != cblkOld) {
8430 state->mCblk = cblkNew;
8431 // block until acked if removing a fast track
8432 if (cblkOld != NULL) {
8433 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8434 }
8435 didModify = true;
8436 }
jiabin01c8f562018-07-19 17:47:28 -07008437 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8438 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8439 if (state->mFastPatchRecordBufferProvider != abp) {
8440 state->mFastPatchRecordBufferProvider = abp;
8441 state->mFastPatchRecordFormat = fastTrack == 0 ?
8442 AUDIO_FORMAT_INVALID : fastTrack->format();
8443 didModify = true;
8444 }
Eric Laurent33403f02020-05-29 18:35:06 -07008445 if (state->mSilenceCapture != silenceFastCapture) {
8446 state->mSilenceCapture = silenceFastCapture;
8447 didModify = true;
8448 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008449 sq->end(didModify);
8450 if (didModify) {
8451 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008452#if 0
8453 if (kUseFastCapture == FastCapture_Dynamic) {
8454 mNormalSource = mPipeSource;
8455 }
8456#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008457 }
8458 }
8459
Glenn Kasten735f45f2014-08-18 15:51:59 -07008460 // now run the fast track destructor with thread mutex unlocked
8461 fastTrackToRemove.clear();
8462
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008463 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8464 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8465 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8466 // If destination is non-contiguous, first read past the nominal end of buffer, then
8467 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008468
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008469 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008470 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008471 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008472
8473 // If an NBAIO source is present, use it to read the normal capture's data
8474 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008475 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008476
8477 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8478 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8479 // we immediately retry the read() to get data and prevent another overflow.
8480 for (int retries = 0; retries <= 2; ++retries) {
8481 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8482 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8483 framesToRead);
8484 if (framesRead != OVERRUN) break;
8485 }
8486
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008487 const ssize_t availableToRead = mPipeSource->availableToRead();
8488 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008489 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008490 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008491 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8492 "more frames to read than fifo size, %zd > %zu",
8493 availableToRead, mPipeFramesP2);
8494 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8495 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8496 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8497 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008498 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8499 }
8500 if (framesRead < 0) {
8501 status_t status = (status_t) framesRead;
8502 switch (status) {
8503 case OVERRUN:
8504 ALOGW("overrun on read from pipe");
8505 framesRead = 0;
8506 break;
8507 case NEGOTIATE:
8508 ALOGE("re-negotiation is needed");
8509 framesRead = -1; // Will cause an attempt to recover.
8510 break;
8511 default:
8512 ALOGE("unknown error %d on read from pipe", status);
8513 break;
8514 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008515 }
8516 // otherwise use the HAL / AudioStreamIn directly
8517 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008518 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008519 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008520 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008521 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008522 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008523 if (result < 0) {
8524 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008525 } else {
8526 framesRead = bytesRead / mFrameSize;
8527 }
8528 }
8529
Andy Hung446f4df2019-02-21 12:26:41 -08008530 const int64_t lastIoEndNs = systemTime(); // end IO timing
8531
Andy Hung3f0c9022016-01-15 17:49:46 -08008532 // Update server timestamp with server stats
8533 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008534 if (framesRead >= 0) {
8535 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8536 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8537 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008538
8539 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008540 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008541 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008542 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008543 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8544 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8545 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008546 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008547 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8548
8549 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008550 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008551 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008552 id(), (long long)time, (long long)position);
8553 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8554 position = correctedTimestamp.mFrames;
8555 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008556 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008557 id(), (long long)time, (long long)position);
8558 }
8559
Andy Hung3f0c9022016-01-15 17:49:46 -08008560 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8561 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8562 // Note: In general record buffers should tend to be empty in
8563 // a properly running pipeline.
8564 //
8565 // Also, it is not advantageous to call get_presentation_position during the read
8566 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008567 } else {
8568 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008569 }
8570 }
Andy Hunge6c37112019-02-26 17:38:10 -08008571
8572 // From the timestamp, input read latency is negative output write latency.
8573 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008574 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008575 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8576 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8577 mLatencyMs.add(latencyMs);
8578 }
8579
Andy Hung3f0c9022016-01-15 17:49:46 -08008580 // Use this to track timestamp information
8581 // ALOGD("%s", mTimestamp.toString().c_str());
8582
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008583 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008584 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008585 // Force input into standby so that it tries to recover at next read attempt
8586 inputStandBy();
8587 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008588 }
8589 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008590 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008591 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008592 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008593 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008594
Andy Hung8946a282018-04-19 20:04:56 -07008595#ifdef TEE_SINK
8596 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8597#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008598 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008599 {
8600 size_t part1 = mRsmpInFramesP2 - rear;
8601 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008602 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008603 (framesRead - part1) * mFrameSize);
8604 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008605 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008606 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008607
8608 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008609
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008610 // loop over each active track
8611 for (size_t i = 0; i < size; i++) {
8612 activeTrack = activeTracks[i];
8613
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008614 // skip fast tracks, as those are handled directly by FastCapture
8615 if (activeTrack->isFastTrack()) {
8616 continue;
8617 }
8618
Andy Hung73c02e42015-03-29 01:13:58 -07008619 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008620 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8621
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008622 enum {
8623 OVERRUN_UNKNOWN,
8624 OVERRUN_TRUE,
8625 OVERRUN_FALSE
8626 } overrun = OVERRUN_UNKNOWN;
8627
8628 // loop over getNextBuffer to handle circular sink
8629 for (;;) {
8630
Andy Hung8d31fd22023-06-26 19:20:57 -07008631 activeTrack->sinkBuffer().frameCount = ~0;
8632 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8633 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008634 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8635
Andy Hung73c02e42015-03-29 01:13:58 -07008636 // check available frames and handle overrun conditions
8637 // if the record track isn't draining fast enough.
8638 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008639 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008640 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008641 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008642 overrun = OVERRUN_TRUE;
8643 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008644 if (framesOut == 0 || framesIn == 0) {
8645 break;
8646 }
8647
Andy Hung6770c6f2015-04-07 13:43:36 -07008648 // Don't allow framesOut to be larger than what is possible with resampling
8649 // from framesIn.
8650 // This isn't strictly necessary but helps limit buffer resizing in
8651 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008652 if (audio_is_linear_pcm(activeTrack->format())) {
8653 framesOut = min(framesOut,
8654 destinationFramesPossible(
8655 framesIn, mSampleRate, activeTrack->sampleRate()));
8656 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008657
8658 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008659 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008660 // straight from RecordThread buffer to RecordTrack buffer.
8661 AudioBufferProvider::Buffer buffer;
8662 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008663 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008664 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008665 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008666 ALOGV_IF(buffer.frameCount != framesOut,
8667 "%s() read less than expected (%zu vs %zu)",
8668 __func__, buffer.frameCount, framesOut);
8669 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008670 memcpy(activeTrack->sinkBuffer().raw,
8671 buffer.raw, buffer.frameCount * mFrameSize);
8672 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008673 } else {
8674 framesOut = 0;
8675 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008676 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008677 }
8678 } else {
8679 // process frames from the RecordThread buffer provider to the RecordTrack
8680 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008681 framesOut = activeTrack->recordBufferConverter()->convert(
8682 activeTrack->sinkBuffer().raw,
8683 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008684 framesOut);
8685 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008686
8687 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8688 overrun = OVERRUN_FALSE;
8689 }
8690
Andy Hung93bb5732023-05-04 21:16:34 -07008691 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8692 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008693 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008694 if (framesToDrop == 0) {
8695 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008696 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008697 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008698 // Sanitize before releasing if the track has no access to the source data
8699 // An idle UID receives silence from non virtual devices until active
8700 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008701 memset(activeTrack->sinkBuffer().raw,
8702 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008703 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008704 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008705 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008706 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008707 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008708 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008709 }
8710 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008711
8712 switch (overrun) {
8713 case OVERRUN_TRUE:
8714 // client isn't retrieving buffers fast enough
8715 if (!activeTrack->setOverflow()) {
8716 nsecs_t now = systemTime();
8717 // FIXME should lastWarning per track?
8718 if ((now - lastWarning) > kWarningThrottleNs) {
8719 ALOGW("RecordThread: buffer overflow");
8720 lastWarning = now;
8721 }
8722 }
8723 break;
8724 case OVERRUN_FALSE:
8725 activeTrack->clearOverflow();
8726 break;
8727 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008728 break;
8729 }
8730
Andy Hung3f0c9022016-01-15 17:49:46 -08008731 // update frame information and push timestamp out
8732 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008733 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008734 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8735 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008736 }
8737
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008738unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008739 // enable changes in effect chain
8740 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008741 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008742 if (audio_has_proportional_frames(mFormat)
8743 && loopCount == lastLoopCountRead + 1) {
8744 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8745 const double jitterMs =
8746 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8747 {framesRead, readPeriodNs},
8748 {0, 0} /* lastTimestamp */, mSampleRate);
8749 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8750
Andy Hung972bec12023-08-31 16:13:39 -07008751 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008752 mIoJitterMs.add(jitterMs);
8753 mProcessTimeMs.add(processMs);
8754 }
8755 // update timing info.
8756 mLastIoBeginNs = lastIoBeginNs;
8757 mLastIoEndNs = lastIoEndNs;
8758 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008759 }
8760
Glenn Kasten93e471f2013-08-19 08:40:07 -07008761 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008762
8763 {
Andy Hung972bec12023-08-31 16:13:39 -07008764 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008765 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008766 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008767 track->invalidate();
8768 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008769 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008770 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008771 }
8772
8773 releaseWakeLock();
8774
8775 ALOGV("RecordThread %p exiting", this);
8776 return false;
8777}
8778
Andy Hungee58e4a2023-07-07 13:47:37 -07008779void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008780{
8781 if (!mStandby) {
8782 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008783 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008784 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008785 mStandby = true;
8786 }
8787}
8788
Andy Hungee58e4a2023-07-07 13:47:37 -07008789void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008790{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008791 // Idle the fast capture if it's currently running
8792 if (mFastCapture != 0) {
8793 FastCaptureStateQueue *sq = mFastCapture->sq();
8794 FastCaptureState *state = sq->begin();
8795 if (!(state->mCommand & FastCaptureState::IDLE)) {
8796 state->mCommand = FastCaptureState::COLD_IDLE;
8797 state->mColdFutexAddr = &mFastCaptureFutex;
8798 state->mColdGen++;
8799 mFastCaptureFutex = 0;
8800 sq->end();
8801 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8802 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8803#if 0
8804 if (kUseFastCapture == FastCapture_Dynamic) {
8805 // FIXME
8806 }
8807#endif
8808#ifdef AUDIO_WATCHDOG
8809 // FIXME
8810#endif
8811 } else {
8812 sq->end(false /*didModify*/);
8813 }
8814 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008815 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008816 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008817
8818 // If going into standby, flush the pipe source.
8819 if (mPipeSource.get() != nullptr) {
8820 const ssize_t flushed = mPipeSource->flush();
8821 if (flushed > 0) {
8822 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8823 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8824 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8825 }
8826 }
Eric Laurent81784c32012-11-19 14:55:58 -08008827}
8828
Andy Hungc5007f82023-08-29 14:26:09 -07008829// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008830sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008831 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008832 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008833 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008834 audio_format_t format,
8835 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008836 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008837 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008838 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008839 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008840 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008841 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008842 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008843 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008844 audio_port_handle_t portId,
8845 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008846{
Glenn Kasten74935e42013-12-19 08:56:45 -08008847 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008848 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008849 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008850 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008851 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008852 audio_input_flags_t requestedFlags = *flags;
8853 uint32_t sampleRate;
8854
8855 lStatus = initCheck();
8856 if (lStatus != NO_ERROR) {
8857 ALOGE("createRecordTrack_l() audio driver not initialized");
8858 goto Exit;
8859 }
8860
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008861 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8862 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8863 lStatus = BAD_VALUE;
8864 goto Exit;
8865 }
8866
Eric Laurentec376dc2021-04-08 20:41:22 +02008867 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008868 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008869 lStatus = PERMISSION_DENIED;
8870 goto Exit;
8871 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008872 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008873 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008874 lStatus = BAD_VALUE;
8875 goto Exit;
8876 }
8877 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008878 if (*pSampleRate == 0) {
8879 *pSampleRate = mSampleRate;
8880 }
8881 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008882
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008883 // special case for FAST flag considered OK if fast capture is present and access to
8884 // audio history is not required
8885 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008886 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8887 }
8888
Eric Laurentf14db3c2017-12-08 14:20:36 -08008889 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008890 if ((*flags & inputFlags) != *flags) {
8891 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8892 " input flags (%08x)",
8893 *flags, inputFlags);
8894 *flags = (audio_input_flags_t)(*flags & inputFlags);
8895 }
Eric Laurent81784c32012-11-19 14:55:58 -08008896
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008897 // client expresses a preference for FAST and no access to audio history,
8898 // but we get the final say
8899 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008900 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008901 // we formerly checked for a callback handler (non-0 tid),
8902 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008903 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008904 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008905 // Frame count is not specified (0), or is less than or equal the pipe depth.
8906 // It is OK to provide a higher capacity than requested.
8907 // We will force it to mPipeFramesP2 below.
8908 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008909 // PCM data
8910 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008911 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008912 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008913 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008914 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008915 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008916 hasFastCapture() &&
8917 // there are sufficient fast track slots available
8918 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008919 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008920 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008921 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008922 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008923 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008924 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008925 audio_input_flags_t old = *flags;
8926 chain->checkInputFlagCompatibility(flags);
8927 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008928 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8929 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008930 }
8931 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008932 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008933 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8934 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008935 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008936 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8937 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008938 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008939 this, frameCount, mFrameCount, mPipeFramesP2,
8940 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008941 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008942 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008943 }
8944 }
8945
Eric Laurentf14db3c2017-12-08 14:20:36 -08008946 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8947 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8948 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8949 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8950 lStatus = BAD_TYPE;
8951 goto Exit;
8952 }
8953
Glenn Kasten74105912014-07-03 12:28:53 -07008954 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008955 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008956 // fast track: frame count is exactly the pipe depth
8957 frameCount = mPipeFramesP2;
8958 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008959 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008960 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008961 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8962 // or 20 ms if there is a fast capture
8963 // TODO This could be a roundupRatio inline, and const
8964 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8965 * sampleRate + mSampleRate - 1) / mSampleRate;
8966 // minimum number of notification periods is at least kMinNotifications,
8967 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8968 static const size_t kMinNotifications = 3;
8969 static const uint32_t kMinMs = 30;
8970 // TODO This could be a roundupRatio inline
8971 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8972 // TODO This could be a roundupRatio inline
8973 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8974 maxNotificationFrames;
8975 const size_t minFrameCount = maxNotificationFrames *
8976 max(kMinNotifications, minNotificationsByMs);
8977 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008978 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8979 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008980 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008981 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008982 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008983 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008984
Andy Hungc5007f82023-08-29 14:26:09 -07008985 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008986 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008987 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008988 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008989 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008990 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008991 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008992 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008993 }
Eric Laurent81784c32012-11-19 14:55:58 -08008994
Andy Hung8d31fd22023-06-26 19:20:57 -07008995 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008996 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008997 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008998 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008999 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009000
Glenn Kasten03003332013-08-06 15:40:54 -07009001 lStatus = track->initCheck();
9002 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009003 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009004 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009005 goto Exit;
9006 }
9007 mTracks.add(track);
9008
Eric Laurent05067782016-06-01 18:27:28 -07009009 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009010 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9011 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9012 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009013 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009014 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009015
9016 if (maxSharedAudioHistoryMs != 0) {
9017 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9018 }
Eric Laurent81784c32012-11-19 14:55:58 -08009019 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009020
Eric Laurent81784c32012-11-19 14:55:58 -08009021 lStatus = NO_ERROR;
9022
9023Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009024 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009025 return track;
9026}
9027
Andy Hungee58e4a2023-07-07 13:47:37 -07009028status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009029 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009030 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009031{
9032 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9033 sp<ThreadBase> strongMe = this;
9034 status_t status = NO_ERROR;
9035
9036 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009037 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009038 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009039 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009040 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009041 event, triggerSession,
9042 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009043 }
9044
9045 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009046 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009047 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009048 if (recordTrack->isInvalid()) {
9049 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009050 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9051 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009052 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009053 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009054 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009055 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9056 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009057 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009058 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009059 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009060 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009061 }
9062 return status;
9063 }
9064
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009065 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9066 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9067 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009068 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009069 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009070 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009071 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009072 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009073 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009074 if (recordTrack->isInvalid()) {
9075 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009076 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9077 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009078 // STARTING_2 forces destroy to call stopInput.
9079 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009080 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9081 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009082 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009083 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009084 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009085 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009086 // Someone else has changed state, let them take over,
9087 // leave mState in the new state.
9088 recordTrack->clearSyncStartEvent();
9089 return INVALID_OPERATION;
9090 }
9091 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009092 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009093 ALOGW("%s(%d): startInput failed, status %d",
9094 __func__, recordTrack->id(), status);
9095 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9096 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009097 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009098 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009099 return status;
9100 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009101 sendIoConfigEvent_l(
9102 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009103 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009104
9105 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9106
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009107 // Catch up with current buffer indices if thread is already running.
9108 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9109 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9110 // see previously buffered data before it called start(), but with greater risk of overrun.
9111
Andy Hung8d31fd22023-06-26 19:20:57 -07009112 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009113 if (!recordTrack->isDirect()) {
9114 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009115 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009116 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009117 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009118 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009119 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009120 return status;
9121 }
Eric Laurent81784c32012-11-19 14:55:58 -08009122}
9123
Andy Hungee58e4a2023-07-07 13:47:37 -07009124void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009125{
Andy Hungee58e4a2023-07-07 13:47:37 -07009126 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009127
9128 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009129 sp<IAfTrackBase> ptr =
9130 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9131 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009132 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009133 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009134 }
Eric Laurent81784c32012-11-19 14:55:58 -08009135 }
9136}
9137
Andy Hungee58e4a2023-07-07 13:47:37 -07009138bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009139 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009140 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009141 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009142 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009143 return false;
9144 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009145 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009146 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009147
Andy Hungabfab202019-03-07 19:45:54 -08009148 // NOTE: Waiting here is important to keep stop synchronous.
9149 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009150 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009151 mWaitWorkCV.notify_all(); // signal thread to stop
9152 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009153 }
Andy Hungce685402018-10-05 17:23:27 -07009154
Andy Hung8d31fd22023-06-26 19:20:57 -07009155 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009156 ALOGV("Record stopped OK");
9157 return true;
9158 }
Andy Hungce685402018-10-05 17:23:27 -07009159
9160 // don't handle anything - we've been invalidated or restarted and in a different state
9161 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009162 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009163 return false;
9164}
9165
Andy Hungee58e4a2023-07-07 13:47:37 -07009166bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009167{
9168 return false;
9169}
9170
Andy Hungee58e4a2023-07-07 13:47:37 -07009171status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009172{
9173#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9174 if (!isValidSyncEvent(event)) {
9175 return BAD_VALUE;
9176 }
9177
Glenn Kastend848eb42016-03-08 13:42:11 -08009178 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009179 status_t ret = NAME_NOT_FOUND;
9180
Andy Hung972bec12023-08-31 16:13:39 -07009181 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009182
9183 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009184 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009185 if (eventSession == track->sessionId()) {
9186 (void) track->setSyncEvent(event);
9187 ret = NO_ERROR;
9188 }
9189 }
9190 return ret;
9191#else
9192 return BAD_VALUE;
9193#endif
9194}
9195
Andy Hungee58e4a2023-07-07 13:47:37 -07009196status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009197 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009198{
9199 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009200 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009201 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009202 return NO_INIT;
9203 }
jiabin9ff780e2018-03-19 18:19:52 -07009204 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9205 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009206}
9207
Andy Hungee58e4a2023-07-07 13:47:37 -07009208status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009209 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009210{
Paul McLean12340082019-03-19 09:35:05 -06009211 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009212 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009213 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009214 return NO_INIT;
9215 }
Paul McLean12340082019-03-19 09:35:05 -06009216 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009217}
9218
Andy Hungee58e4a2023-07-07 13:47:37 -07009219status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009220{
Paul McLean12340082019-03-19 09:35:05 -06009221 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009222 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009223 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009224 return NO_INIT;
9225 }
Paul McLean12340082019-03-19 09:35:05 -06009226 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009227}
9228
Andy Hungee58e4a2023-07-07 13:47:37 -07009229status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009230 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9231 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009232 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009233 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9234}
9235
Andy Hungee58e4a2023-07-07 13:47:37 -07009236status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009237 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9238 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009239
Eric Laurentec376dc2021-04-08 20:41:22 +02009240 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9241 return BAD_VALUE;
9242 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009243
9244 if (sharedAudioStartMs < 0
9245 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009246 return BAD_VALUE;
9247 }
9248
Eric Laurent2407ce32021-04-26 14:56:03 +02009249 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9250 // As we cannot detect more than one wraparound, only accept values up current write position
9251 // after one wraparound
9252 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9253 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009254 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009255 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9256 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009257 // Bring the start frame position within the input buffer to match the documented
9258 // "best effort" behavior of the API.
9259 if (sharedOffset < 0) {
9260 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009261 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009262 sharedAudioStartFrames =
9263 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009264 }
9265
Eric Laurentec376dc2021-04-08 20:41:22 +02009266 mSharedAudioPackageName = sharedAudioPackageName;
9267 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009268 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009269 } else {
9270 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009271 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009272 }
9273 return NO_ERROR;
9274}
9275
Andy Hungee58e4a2023-07-07 13:47:37 -07009276void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009277 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9278 mSharedAudioStartFrames = -1;
9279 mSharedAudioPackageName = "";
9280}
9281
Andy Hungee58e4a2023-07-07 13:47:37 -07009282ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009283{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009284 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009285 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009286 }
9287 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009288 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009289 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009290 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009291 }
9292 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009293 MetadataUpdate change;
9294 change.recordMetadataUpdate = metadata.tracks;
9295 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009296}
9297
Andy Hungc5007f82023-08-29 14:26:09 -07009298// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009299void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009300{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009301 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009302 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009303
Eric Laurent81784c32012-11-19 14:55:58 -08009304 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009305 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009306 removeTrack_l(track);
9307 }
9308}
9309
Andy Hungee58e4a2023-07-07 13:47:37 -07009310void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009311{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009312 String8 result;
9313 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009314 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009315
Eric Laurent81784c32012-11-19 14:55:58 -08009316 mTracks.remove(track);
9317 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009318 if (track->isFastTrack()) {
9319 ALOG_ASSERT(!mFastTrackAvail);
9320 mFastTrackAvail = true;
9321 }
Eric Laurent81784c32012-11-19 14:55:58 -08009322}
9323
Andy Hungee58e4a2023-07-07 13:47:37 -07009324void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009325{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009326 AudioStreamIn *input = mInput;
9327 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9328 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009329 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009330 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009331 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009332 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009333 }
Andy Hungbfa64962017-06-12 14:43:19 -07009334
9335 if (input != nullptr) {
9336 dprintf(fd, " Hal stream dump:\n");
9337 (void)input->stream->dump(fd);
9338 }
9339
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009340 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009341 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009342
Glenn Kasten2f90c512015-12-02 11:40:09 -08009343 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9344 // while we are dumping it. It may be inconsistent, but it won't mutate!
9345 // This is a large object so we place it on the heap.
9346 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009347 const std::unique_ptr<FastCaptureDumpState> copy =
9348 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009349 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009350}
9351
Andy Hungee58e4a2023-07-07 13:47:37 -07009352void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009353{
Eric Laurent81784c32012-11-19 14:55:58 -08009354 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009355 size_t numtracks = mTracks.size();
9356 size_t numactive = mActiveTracks.size();
9357 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009358 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009359 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009360 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009361 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009362 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009363 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009364 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009365 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009366 if (track != 0) {
9367 bool active = mActiveTracks.indexOf(track) >= 0;
9368 if (active) {
9369 numactiveseen++;
9370 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009371 result.append(prefix);
9372 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009373 }
Eric Laurent81784c32012-11-19 14:55:58 -08009374 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009375 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009376 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009377 }
9378
Marco Nelissenb2208842014-02-07 14:00:50 -08009379 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009380 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009381 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009382 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009383 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009384 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009385 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009386 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009387 result.append(prefix);
9388 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009389 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009390 }
Eric Laurent81784c32012-11-19 14:55:58 -08009391
9392 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009393 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009394}
9395
Andy Hungee58e4a2023-07-07 13:47:37 -07009396void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009397{
Andy Hung972bec12023-08-31 16:13:39 -07009398 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009399 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009400 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009401 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009402 track->setSilenced(silenced);
9403 }
9404 }
9405}
Andy Hung73c02e42015-03-29 01:13:58 -07009406
Andy Hung8d31fd22023-06-26 19:20:57 -07009407void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009408{
Andy Hung87c693c2023-07-06 20:56:16 -07009409 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009410 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009411 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009412 const int32_t rear = recordThread->mRsmpInRear;
9413 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009414 if (mRecordTrack->startFrames() >= 0) {
9415 int32_t startFrames = mRecordTrack->startFrames();
9416 // Accept a recent wraparound of mRsmpInRear
9417 if (startFrames <= rear) {
9418 deltaFrames = rear - startFrames;
9419 } else {
9420 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009421 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009422 // start frame cannot be further in the past than start of resampling buffer
9423 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9424 deltaFrames = recordThread->mRsmpInFrames;
9425 }
9426 }
9427 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009428}
9429
Andy Hung8d31fd22023-06-26 19:20:57 -07009430void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009431 size_t *framesAvailable, bool *hasOverrun)
9432{
Andy Hung87c693c2023-07-06 20:56:16 -07009433 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009434 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009435 const int32_t rear = recordThread->mRsmpInRear;
9436 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009437 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009438
9439 size_t framesIn;
9440 bool overrun = false;
9441 if (filled < 0) {
9442 // should not happen, but treat like a massive overrun and re-sync
9443 framesIn = 0;
9444 mRsmpInFront = rear;
9445 overrun = true;
9446 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9447 framesIn = (size_t) filled;
9448 } else {
9449 // client is not keeping up with server, but give it latest data
9450 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009451 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9452 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009453 overrun = true;
9454 }
9455 if (framesAvailable != NULL) {
9456 *framesAvailable = framesIn;
9457 }
9458 if (hasOverrun != NULL) {
9459 *hasOverrun = overrun;
9460 }
9461}
9462
Eric Laurent81784c32012-11-19 14:55:58 -08009463// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009464status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009465 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009466{
Andy Hung87c693c2023-07-06 20:56:16 -07009467 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009468 if (threadBase == 0) {
9469 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009470 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009471 return NOT_ENOUGH_DATA;
9472 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009473 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009474 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009475 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009476 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009477 // FIXME should not be P2 (don't want to increase latency)
9478 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009479 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009480 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009481
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009482 front &= recordThread->mRsmpInFramesP2 - 1;
9483 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009484 if (part1 > (size_t) filled) {
9485 part1 = filled;
9486 }
9487 size_t ask = buffer->frameCount;
9488 ALOG_ASSERT(ask > 0);
9489 if (part1 > ask) {
9490 part1 = ask;
9491 }
9492 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009493 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009494 buffer->raw = NULL;
9495 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009496 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009497 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009498 }
9499
Andy Hung57446612015-04-19 23:56:46 -07009500 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009501 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009502 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009503 return NO_ERROR;
9504}
9505
9506// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009507void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009508 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009509{
Hongwei Wang95e37682019-04-12 11:13:36 -07009510 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009511 if (stepCount == 0) {
9512 return;
9513 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009514 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009515 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009516 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009517 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009518 buffer->frameCount = 0;
9519}
9520
Andy Hungee58e4a2023-07-07 13:47:37 -07009521void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009522{
Andy Hung972bec12023-08-31 16:13:39 -07009523 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009524 checkBtNrec_l();
9525}
9526
Andy Hungee58e4a2023-07-07 13:47:37 -07009527void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009528{
9529 // disable AEC and NS if the device is a BT SCO headset supporting those
9530 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009531 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009532 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009533 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9534 for (size_t i = 0; i < mEffectChains.size(); i++) {
9535 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9536 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9537 }
9538 }
9539}
9540
Andy Hung97a893e2015-03-29 01:03:07 -07009541
Andy Hungee58e4a2023-07-07 13:47:37 -07009542bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009543 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009544{
9545 bool reconfig = false;
9546
Eric Laurent10351942014-05-08 18:49:52 -07009547 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009548
Eric Laurent10351942014-05-08 18:49:52 -07009549 audio_format_t reqFormat = mFormat;
9550 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009551 // 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 +08009552 [[maybe_unused]] audio_channel_mask_t channelMask =
9553 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009554
9555 AudioParameter param = AudioParameter(keyValuePair);
9556 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009557
9558 // scope for AutoPark extends to end of method
9559 AutoPark<FastCapture> park(mFastCapture);
9560
Eric Laurent10351942014-05-08 18:49:52 -07009561 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9562 // channel count change can be requested. Do we mandate the first client defines the
9563 // HAL sampling rate and channel count or do we allow changes on the fly?
9564 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9565 samplingRate = value;
9566 reconfig = true;
9567 }
9568 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009569 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009570 status = BAD_VALUE;
9571 } else {
9572 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009573 reconfig = true;
9574 }
Eric Laurent10351942014-05-08 18:49:52 -07009575 }
9576 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9577 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009578 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009579 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009580 status = BAD_VALUE;
9581 } else {
9582 channelMask = mask;
9583 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009584 }
Eric Laurent10351942014-05-08 18:49:52 -07009585 }
9586 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9587 // do not accept frame count changes if tracks are open as the track buffer
9588 // size depends on frame count and correct behavior would not be guaranteed
9589 // if frame count is changed after track creation
9590 if (mActiveTracks.size() > 0) {
9591 status = INVALID_OPERATION;
9592 } else {
9593 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009594 }
Eric Laurent10351942014-05-08 18:49:52 -07009595 }
9596 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009597 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009598 }
9599 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9600 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009601 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009602 }
Glenn Kastene198c362013-08-13 09:13:36 -07009603
Eric Laurent10351942014-05-08 18:49:52 -07009604 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009605 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009606 if (status == INVALID_OPERATION) {
9607 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009608 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009609 }
9610 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009611 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009612 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9613 if (mInput->stream->getAudioProperties(&config) == OK &&
9614 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9615 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009616 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009617 status = NO_ERROR;
9618 }
Eric Laurent81784c32012-11-19 14:55:58 -08009619 }
Eric Laurent10351942014-05-08 18:49:52 -07009620 if (status == NO_ERROR) {
9621 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009622 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009623 }
9624 }
Eric Laurent81784c32012-11-19 14:55:58 -08009625 }
Eric Laurent10351942014-05-08 18:49:52 -07009626
Eric Laurent81784c32012-11-19 14:55:58 -08009627 return reconfig;
9628}
9629
Andy Hungee58e4a2023-07-07 13:47:37 -07009630String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009631{
Andy Hung972bec12023-08-31 16:13:39 -07009632 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009633 if (initCheck() == NO_ERROR) {
9634 String8 out_s8;
9635 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9636 return out_s8;
9637 }
Eric Laurent81784c32012-11-19 14:55:58 -08009638 }
Andy Hung920f6572022-10-06 12:09:49 -07009639 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009640}
9641
Andy Hungab65b182023-09-06 19:41:47 -07009642void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009643 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009644 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009645 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009646 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009647 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009648 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009649 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9650 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009651 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009652 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009653 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009654 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009655 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009656 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009657 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009658 break;
9659 }
Andy Hungab65b182023-09-06 19:41:47 -07009660 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009661}
9662
Andy Hungee58e4a2023-07-07 13:47:37 -07009663void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009664{
Dean Wheatley6c009512023-10-23 09:34:14 +11009665 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9666 mSampleRate = audioConfig.sample_rate;
9667 mChannelMask = audioConfig.channel_mask;
9668 if (!audio_is_input_channel(mChannelMask)) {
9669 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9670 }
9671
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009672 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009673
9674 // Get actual HAL format.
9675 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9676 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9677 // Get format from the shim, which will be different than the HAL format
9678 // if recording compressed audio from IEC61937 wrapped sources.
9679 mFormat = audioConfig.format;
9680 if (!audio_is_valid_format(mFormat)) {
9681 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9682 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009683 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009684 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9685 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009686 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009687 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009688 ALOGI("HAL format %#x is not linear pcm", mFormat);
9689 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009690 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009691 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9692 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009693 result = mInput->stream->getBufferSize(&mBufferSize);
9694 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009695 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009696 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9697 "mBufferSize=%zu, mFrameCount=%zu",
9698 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009699
Eric Laurentec376dc2021-04-08 20:41:22 +02009700 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9701 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009702 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009703
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009704 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9705 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009706
9707 audio_input_flags_t flags = mInput->flags;
9708 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9709 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009710 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009711 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9712 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9713 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9714 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9715 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9716 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009717}
9718
Andy Hungee58e4a2023-07-07 13:47:37 -07009719uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009720{
Andy Hung972bec12023-08-31 16:13:39 -07009721 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009722 uint32_t result;
9723 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9724 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009725 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009726 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009727}
9728
Andy Hungee58e4a2023-07-07 13:47:37 -07009729KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009730{
Glenn Kastend848eb42016-03-08 13:42:11 -08009731 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009732 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009733 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009734 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009735 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009736 if (ids.indexOfKey(sessionId) < 0) {
9737 ids.add(sessionId, true);
9738 }
9739 }
9740 return ids;
9741}
9742
Andy Hungee58e4a2023-07-07 13:47:37 -07009743AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009744{
Andy Hung972bec12023-08-31 16:13:39 -07009745 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009746 AudioStreamIn *input = mInput;
9747 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009748 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009749 return input;
9750}
9751
Andy Hungc5007f82023-08-29 14:26:09 -07009752// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009753sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009754{
9755 if (mInput == NULL) {
9756 return NULL;
9757 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009758 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009759}
9760
Andy Hungee58e4a2023-07-07 13:47:37 -07009761status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009762{
Eric Laurent81784c32012-11-19 14:55:58 -08009763 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009764 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009765 chain->setInBuffer(NULL);
9766 chain->setOutBuffer(NULL);
9767
9768 checkSuspendOnAddEffectChain_l(chain);
9769
Eric Laurent1b928682014-10-02 19:41:47 -07009770 // make sure enabled pre processing effects state is communicated to the HAL as we
9771 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009772 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009773
Eric Laurent81784c32012-11-19 14:55:58 -08009774 mEffectChains.add(chain);
9775
9776 return NO_ERROR;
9777}
9778
Andy Hungee58e4a2023-07-07 13:47:37 -07009779size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009780{
9781 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009782
9783 for (size_t i = 0; i < mEffectChains.size(); i++) {
9784 if (chain == mEffectChains[i]) {
9785 mEffectChains.removeAt(i);
9786 break;
9787 }
Eric Laurent81784c32012-11-19 14:55:58 -08009788 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009789 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009790}
9791
Andy Hungee58e4a2023-07-07 13:47:37 -07009792status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009793 audio_patch_handle_t *handle)
9794{
9795 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009796
9797 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009798 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009799 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009800 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009801 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009802 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009803 }
9804
Eric Laurentd8365c52017-07-16 15:27:05 -07009805 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009806
9807 // store new source and send to effects
9808 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9809 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009810 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009811 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009812 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009813 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009814
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009815 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009816 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9817 status = hwDevice->createAudioPatch(patch->num_sources,
9818 patch->sources,
9819 patch->num_sinks,
9820 patch->sinks,
9821 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009822 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009823 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9824 patch->sinks[0].ext.mix.usecase.source,
9825 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009826 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009827 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009828
jiabinc52b1ff2019-10-31 17:20:42 -07009829 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009830 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009831 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009832 }
Eric Laurent296fb132015-05-01 11:38:42 -07009833
Andy Hungc2b11cb2020-04-22 09:04:01 -07009834 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009835 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009836 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009837 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009838 // also dispatch to active AudioRecords
9839 for (const auto &track : mActiveTracks) {
9840 track->logEndInterval();
9841 track->logBeginInterval(pathSourcesAsString);
9842 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009843 // Force meteadata update after a route change
9844 mActiveTracks.setHasChanged();
9845
Eric Laurent1c333e22014-05-20 10:48:17 -07009846 return status;
9847}
9848
Andy Hungee58e4a2023-07-07 13:47:37 -07009849status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009850{
9851 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009852
jiabinc52b1ff2019-10-31 17:20:42 -07009853 mPatch = audio_patch{};
9854 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009855
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009856 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009857 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9858 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009859 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009860 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009861 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009862 // Force meteadata update after a route change
9863 mActiveTracks.setHasChanged();
9864
Eric Laurent1c333e22014-05-20 10:48:17 -07009865 return status;
9866}
9867
Andy Hungee58e4a2023-07-07 13:47:37 -07009868void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009869{
Andy Hung972bec12023-08-31 16:13:39 -07009870 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009871 mOutDevices = outDevices;
9872 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9873 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009874 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009875 }
9876}
9877
Andy Hungee58e4a2023-07-07 13:47:37 -07009878int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009879{
9880 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009881 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009882 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009883 int32_t oldestFront = mRsmpInRear;
9884 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009885 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009886 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009887 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009888 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009889 if (filled > maxFilled) {
9890 oldestFront = front;
9891 maxFilled = filled;
9892 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009893 }
Andy Hung920f6572022-10-06 12:09:49 -07009894 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009895 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9896 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009897 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009898}
9899
Andy Hungee58e4a2023-07-07 13:47:37 -07009900void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009901{
9902 if (offset == 0) {
9903 return;
9904 }
9905 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009906 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009907 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009908 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009909 }
9910}
9911
Andy Hungee58e4a2023-07-07 13:47:37 -07009912void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009913{
9914 // This is the formula for calculating the temporary buffer size.
9915 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9916 // 1 full output buffer, regardless of the alignment of the available input.
9917 // The value is somewhat arbitrary, and could probably be even larger.
9918 // A larger value should allow more old data to be read after a track calls start(),
9919 // without increasing latency.
9920 //
9921 // Note this is independent of the maximum downsampling ratio permitted for capture.
9922 size_t minRsmpInFrames = mFrameCount * 7;
9923
9924 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9925 // capture history available to another client using the same session ID:
9926 // dimension the resampler input buffer accordingly.
9927
9928 // Get oldest client read position: getOldestFront_l() must be called before altering
9929 // mRsmpInRear, or mRsmpInFrames
9930 int32_t previousFront = getOldestFront_l();
9931 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9932 int32_t previousRear = mRsmpInRear;
9933 mRsmpInRear = 0;
9934
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009935 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009936 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009937 "resizeInputBuffer_l() called with invalid max shared history %d",
9938 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009939 if (maxSharedAudioHistoryMs != 0) {
9940 // resizeInputBuffer_l should never be called with a non zero shared history if the
9941 // buffer was not already allocated
9942 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9943 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9944 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9945 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009946 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009947 return;
9948 }
9949 mRsmpInFrames = rsmpInFrames;
9950 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009951 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009952 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9953 // initialized
9954 if (mRsmpInFrames < minRsmpInFrames) {
9955 mRsmpInFrames = minRsmpInFrames;
9956 }
9957 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9958
9959 // TODO optimize audio capture buffer sizes ...
9960 // Here we calculate the size of the sliding buffer used as a source
9961 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9962 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9963 // be better to have it derived from the pipe depth in the long term.
9964 // The current value is higher than necessary. However it should not add to latency.
9965
9966 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9967 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9968
9969 void *rsmpInBuffer;
9970 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9971 // if posix_memalign fails, will segv here.
9972 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9973
9974 // Copy audio history if any from old buffer before freeing it
9975 if (previousRear != 0) {
9976 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9977 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9978
9979 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9980 previousFront &= previousRsmpInFramesP2 - 1;
9981 size_t part1 = previousRsmpInFramesP2 - previousFront;
9982 if (part1 > (size_t) unread) {
9983 part1 = unread;
9984 }
9985 if (part1 != 0) {
9986 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9987 part1 * mFrameSize);
9988 mRsmpInRear = part1;
9989 part1 = unread - part1;
9990 if (part1 != 0) {
9991 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9992 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9993 mRsmpInRear += part1;
9994 }
9995 }
9996 // Update front for all clients according to new rear
9997 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9998 } else {
9999 mRsmpInRear = 0;
10000 }
10001 free(mRsmpInBuffer);
10002 mRsmpInBuffer = rsmpInBuffer;
10003}
10004
Andy Hungee58e4a2023-07-07 13:47:37 -070010005void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010006{
Andy Hung972bec12023-08-31 16:13:39 -070010007 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010008 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010009 if (record->getSource()) {
10010 mSource = record->getSource();
10011 }
Eric Laurent83b88082014-06-20 18:31:16 -070010012}
10013
Andy Hungee58e4a2023-07-07 13:47:37 -070010014void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010015{
Andy Hung972bec12023-08-31 16:13:39 -070010016 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010017 if (mSource == record->getSource()) {
10018 mSource = mInput;
10019 }
Eric Laurent83b88082014-06-20 18:31:16 -070010020 destroyTrack_l(record);
10021}
10022
Andy Hungee58e4a2023-07-07 13:47:37 -070010023void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010024{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010025 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010026 config->role = AUDIO_PORT_ROLE_SINK;
10027 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10028 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010029 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10030 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10031 config->flags.input = mInput->flags;
10032 }
Eric Laurent83b88082014-06-20 18:31:16 -070010033}
Eric Laurent1c333e22014-05-20 10:48:17 -070010034
Eric Laurent6acd1d42017-01-04 14:23:29 -080010035// ----------------------------------------------------------------------------
10036// Mmap
10037// ----------------------------------------------------------------------------
10038
Andy Hung7aa7d102023-07-07 15:58:48 -070010039// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10040// MmapPlaybackThread or MmapCaptureThread instance.
10041class MmapThreadHandle : public MmapStreamInterface {
10042public:
10043 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10044 ~MmapThreadHandle() override;
10045
10046 // MmapStreamInterface virtuals
10047 status_t createMmapBuffer(int32_t minSizeFrames,
10048 struct audio_mmap_buffer_info* info) final;
10049 status_t getMmapPosition(struct audio_mmap_position* position) final;
10050 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10051 status_t start(const AudioClient& client,
10052 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10053 status_t stop(audio_port_handle_t handle) final;
10054 status_t standby() final;
10055 status_t reportData(const void* buffer, size_t frameCount) final;
10056private:
10057 const sp<IAfMmapThread> mThread;
10058};
10059
10060/* static */
10061sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10062 const sp<IAfMmapThread>& mmapThread) {
10063 return sp<MmapThreadHandle>::make(mmapThread);
10064}
10065
10066MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010067 : mThread(thread)
10068{
Phil Burk9fabbf82017-08-03 12:02:00 -070010069 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010070}
10071
Andy Hung7aa7d102023-07-07 15:58:48 -070010072// MmapStreamInterface could be directly implemented by MmapThread excepting this
10073// special handling on adapter dtor.
10074MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075{
Phil Burk9fabbf82017-08-03 12:02:00 -070010076 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010077}
10078
Andy Hung7aa7d102023-07-07 15:58:48 -070010079status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010080 struct audio_mmap_buffer_info *info)
10081{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010082 return mThread->createMmapBuffer(minSizeFrames, info);
10083}
10084
Andy Hung7aa7d102023-07-07 15:58:48 -070010085status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010086{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010087 return mThread->getMmapPosition(position);
10088}
10089
Andy Hung7aa7d102023-07-07 15:58:48 -070010090status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010091 int64_t *timeNanos) {
10092 return mThread->getExternalPosition(position, timeNanos);
10093}
10094
Andy Hung7aa7d102023-07-07 15:58:48 -070010095status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010096 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010097{
jiabind1f1cb62020-03-24 11:57:57 -070010098 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010099}
10100
Andy Hung7aa7d102023-07-07 15:58:48 -070010101status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010102{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010103 return mThread->stop(handle);
10104}
10105
Andy Hung7aa7d102023-07-07 15:58:48 -070010106status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010107{
Eric Laurent18b57012017-02-13 16:23:52 -080010108 return mThread->standby();
10109}
10110
Andy Hung7aa7d102023-07-07 15:58:48 -070010111status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10112{
jiabinfc791ee2023-02-15 19:43:40 +000010113 return mThread->reportData(buffer, frameCount);
10114}
10115
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116
Andy Hungee58e4a2023-07-07 13:47:37 -070010117MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010118 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010119 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010120 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010121 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010122 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010123 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010124 mActiveTracks(&this->mLocalLog),
10125 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10126 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010127{
Eric Laurent18b57012017-02-13 16:23:52 -080010128 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010129 readHalParameters_l();
10130}
10131
Andy Hungee58e4a2023-07-07 13:47:37 -070010132void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010133{
10134 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10135}
10136
Andy Hungee58e4a2023-07-07 13:47:37 -070010137void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138{
Andy Hung8d31fd22023-06-26 19:20:57 -070010139 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010140 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010141 {
Andy Hung972bec12023-08-31 16:13:39 -070010142 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010143 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010144 activeTracks.add(t);
10145 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010146 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010147 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010148 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149 stop(t->portId());
10150 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010151 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010153 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010154 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010155 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156 }
10157}
10158
10159
Andy Hung8d672e02023-09-15 18:19:28 -070010160void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 audio_stream_type_t streamType __unused,
10162 audio_session_t sessionId,
10163 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010164 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 audio_port_handle_t portId)
10166{
10167 mAttr = *attr;
10168 mSessionId = sessionId;
10169 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010170 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010171 mPortId = portId;
10172}
10173
Andy Hungee58e4a2023-07-07 13:47:37 -070010174status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010175 struct audio_mmap_buffer_info *info)
10176{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010177 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 if (mHalStream == 0) {
10179 return NO_INIT;
10180 }
Eric Laurent18b57012017-02-13 16:23:52 -080010181 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010182 return mHalStream->createMmapBuffer(minSizeFrames, info);
10183}
10184
Andy Hungee58e4a2023-07-07 13:47:37 -070010185status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010186{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010187 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010188 if (mHalStream == 0) {
10189 return NO_INIT;
10190 }
10191 return mHalStream->getMmapPosition(position);
10192}
10193
Andy Hungee58e4a2023-07-07 13:47:37 -070010194status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010195{
Eric Laurentdda206a2022-07-08 17:28:35 +020010196 // The HAL must receive track metadata before starting the stream
10197 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010198 status_t ret = mHalStream->start();
10199 if (ret != NO_ERROR) {
10200 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10201 return ret;
10202 }
Andy Hungcf10d742020-04-28 15:38:24 -070010203 if (mStandby) {
10204 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010205 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010206 mStandby = false;
10207 }
Eric Laurent331679c2018-04-16 17:03:16 -070010208 return NO_ERROR;
10209}
10210
Andy Hungee58e4a2023-07-07 13:47:37 -070010211status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010212 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213 audio_port_handle_t *handle)
10214{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010215 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010216 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010217 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010218 if (mHalStream == 0) {
10219 return NO_INIT;
10220 }
10221
10222 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010223
Eric Laurentdda206a2022-07-08 17:28:35 +020010224 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010225 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010226 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010227 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010228 }
10229
10230 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10231
10232 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010233 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010234 client.attributionSource);
10235
Andy Hung3f49ebb2023-09-19 14:48:41 -070010236 const auto localSessionId = mSessionId;
10237 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010238 if (isOutput()) {
10239 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10240 config.sample_rate = mSampleRate;
10241 config.channel_mask = mChannelMask;
10242 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010243 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010244 audio_output_flags_t flags =
10245 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010246 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010247 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010248 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010249 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010250 mutex().unlock();
10251 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10252 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010253 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010254 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010255 &config,
10256 flags,
10257 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010258 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010259 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010260 &isSpatialized,
10261 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010262 mutex().lock();
10263 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010264 ALOGD_IF(!secondaryOutputs.empty(),
10265 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010267 audio_config_base_t config;
10268 config.sample_rate = mSampleRate;
10269 config.channel_mask = mChannelMask;
10270 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010271 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010272 mutex().unlock();
10273 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010274 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010275 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010276 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010277 &config,
10278 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10279 &deviceId,
10280 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010281 mutex().lock();
10282 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010283 }
10284 // APM should not chose a different input or output stream for the same set of attributes
10285 // and audo configuration
10286 if (ret != NO_ERROR || io != mId) {
10287 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10288 __FUNCTION__, ret, io, mId);
10289 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290 }
10291
10292 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010293 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010294 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010295 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296 } else {
jiabin09609032022-06-15 19:26:01 +000010297 {
10298 // Add the track record before starting input so that the silent status for the
10299 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010300 setClientSilencedState_l(portId, false /*silenced*/);
10301 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010302 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010303 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010304 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305 }
10306
10307 // abort if start is rejected by audio policy manager
10308 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010309 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010310 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010311 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010313 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010315 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 }
Andy Hungc5007f82023-08-29 14:26:09 -070010317 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010318 } else {
10319 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010320 }
jiabin09609032022-06-15 19:26:01 +000010321 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322 return PERMISSION_DENIED;
10323 }
10324
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010325 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010326 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10327 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010328 mChannelMask, mSessionId, isOutput(),
10329 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010330 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010331 if (!isOutput()) {
10332 track->setSilenced_l(isClientSilenced_l(portId));
10333 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010334
Eric Laurent4eb58f12018-12-07 16:41:02 -080010335 if (isOutput()) {
10336 // force volume update when a new track is added
10337 mHalVolFloat = -1.0f;
10338 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010339 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010340 if (t->isSilenced_l()
10341 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010342 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010343 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010344 }
10345 }
10346
Eric Laurent6acd1d42017-01-04 14:23:29 -080010347 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010348 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010350 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351 chain->incTrackCnt();
10352 chain->incActiveTrackCnt();
10353 }
10354
Andy Hungc2b11cb2020-04-22 09:04:01 -070010355 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010357
10358 if (mActiveTracks.size() == 1) {
10359 ret = exitStandby_l();
10360 }
10361
Eric Laurent6acd1d42017-01-04 14:23:29 -080010362 broadcast_l();
10363
Eric Laurentdda206a2022-07-08 17:28:35 +020010364 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365
Eric Laurentdda206a2022-07-08 17:28:35 +020010366 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010367}
10368
Andy Hungee58e4a2023-07-07 13:47:37 -070010369status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010371 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010372 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010373
10374 if (mHalStream == 0) {
10375 return NO_INIT;
10376 }
10377
Eric Laurenta54f1282017-07-01 19:39:32 -070010378 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010379 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010380 return NO_ERROR;
10381 }
10382
Andy Hung8d31fd22023-06-26 19:20:57 -070010383 sp<IAfMmapTrack> track;
10384 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385 if (handle == t->portId()) {
10386 track = t;
10387 break;
10388 }
10389 }
10390 if (track == 0) {
10391 return BAD_VALUE;
10392 }
10393
10394 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010395 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396
Andy Hungc5007f82023-08-29 14:26:09 -070010397 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010398 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010399 AudioSystem::stopOutput(track->portId());
10400 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010402 AudioSystem::stopInput(track->portId());
10403 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010404 }
Andy Hungc5007f82023-08-29 14:26:09 -070010405 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406
Andy Hung116bc262023-06-20 18:56:17 -070010407 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010408 if (chain != 0) {
10409 chain->decActiveTrackCnt();
10410 chain->decTrackCnt();
10411 }
10412
Eric Laurentdda206a2022-07-08 17:28:35 +020010413 if (mActiveTracks.isEmpty()) {
10414 mHalStream->stop();
10415 }
10416
Eric Laurent6acd1d42017-01-04 14:23:29 -080010417 broadcast_l();
10418
Eric Laurent6acd1d42017-01-04 14:23:29 -080010419 return NO_ERROR;
10420}
10421
Andy Hungee58e4a2023-07-07 13:47:37 -070010422status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010423NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010424{
10425 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010426 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010427
10428 if (mHalStream == 0) {
10429 return NO_INIT;
10430 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010431 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010432 return INVALID_OPERATION;
10433 }
10434 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010435 if (!mStandby) {
10436 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010437 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010438 mStandby = true;
10439 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010440 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010441 return NO_ERROR;
10442}
10443
Andy Hungee58e4a2023-07-07 13:47:37 -070010444status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010445 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10446 return INVALID_OPERATION;
10447}
10448
Andy Hungee58e4a2023-07-07 13:47:37 -070010449void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010450{
10451 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10452 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10453 mFormat = mHALFormat;
10454 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10455 result = mHalStream->getFrameSize(&mFrameSize);
10456 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010457 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10458 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459 result = mHalStream->getBufferSize(&mBufferSize);
10460 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10461 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010462
Andy Hungcf10d742020-04-28 15:38:24 -070010463 // TODO: make a readHalParameters call?
10464 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010465 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010466 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010467 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10468 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10469 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10470 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10471 /*
10472 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10473 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10474 (int32_t)mHapticChannelMask)
10475 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10476 (int32_t)mHapticChannelCount)
10477 */
10478 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010479 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010480 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10481 (int32_t)mFrameCount) // sic - added HAL
10482 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010483}
10484
Andy Hungee58e4a2023-07-07 13:47:37 -070010485bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486{
Andy Hungab65b182023-09-06 19:41:47 -070010487 {
10488 audio_utils::unique_lock _l(mutex());
10489 checkSilentMode_l();
10490 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491
10492 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10493
10494 while (!exitPending())
10495 {
Andy Hung116bc262023-06-20 18:56:17 -070010496 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497
Andy Hung13850be2019-03-14 11:33:09 -070010498 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010499 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010500
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501 if (mSignalPending) {
10502 // A signal was raised while we were unlocked
10503 mSignalPending = false;
10504 } else {
10505 if (mConfigEvents.isEmpty()) {
10506 // we're about to wait, flush the binder command buffer
10507 IPCThreadState::self()->flushCommands();
10508
10509 if (exitPending()) {
10510 break;
10511 }
10512
Eric Laurent6acd1d42017-01-04 14:23:29 -080010513 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010514 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010515 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010516 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010517
10518 checkSilentMode_l();
10519
10520 continue;
10521 }
10522 }
10523
10524 processConfigEvents_l();
10525
10526 processVolume_l();
10527
10528 checkInvalidTracks_l();
10529
Andy Hungab65b182023-09-06 19:41:47 -070010530 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531
Kevin Rocard069c2712018-03-29 19:09:14 -070010532 updateMetadata_l();
10533
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010535 } // release Thread lock
10536
Eric Laurent6acd1d42017-01-04 14:23:29 -080010537 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010538 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010539 }
Andy Hung13850be2019-03-14 11:33:09 -070010540
10541 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010542 unlockEffectChains(effectChains);
10543 // Effect chains will be actually deleted here if they were removed from
10544 // mEffectChains list during mixing or effects processing
10545 }
10546
10547 threadLoop_exit();
10548
10549 if (!mStandby) {
10550 threadLoop_standby();
10551 mStandby = true;
10552 }
10553
Eric Laurent6acd1d42017-01-04 14:23:29 -080010554 ALOGV("Thread %p type %d exiting", this, mType);
10555 return false;
10556}
10557
Andy Hungc5007f82023-08-29 14:26:09 -070010558// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010559bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 status_t& status)
10561{
10562 AudioParameter param = AudioParameter(keyValuePair);
10563 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010564 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010566 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010568 if (sendToHal) {
10569 status = mHalStream->setParameters(keyValuePair);
10570 } else {
10571 status = NO_ERROR;
10572 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573
10574 return false;
10575}
10576
Andy Hungee58e4a2023-07-07 13:47:37 -070010577String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578{
Andy Hung972bec12023-08-31 16:13:39 -070010579 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580 String8 out_s8;
10581 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10582 return out_s8;
10583 }
Andy Hung920f6572022-10-06 12:09:49 -070010584 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010585}
10586
Andy Hungab65b182023-09-06 19:41:47 -070010587void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010588 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010589 sp<AudioIoDescriptor> desc;
10590 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 switch (event) {
10592 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010593 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010595 isInput = true;
10596 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010597 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010598 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010600 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10601 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603 case AUDIO_INPUT_CLOSED:
10604 case AUDIO_OUTPUT_CLOSED:
10605 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010606 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 break;
10608 }
Andy Hungab65b182023-09-06 19:41:47 -070010609 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010610}
10611
Andy Hungee58e4a2023-07-07 13:47:37 -070010612status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010613 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010614NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615{
10616 status_t status = NO_ERROR;
10617
10618 // store new device and send to effects
10619 audio_devices_t type = AUDIO_DEVICE_NONE;
10620 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010621 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10622 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10623 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624 if (isOutput()) {
10625 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010626 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10627 && !mAudioHwDev->supportsAudioPatches(),
10628 "Enumerated device type(%#x) must not be used "
10629 "as it does not support audio patches",
10630 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010631 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010632 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10633 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634 }
10635 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010636 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 } else {
10638 type = patch->sources[0].ext.device.type;
10639 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010640 numDevices = mPatch.num_sources;
10641 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010642 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643 }
10644
10645 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010646 if (isOutput()) {
10647 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10648 } else {
10649 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10650 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010651 }
10652
jiabinc52b1ff2019-10-31 17:20:42 -070010653 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 // store new source and send to effects
10655 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10656 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10657 for (size_t i = 0; i < mEffectChains.size(); i++) {
10658 mEffectChains[i]->setAudioSource_l(mAudioSource);
10659 }
10660 }
10661 }
10662
10663 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010664 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10665 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010666 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010667 audio_port_config port;
10668 std::optional<audio_source_t> source;
10669 if (isOutput()) {
10670 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010672 port = patch->sources[0];
10673 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010674 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010675 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676 *handle = AUDIO_PATCH_HANDLE_NONE;
10677 }
10678
jiabinc52b1ff2019-10-31 17:20:42 -070010679 if (numDevices == 0 || mDeviceId != deviceId) {
10680 if (isOutput()) {
10681 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10682 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010683 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010684 } else {
10685 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10686 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10687 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010688 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010689 if (mDeviceId != deviceId && callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010690 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010691 callback->onRoutingChanged(deviceId);
Andy Hungc5007f82023-08-29 14:26:09 -070010692 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010693 }
jiabinc52b1ff2019-10-31 17:20:42 -070010694 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010695 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010697 // Force meteadata update after a route change
10698 mActiveTracks.setHasChanged();
10699
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700 return status;
10701}
10702
Andy Hungee58e4a2023-07-07 13:47:37 -070010703status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704{
10705 status_t status = NO_ERROR;
10706
jiabinc52b1ff2019-10-31 17:20:42 -070010707 mPatch = audio_patch{};
10708 mOutDeviceTypeAddrs.clear();
10709 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010710
10711 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10712 supportsAudioPatches : false;
10713
10714 if (supportsAudioPatches) {
10715 status = mHalDevice->releaseAudioPatch(handle);
10716 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010717 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010718 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010719 // Force meteadata update after a route change
10720 mActiveTracks.setHasChanged();
10721
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 return status;
10723}
10724
Andy Hungee58e4a2023-07-07 13:47:37 -070010725void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010726NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010728 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010729 if (isOutput()) {
10730 config->role = AUDIO_PORT_ROLE_SOURCE;
10731 config->ext.mix.hw_module = mAudioHwDev->handle();
10732 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10733 } else {
10734 config->role = AUDIO_PORT_ROLE_SINK;
10735 config->ext.mix.hw_module = mAudioHwDev->handle();
10736 config->ext.mix.usecase.source = mAudioSource;
10737 }
10738}
10739
Andy Hungee58e4a2023-07-07 13:47:37 -070010740status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010741{
10742 audio_session_t session = chain->sessionId();
10743
10744 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10745 // Attach all tracks with same session ID to this chain.
10746 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010747 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010748 if (session == track->sessionId()) {
10749 chain->incTrackCnt();
10750 chain->incActiveTrackCnt();
10751 }
10752 }
10753
10754 chain->setThread(this);
10755 chain->setInBuffer(nullptr);
10756 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010757 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758
10759 mEffectChains.add(chain);
10760 checkSuspendOnAddEffectChain_l(chain);
10761 return NO_ERROR;
10762}
10763
Andy Hungee58e4a2023-07-07 13:47:37 -070010764size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010765{
10766 audio_session_t session = chain->sessionId();
10767
10768 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10769
10770 for (size_t i = 0; i < mEffectChains.size(); i++) {
10771 if (chain == mEffectChains[i]) {
10772 mEffectChains.removeAt(i);
10773 // detach all active tracks from the chain
10774 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010775 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776 if (session == track->sessionId()) {
10777 chain->decActiveTrackCnt();
10778 chain->decTrackCnt();
10779 }
10780 }
10781 break;
10782 }
10783 }
10784 return mEffectChains.size();
10785}
10786
Andy Hungee58e4a2023-07-07 13:47:37 -070010787void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010788{
10789 mHalStream->standby();
10790}
10791
Andy Hungee58e4a2023-07-07 13:47:37 -070010792void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793{
Phil Burk7dce7282017-09-27 13:51:41 -070010794 // Do not call callback->onTearDown() because it is redundant for thread exit
10795 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010796}
10797
Andy Hungee58e4a2023-07-07 13:47:37 -070010798status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010799{
10800 return BAD_VALUE;
10801}
10802
Andy Hungee58e4a2023-07-07 13:47:37 -070010803bool MmapThread::isValidSyncEvent(
10804 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010805{
10806 return false;
10807}
10808
Andy Hungee58e4a2023-07-07 13:47:37 -070010809status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010810 const effect_descriptor_t *desc, audio_session_t sessionId)
10811{
10812 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010813 if (audio_is_global_session(sessionId)) {
10814 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010815 desc->name, mThreadName);
10816 return BAD_VALUE;
10817 }
10818
10819 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10820 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10821 desc->name);
10822 return BAD_VALUE;
10823 }
10824 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010825 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10826 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827 return BAD_VALUE;
10828 }
10829
10830 // Only allow effects without processing load or latency
10831 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10832 return BAD_VALUE;
10833 }
10834
Andy Hung116bc262023-06-20 18:56:17 -070010835 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010836 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10837 return BAD_VALUE;
10838 }
10839
Eric Laurent6acd1d42017-01-04 14:23:29 -080010840 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010841}
10842
Andy Hungee58e4a2023-07-07 13:47:37 -070010843void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844{
Eric Laurent039c24a2022-10-07 14:01:59 +020010845 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010846 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010847 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010848 callback = mCallback.promote();
10849 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10850 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10851 mNoCallbackWarningCount++;
10852 }
10853 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854 }
10855 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010856 if (callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010857 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010858 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungc5007f82023-08-29 14:26:09 -070010859 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010860 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861}
10862
Andy Hungee58e4a2023-07-07 13:47:37 -070010863void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010864{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010865 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10866 mAttr.content_type, mAttr.usage, mAttr.source);
10867 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010868 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010869 dprintf(fd, " No active clients\n");
10870 }
10871}
10872
Andy Hungee58e4a2023-07-07 13:47:37 -070010873void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010874{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010875 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010876 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010877 dprintf(fd, " %zu Tracks\n", numtracks);
10878 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010879 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010880 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010881 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010882 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010883 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010884 result.append(prefix);
10885 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886 }
10887 } else {
10888 dprintf(fd, "\n");
10889 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010890 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010891}
10892
Andy Hungee58e4a2023-07-07 13:47:37 -070010893/* static */
10894sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010895 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010896 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010897 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010898}
10899
10900MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010901 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010902 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010903 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010904 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010905 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010906{
10907 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10908 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010909 mMasterVolume = afThreadCallback->masterVolume_l();
10910 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010911
10912 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10913 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10914 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010915 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010916 }
10917 // Audio patch and call assistant volume are always max
10918 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10919 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10920 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10921 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10922
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923 if (mAudioHwDev) {
10924 if (mAudioHwDev->canSetMasterVolume()) {
10925 mMasterVolume = 1.0;
10926 }
10927
10928 if (mAudioHwDev->canSetMasterMute()) {
10929 mMasterMute = false;
10930 }
10931 }
10932}
10933
Andy Hungee58e4a2023-07-07 13:47:37 -070010934void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935 audio_stream_type_t streamType,
10936 audio_session_t sessionId,
10937 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010938 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010939 audio_port_handle_t portId)
10940{
Andy Hung8d672e02023-09-15 18:19:28 -070010941 audio_utils::lock_guard l(mutex());
10942 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010943 mStreamType = streamType;
10944}
10945
Andy Hungee58e4a2023-07-07 13:47:37 -070010946AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010947{
Andy Hung972bec12023-08-31 16:13:39 -070010948 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010949 AudioStreamOut *output = mOutput;
10950 mOutput = NULL;
10951 return output;
10952}
10953
Andy Hungee58e4a2023-07-07 13:47:37 -070010954void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010955{
Andy Hung972bec12023-08-31 16:13:39 -070010956 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010957 // Don't apply master volume in SW if our HAL can do it for us.
10958 if (mAudioHwDev &&
10959 mAudioHwDev->canSetMasterVolume()) {
10960 mMasterVolume = 1.0;
10961 } else {
10962 mMasterVolume = value;
10963 }
10964}
10965
Andy Hungee58e4a2023-07-07 13:47:37 -070010966void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010967{
Andy Hung972bec12023-08-31 16:13:39 -070010968 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969 // Don't apply master mute in SW if our HAL can do it for us.
10970 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10971 mMasterMute = false;
10972 } else {
10973 mMasterMute = muted;
10974 }
10975}
10976
Andy Hungee58e4a2023-07-07 13:47:37 -070010977void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010978{
Andy Hung972bec12023-08-31 16:13:39 -070010979 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010980 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010981 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010982 broadcast_l();
10983 }
10984}
10985
Andy Hungee58e4a2023-07-07 13:47:37 -070010986float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010987{
Andy Hung972bec12023-08-31 16:13:39 -070010988 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010989 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010990}
10991
Andy Hungee58e4a2023-07-07 13:47:37 -070010992void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010993{
Andy Hung972bec12023-08-31 16:13:39 -070010994 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010995 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010996 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010997 broadcast_l();
10998 }
10999}
11000
Andy Hungee58e4a2023-07-07 13:47:37 -070011001void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011002{
Andy Hung972bec12023-08-31 16:13:39 -070011003 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011004 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011005 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011006 track->invalidate();
11007 }
11008 broadcast_l();
11009 }
11010}
11011
Andy Hungee58e4a2023-07-07 13:47:37 -070011012void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011013{
Andy Hung972bec12023-08-31 16:13:39 -070011014 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011015 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011016 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011017 if (portIds.find(track->portId()) != portIds.end()) {
11018 track->invalidate();
11019 trackMatch = true;
11020 portIds.erase(track->portId());
11021 }
11022 if (portIds.empty()) {
11023 break;
11024 }
11025 }
11026 if (trackMatch) {
11027 broadcast_l();
11028 }
11029}
11030
Andy Hungee58e4a2023-07-07 13:47:37 -070011031void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011032NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033{
11034 float volume;
11035
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011036 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011037 volume = 0;
11038 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011039 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011040 }
11041
11042 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 // Convert volumes from float to 8.24
11044 uint32_t vol = (uint32_t)(volume * (1 << 24));
11045
11046 // Delegate volume control to effect in track effect chain if needed
11047 // only one effect chain can be present on DirectOutputThread, so if
11048 // there is one, the track is connected to it
11049 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011050 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051 volume = (float)vol / (1 << 24);
11052 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011053 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011054 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11055 mHalVolFloat = volume; // HW volume control worked, so update value.
11056 mNoCallbackWarningCount = 0;
11057 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011058 sp<MmapStreamCallback> callback = mCallback.promote();
11059 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011060 mHalVolFloat = volume; // SW volume control worked, so update value.
11061 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011062 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011063 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011064 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011065 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011066 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11067 ALOGW("Could not set MMAP stream volume: no volume callback!");
11068 mNoCallbackWarningCount++;
11069 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011070 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011071 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011072 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011073 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070011074 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011075 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011076 streamVolume_l() == 0.f,
11077 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011078 // TODO(b/241533526): adjust logic to include mute from AppOps
11079 false /*muteFromPlaybackRestricted*/,
11080 false /*muteFromClientVolume*/,
11081 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011082 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011083 }
11084}
11085
Andy Hungee58e4a2023-07-07 13:47:37 -070011086ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011087{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011088 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011089 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011090 }
11091 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011092 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011093 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011094 playback_track_metadata_v7_t trackMetadata;
11095 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011096 .usage = track->attributes().usage,
11097 .content_type = track->attributes().content_type,
11098 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011099 };
11100 trackMetadata.channel_mask = track->channelMask(),
11101 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11102 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011103 }
11104 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011105
11106 MetadataUpdate change;
11107 change.playbackMetadataUpdate = metadata.tracks;
11108 return change;
11109};
Kevin Rocard069c2712018-03-29 19:09:14 -070011110
Andy Hungee58e4a2023-07-07 13:47:37 -070011111void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011112{
11113 if (!mMasterMute) {
11114 char value[PROPERTY_VALUE_MAX];
11115 if (property_get("ro.audio.silent", value, "0") > 0) {
11116 char *endptr;
11117 unsigned long ul = strtoul(value, &endptr, 0);
11118 if (*endptr == '\0' && ul != 0) {
11119 ALOGD("Silence is golden");
11120 // The setprop command will not allow a property to be changed after
11121 // the first time it is set, so we don't have to worry about un-muting.
11122 setMasterMute_l(true);
11123 }
11124 }
11125 }
11126}
11127
Andy Hungee58e4a2023-07-07 13:47:37 -070011128void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011129{
11130 MmapThread::toAudioPortConfig(config);
11131 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11132 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11133 config->flags.output = mOutput->flags;
11134 }
11135}
11136
Andy Hungee58e4a2023-07-07 13:47:37 -070011137status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011138 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011139{
11140 if (mOutput == nullptr) {
11141 return NO_INIT;
11142 }
11143 struct timespec timestamp;
11144 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11145 if (status == NO_ERROR) {
11146 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11147 }
11148 return status;
11149}
11150
Andy Hungee58e4a2023-07-07 13:47:37 -070011151status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011152 // Send to MelProcessor for sound dose measurement.
11153 auto processor = mMelProcessor.load();
11154 if (processor) {
11155 processor->process(buffer, frameCount * mFrameSize);
11156 }
11157
jiabinfc791ee2023-02-15 19:43:40 +000011158 return NO_ERROR;
11159}
11160
Andy Hungc5007f82023-08-29 14:26:09 -070011161// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011162void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011163 const sp<audio_utils::MelProcessor>& processor)
11164{
11165 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011166 mMelProcessor.store(processor);
11167 if (processor) {
11168 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011169 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011170
11171 // no need to update output format for MMapPlaybackThread since it is
11172 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011173}
11174
Andy Hungc5007f82023-08-29 14:26:09 -070011175// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011176void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011177{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011178 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11179 auto melProcessor = mMelProcessor.load();
11180 if (melProcessor != nullptr) {
11181 melProcessor->pause();
11182 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011183}
11184
Andy Hungee58e4a2023-07-07 13:47:37 -070011185void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011186{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011187 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011188
Glenn Kastend3bb6452016-12-05 18:14:37 -080011189 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011190 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011191 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11192}
11193
Andy Hungee58e4a2023-07-07 13:47:37 -070011194/* static */
11195sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011196 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011197 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011198 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011199}
11200
11201MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011202 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011203 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011204 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011205 mInput(input)
11206{
11207 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11208 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11209}
11210
Andy Hungee58e4a2023-07-07 13:47:37 -070011211status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011212{
Phil Burkf054fc32018-12-06 09:45:59 -080011213 {
11214 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011215 if (mInput != nullptr && mInput->stream != nullptr) {
11216 mInput->stream->setGain(1.0f);
11217 }
11218 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011219 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011220}
11221
Andy Hungee58e4a2023-07-07 13:47:37 -070011222AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011223{
Andy Hung972bec12023-08-31 16:13:39 -070011224 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011225 AudioStreamIn *input = mInput;
11226 mInput = NULL;
11227 return input;
11228}
Kevin Rocard069c2712018-03-29 19:09:14 -070011229
Andy Hungee58e4a2023-07-07 13:47:37 -070011230void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011231{
11232 bool changed = false;
11233 bool silenced = false;
11234
11235 sp<MmapStreamCallback> callback = mCallback.promote();
11236 if (callback == 0) {
11237 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11238 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11239 mNoCallbackWarningCount++;
11240 }
11241 }
11242
11243 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11244 // track is silenced and unmute otherwise
11245 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11246 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11247 changed = true;
11248 silenced = mActiveTracks[i]->isSilenced_l();
11249 }
11250 }
11251
11252 if (changed) {
11253 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11254 }
11255}
11256
Andy Hungee58e4a2023-07-07 13:47:37 -070011257ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011258{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011259 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011260 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011261 }
11262 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011263 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011264 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011265 record_track_metadata_v7_t trackMetadata;
11266 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011267 .source = track->attributes().source,
11268 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011269 };
11270 trackMetadata.channel_mask = track->channelMask(),
11271 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11272 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011273 }
11274 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011275 MetadataUpdate change;
11276 change.recordMetadataUpdate = metadata.tracks;
11277 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011278}
11279
Andy Hungee58e4a2023-07-07 13:47:37 -070011280void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011281{
Andy Hung972bec12023-08-31 16:13:39 -070011282 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011283 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011284 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011285 mActiveTracks[i]->setSilenced_l(silenced);
11286 broadcast_l();
11287 }
11288 }
jiabin09609032022-06-15 19:26:01 +000011289 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011290}
11291
Andy Hungee58e4a2023-07-07 13:47:37 -070011292void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011293{
11294 MmapThread::toAudioPortConfig(config);
11295 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11296 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11297 config->flags.input = mInput->flags;
11298 }
11299}
11300
Andy Hungee58e4a2023-07-07 13:47:37 -070011301status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011302 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011303{
11304 if (mInput == nullptr) {
11305 return NO_INIT;
11306 }
11307 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11308}
11309
jiabinc658e452022-10-21 20:52:21 +000011310// ----------------------------------------------------------------------------
11311
Andy Hungee58e4a2023-07-07 13:47:37 -070011312/* static */
11313sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011314 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011315 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011316 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011317}
11318
Andy Hung583043b2023-07-17 17:05:00 -070011319BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011320 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011321 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011322
Andy Hungee58e4a2023-07-07 13:47:37 -070011323PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011324 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011325 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11326 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011327 float volumeLeft = 1.0f;
11328 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011329 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11330 const int trackId = mActiveTracks[0]->id();
11331 mAudioMixer->setParameter(
11332 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11333 mAudioMixer->setParameter(
11334 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11335 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011336 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011337 mIsBitPerfect = true;
11338 } else {
11339 mIsBitPerfect = false;
11340 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11341 // active.
11342 for (const auto& track : mActiveTracks) {
11343 const int trackId = track->id();
11344 mAudioMixer->setParameter(
11345 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11346 }
11347 }
jiabin76d94692022-12-15 21:51:21 +000011348 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11349 mVolumeLeft = volumeLeft;
11350 mVolumeRight = volumeRight;
11351 setVolumeForOutput_l(volumeLeft, volumeRight);
11352 }
jiabinc658e452022-10-21 20:52:21 +000011353 return result;
11354}
11355
Andy Hungee58e4a2023-07-07 13:47:37 -070011356void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011357 MixerThread::threadLoop_mix();
11358 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11359}
11360
Glenn Kasten63238ef2015-03-02 15:50:29 -080011361} // namespace android