blob: a6630a84f386860e533aaae3dd50350ce815c72d [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020054#include <system/audio_effects/effect_downmix.h>
55#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020056#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070057#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080058
59// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080061#include <media/nbaio/AudioStreamOutSink.h>
62#include <media/nbaio/MonoPipe.h>
63#include <media/nbaio/MonoPipeReader.h>
64#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
66#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070068#include <mediautils/Process.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069
Mikhail Naganov2996f672019-04-18 12:29:59 -070070#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071#include <powermanager/PowerManager.h>
72
Kevin Rocard7588ff42018-01-08 11:11:30 -080073#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070074#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080075
Eric Laurent81784c32012-11-19 14:55:58 -080076#include "AudioFlinger.h"
Andy Hungab7ef302018-05-15 19:35:29 -070077#include <mediautils/SchedulingPolicyService.h>
78#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080079
Eric Laurent81784c32012-11-19 14:55:58 -080080#ifdef ADD_BATTERY_DATA
81#include <media/IMediaPlayerService.h>
82#include <media/IMediaDeathNotifier.h>
83#endif
84
Eric Laurent81784c32012-11-19 14:55:58 -080085#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070086#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080087#include <cpustats/ThreadCpuUsage.h>
88#endif
89
Andy Hungbef3a1e2023-05-23 17:36:46 -070090#include <fastpath/AutoPark.h>
Glenn Kastenc05b8d72016-03-24 09:48:17 -070091
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080092#include <pthread.h>
Andy Hungb776e372023-05-24 11:53:47 -070093#include <afutils/TypedLogger.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080094
Eric Laurent81784c32012-11-19 14:55:58 -080095// ----------------------------------------------------------------------------
96
97// Note: the following macro is used for extremely verbose logging message. In
98// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
99// 0; but one side effect of this is to turn all LOGV's as well. Some messages
100// are so verbose that we want to suppress them even when we have ALOG_ASSERT
101// turned on. Do not uncomment the #def below unless you really know what you
102// are doing and want to see all of the extremely verbose messages.
103//#define VERY_VERY_VERBOSE_LOGGING
104#ifdef VERY_VERY_VERBOSE_LOGGING
105#define ALOGVV ALOGV
106#else
107#define ALOGVV(a...) do { } while(0)
108#endif
109
Andy Hung6770c6f2015-04-07 13:43:36 -0700110// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700111#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700112
Andy Hung6770c6f2015-04-07 13:43:36 -0700113template <typename T>
114static inline T min(const T& a, const T& b)
115{
116 return a < b ? a : b;
117}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700118
Eric Laurent81784c32012-11-19 14:55:58 -0800119namespace android {
120
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700121using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000122using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700123
Eric Laurent81784c32012-11-19 14:55:58 -0800124// retry counts for buffer fill timeout
125// 50 * ~20msecs = 1 second
126static const int8_t kMaxTrackRetries = 50;
127static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700128
Eric Laurent81784c32012-11-19 14:55:58 -0800129// allow less retry attempts on direct output thread.
130// direct outputs can be a scarce resource in audio hardware and should
131// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700132// Notes:
133// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
134// in case the data write is bursty for the AudioTrack. The application
135// should endeavor to write at least once every kMaxTrackRetriesDirectMs
136// to prevent an underrun situation. If the data is bursty, then
137// the application can also throttle the data sent to be even.
138// 2) For compressed audio data, any data present in the AudioTrack buffer
139// will be sent and reset the retry count. This delivers data as
140// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
141// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
142// of data to be available, then any remaining data is delivered.
143// This is required to ensure the last bit of data is delivered before underrun.
144//
145// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
146// or the size of the HAL period for proportional / linear PCM tracks.
147static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800148
149// don't warn about blocked writes or record buffer overflows more often than this
150static const nsecs_t kWarningThrottleNs = seconds(5);
151
152// RecordThread loop sleep time upon application overrun or audio HAL read error
153static const int kRecordThreadSleepUs = 5000;
154
Eric Laurent10351942014-05-08 18:49:52 -0700155// maximum time to wait in sendConfigEvent_l() for a status to be received
156static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800157
158// minimum sleep time for the mixer thread loop when tracks are active but in underrun
159static const uint32_t kMinThreadSleepTimeUs = 5000;
160// maximum divider applied to the active sleep time in the mixer thread loop
161static const uint32_t kMaxThreadSleepTimeShift = 2;
162
Andy Hung09a50072014-02-27 14:30:47 -0800163// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700164// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800165static const uint32_t kMinNormalSinkBufferSizeMs = 20;
166// maximum normal sink buffer size
167static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800168
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700169// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
170// FIXME This should be based on experimentally observed scheduling jitter
171static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
172
Eric Laurent972a1732013-09-04 09:42:59 -0700173// Offloaded output thread standby delay: allows track transition without going to standby
174static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
175
Eric Laurent51716182016-02-29 18:00:56 -0800176// Direct output thread minimum sleep time in idle or active(underrun) state
177static const nsecs_t kDirectMinSleepTimeUs = 10000;
178
Brian Lindahl9e661ad2022-07-27 18:01:07 +0200179// Minimum amount of time between checking to see if the timestamp is advancing
180// for underrun detection. If we check too frequently, we may not detect a
181// timestamp update and will falsely detect underrun.
182static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
183
Glenn Kasten1b291842016-07-18 14:55:21 -0700184// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
185// balance between power consumption and latency, and allows threads to be scheduled reliably
186// by the CFS scheduler.
187// FIXME Express other hardcoded references to 20ms with references to this constant and move
188// it appropriately.
189#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800190
Eric Laurent81784c32012-11-19 14:55:58 -0800191// Whether to use fast mixer
192static const enum {
193 FastMixer_Never, // never initialize or use: for debugging only
194 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
195 // normal mixer multiplier is 1
196 FastMixer_Static, // initialize if needed, then use all the time if initialized,
197 // multiplier is calculated based on min & max normal mixer buffer size
198 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
199 // multiplier is calculated based on min & max normal mixer buffer size
200 // FIXME for FastMixer_Dynamic:
201 // Supporting this option will require fixing HALs that can't handle large writes.
202 // For example, one HAL implementation returns an error from a large write,
203 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
204 // We could either fix the HAL implementations, or provide a wrapper that breaks
205 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
206} kUseFastMixer = FastMixer_Static;
207
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700208// Whether to use fast capture
209static const enum {
210 FastCapture_Never, // never initialize or use: for debugging only
211 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
212 FastCapture_Static, // initialize if needed, then use all the time if initialized
213} kUseFastCapture = FastCapture_Static;
214
Eric Laurent81784c32012-11-19 14:55:58 -0800215// Priorities for requestPriority
216static const int kPriorityAudioApp = 2;
217static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700218static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800219
Glenn Kastenea38ee72016-04-18 11:08:01 -0700220// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
221// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
222// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700223
224// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800225static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800226
Glenn Kasten03490092014-05-27 12:30:54 -0700227// The minimum and maximum allowed values
228static const int kFastTrackMultiplierMin = 1;
229static const int kFastTrackMultiplierMax = 2;
230
231// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
232static int sFastTrackMultiplier = kFastTrackMultiplier;
233
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700234// See Thread::readOnlyHeap().
235// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
236// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
237// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700238static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700239
Eric Laurent81784c32012-11-19 14:55:58 -0800240// ----------------------------------------------------------------------------
241
Andy Hungb68f5eb2019-12-03 16:49:17 -0800242// TODO: move all toString helpers to audio.h
243// under #ifdef __cplusplus #endif
244static std::string patchSinksToString(const struct audio_patch *patch)
245{
246 std::stringstream ss;
247 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700248 if (i > 0) {
249 ss << "|";
250 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800251 ss << "(" << toString(patch->sinks[i].ext.device.type)
252 << ", " << patch->sinks[i].ext.device.address << ")";
253 }
254 return ss.str();
255}
256
257static std::string patchSourcesToString(const struct audio_patch *patch)
258{
259 std::stringstream ss;
260 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700261 if (i > 0) {
262 ss << "|";
263 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800264 ss << "(" << toString(patch->sources[i].ext.device.type)
265 << ", " << patch->sources[i].ext.device.address << ")";
266 }
267 return ss.str();
268}
269
Andy Hung4bd53e72022-11-17 17:21:45 -0800270static std::string toString(audio_latency_mode_t mode) {
271 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganova77d5552022-12-18 02:48:14 +0000272 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
273 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800274}
275
276// Could be made a template, but other toString overloads for std::vector are confused.
277static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
278 std::string s("{ ");
279 for (const auto& e : elements) {
280 s.append(toString(e));
281 s.append(" ");
282 }
283 s.append("}");
284 return s;
285}
286
Glenn Kasten03490092014-05-27 12:30:54 -0700287static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
288
289static void sFastTrackMultiplierInit()
290{
291 char value[PROPERTY_VALUE_MAX];
292 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
293 char *endptr;
294 unsigned long ul = strtoul(value, &endptr, 0);
295 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
296 sFastTrackMultiplier = (int) ul;
297 }
298 }
299}
300
301// ----------------------------------------------------------------------------
302
Eric Laurent81784c32012-11-19 14:55:58 -0800303#ifdef ADD_BATTERY_DATA
304// To collect the amplifier usage
305static void addBatteryData(uint32_t params) {
306 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
307 if (service == NULL) {
308 // it already logged
309 return;
310 }
311
312 service->addBatteryData(params);
313}
314#endif
315
Andy Hung3f0c9022016-01-15 17:49:46 -0800316// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
317struct {
318 // call when you acquire a partial wakelock
319 void acquire(const sp<IBinder> &wakeLockToken) {
320 pthread_mutex_lock(&mLock);
321 if (wakeLockToken.get() == nullptr) {
322 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
323 } else {
324 if (mCount == 0) {
325 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
326 }
327 ++mCount;
328 }
329 pthread_mutex_unlock(&mLock);
330 }
331
332 // call when you release a partial wakelock.
333 void release(const sp<IBinder> &wakeLockToken) {
334 if (wakeLockToken.get() == nullptr) {
335 return;
336 }
337 pthread_mutex_lock(&mLock);
338 if (--mCount < 0) {
339 ALOGE("negative wakelock count");
340 mCount = 0;
341 }
342 pthread_mutex_unlock(&mLock);
343 }
344
345 // retrieves the boottime timebase offset from monotonic.
346 int64_t getBoottimeOffset() {
347 pthread_mutex_lock(&mLock);
348 int64_t boottimeOffset = mBoottimeOffset;
349 pthread_mutex_unlock(&mLock);
350 return boottimeOffset;
351 }
352
353 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
354 // and the selected timebase.
355 // Currently only TIMEBASE_BOOTTIME is allowed.
356 //
357 // This only needs to be called upon acquiring the first partial wakelock
358 // after all other partial wakelocks are released.
359 //
360 // We do an empirical measurement of the offset rather than parsing
361 // /proc/timer_list since the latter is not a formal kernel ABI.
362 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
363 int clockbase;
364 switch (timebase) {
365 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
366 clockbase = SYSTEM_TIME_BOOTTIME;
367 break;
368 default:
369 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
370 break;
371 }
372 // try three times to get the clock offset, choose the one
373 // with the minimum gap in measurements.
374 const int tries = 3;
Andy Hung71ba4b32022-10-06 12:09:49 -0700375 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800376 for (int i = 0; i < tries; ++i) {
377 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
378 const nsecs_t tbase = systemTime(clockbase);
379 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
380 const nsecs_t gap = tmono2 - tmono;
381 if (i == 0 || gap < bestGap) {
382 bestGap = gap;
383 measured = tbase - ((tmono + tmono2) >> 1);
384 }
385 }
386
387 // to avoid micro-adjusting, we don't change the timebase
388 // unless it is significantly different.
389 //
390 // Assumption: It probably takes more than toleranceNs to
391 // suspend and resume the device.
392 static int64_t toleranceNs = 10000; // 10 us
393 if (llabs(*offset - measured) > toleranceNs) {
394 ALOGV("Adjusting timebase offset old: %lld new: %lld",
395 (long long)*offset, (long long)measured);
396 *offset = measured;
397 }
398 }
399
400 pthread_mutex_t mLock;
401 int32_t mCount;
402 int64_t mBoottimeOffset;
403} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800404
405// ----------------------------------------------------------------------------
406// CPU Stats
407// ----------------------------------------------------------------------------
408
409class CpuStats {
410public:
411 CpuStats();
412 void sample(const String8 &title);
413#ifdef DEBUG_CPU_USAGE
414private:
415 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700416 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800417
Andy Hung16698b82018-08-01 10:48:38 -0700418 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800419
420 int mCpuNum; // thread's current CPU number
421 int mCpukHz; // frequency of thread's current CPU in kHz
422#endif
423};
424
425CpuStats::CpuStats()
426#ifdef DEBUG_CPU_USAGE
427 : mCpuNum(-1), mCpukHz(-1)
428#endif
429{
430}
431
Glenn Kasten0f11b512014-01-31 16:18:54 -0800432void CpuStats::sample(const String8 &title
433#ifndef DEBUG_CPU_USAGE
434 __unused
435#endif
436 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800437#ifdef DEBUG_CPU_USAGE
438 // get current thread's delta CPU time in wall clock ns
439 double wcNs;
440 bool valid = mCpuUsage.sampleAndEnable(wcNs);
441
442 // record sample for wall clock statistics
443 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700444 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800445 }
446
447 // get the current CPU number
448 int cpuNum = sched_getcpu();
449
450 // get the current CPU frequency in kHz
451 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
452
453 // check if either CPU number or frequency changed
454 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
455 mCpuNum = cpuNum;
456 mCpukHz = cpukHz;
457 // ignore sample for purposes of cycles
458 valid = false;
459 }
460
461 // if no change in CPU number or frequency, then record sample for cycle statistics
462 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700463 const double cycles = wcNs * cpukHz * 0.000001;
464 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800465 }
466
Eric Tan5b13ff82018-07-27 11:20:17 -0700467 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800468 // mCpuUsage.elapsed() is expensive, so don't call it every loop
469 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700470 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800471 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700472 const double perLoop = elapsed / (double) n;
473 const double perLoop100 = perLoop * 0.01;
474 const double perLoop1k = perLoop * 0.001;
475 const double mean = mWcStats.getMean();
476 const double stddev = mWcStats.getStdDev();
477 const double minimum = mWcStats.getMin();
478 const double maximum = mWcStats.getMax();
479 const double meanCycles = mHzStats.getMean();
480 const double stddevCycles = mHzStats.getStdDev();
481 const double minCycles = mHzStats.getMin();
482 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800483 mCpuUsage.resetElapsed();
484 mWcStats.reset();
485 mHzStats.reset();
486 ALOGD("CPU usage for %s over past %.1f secs\n"
487 " (%u mixer loops at %.1f mean ms per loop):\n"
488 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
489 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
490 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000491 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800492 elapsed * .000000001, n, perLoop * .000001,
493 mean * .001,
494 stddev * .001,
495 minimum * .001,
496 maximum * .001,
497 mean / perLoop100,
498 stddev / perLoop100,
499 minimum / perLoop100,
500 maximum / perLoop100,
501 meanCycles / perLoop1k,
502 stddevCycles / perLoop1k,
503 minCycles / perLoop1k,
504 maxCycles / perLoop1k);
505
506 }
507 }
508#endif
509};
510
511// ----------------------------------------------------------------------------
512// ThreadBase
513// ----------------------------------------------------------------------------
514
Glenn Kasten97b7b752014-09-28 13:04:24 -0700515// static
516const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
517{
518 switch (type) {
519 case MIXER:
520 return "MIXER";
521 case DIRECT:
522 return "DIRECT";
523 case DUPLICATING:
524 return "DUPLICATING";
525 case RECORD:
526 return "RECORD";
527 case OFFLOAD:
528 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700529 case MMAP_PLAYBACK:
530 return "MMAP_PLAYBACK";
531 case MMAP_CAPTURE:
532 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200533 case SPATIALIZER:
534 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700535 default:
536 return "unknown";
537 }
538}
539
Eric Laurent81784c32012-11-19 14:55:58 -0800540AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700541 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800542 : Thread(false /*canCallJava*/),
543 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700544 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700545 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
546 isOut),
547 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700548 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800549 // are set by PlaybackThread::readOutputParameters_l() or
550 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700551 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700552 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700553 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800554 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700555 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800556 mSystemReady(systemReady),
557 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800558{
Andy Hungcf10d742020-04-28 15:38:24 -0700559 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700560 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800561}
562
563AudioFlinger::ThreadBase::~ThreadBase()
564{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700565 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700566 mConfigEvents.clear();
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568 // do not lock the mutex in destructor
569 releaseWakeLock_l();
570 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800571 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800572 binder->unlinkToDeath(mDeathRecipient);
573 }
Andy Hungd0979812019-02-21 15:51:44 -0800574
575 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800576}
577
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700578status_t AudioFlinger::ThreadBase::readyToRun()
579{
580 status_t status = initCheck();
581 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800582 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700583 } else {
584 ALOGE("No working audio driver found.");
585 }
586 return status;
587}
588
Eric Laurent81784c32012-11-19 14:55:58 -0800589void AudioFlinger::ThreadBase::exit()
590{
591 ALOGV("ThreadBase::exit");
592 // do any cleanup required for exit to succeed
593 preExit();
594 {
595 // This lock prevents the following race in thread (uniprocessor for illustration):
596 // if (!exitPending()) {
597 // // context switch from here to exit()
598 // // exit() calls requestExit(), what exitPending() observes
599 // // exit() calls signal(), which is dropped since no waiters
600 // // context switch back from exit() to here
601 // mWaitWorkCV.wait(...);
602 // // now thread is hung
603 // }
604 AutoMutex lock(mLock);
605 requestExit();
606 mWaitWorkCV.broadcast();
607 }
608 // When Thread::requestExitAndWait is made virtual and this method is renamed to
609 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
610 requestExitAndWait();
611}
612
613status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
614{
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000615 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800616 Mutex::Autolock _l(mLock);
617
Eric Laurent10351942014-05-08 18:49:52 -0700618 return sendSetParameterConfigEvent_l(keyValuePairs);
619}
620
621// sendConfigEvent_l() must be called with ThreadBase::mLock held
622// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
623status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-10-06 12:09:49 -0700624NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700625{
626 status_t status = NO_ERROR;
627
Eric Laurent72e3f392015-05-20 14:43:50 -0700628 if (event->mRequiresSystemReady && !mSystemReady) {
629 event->mWaitStatus = false;
630 mPendingConfigEvents.add(event);
631 return status;
632 }
Eric Laurent10351942014-05-08 18:49:52 -0700633 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700634 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800635 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700636 mLock.unlock();
637 {
638 Mutex::Autolock _l(event->mLock);
639 while (event->mWaitStatus) {
640 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
641 event->mStatus = TIMED_OUT;
642 event->mWaitStatus = false;
643 }
644 }
645 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800646 }
Eric Laurent10351942014-05-08 18:49:52 -0700647 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800648 return status;
649}
650
Mikhail Naganov88536df2021-07-26 17:30:29 -0700651void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700652 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800653{
654 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700655 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800656}
657
658// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov88536df2021-07-26 17:30:29 -0700659void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700660 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800661{
Andy Hungd0979812019-02-21 15:51:44 -0800662 // The audio statistics history is exponentially weighted to forget events
663 // about five or more seconds in the past. In order to have
664 // crisper statistics for mediametrics, we reset the statistics on
665 // an IoConfigEvent, to reflect different properties for a new device.
666 mIoJitterMs.reset();
667 mLatencyMs.reset();
668 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000669 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100670 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800671
Eric Laurent09f1ed22019-04-24 17:45:17 -0700672 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700673 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800674}
675
Mikhail Naganov83f04272017-02-07 10:45:09 -0800676void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700677{
678 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800679 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700680}
681
Eric Laurent81784c32012-11-19 14:55:58 -0800682// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800683void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
684 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800685{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800686 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700687 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800688}
689
Eric Laurent10351942014-05-08 18:49:52 -0700690// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
691status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800692{
Andy Hung2ddee192015-12-18 17:34:44 -0800693 sp<ConfigEvent> configEvent;
694 AudioParameter param(keyValuePair);
695 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700696 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800697 setMasterMono_l(value != 0);
698 if (param.size() == 1) {
699 return NO_ERROR; // should be a solo parameter - we don't pass down
700 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700701 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800702 configEvent = new SetParameterConfigEvent(param.toString());
703 } else {
704 configEvent = new SetParameterConfigEvent(keyValuePair);
705 }
Eric Laurent10351942014-05-08 18:49:52 -0700706 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700707}
708
Eric Laurent1c333e22014-05-20 10:48:17 -0700709status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
710 const struct audio_patch *patch,
711 audio_patch_handle_t *handle)
712{
713 Mutex::Autolock _l(mLock);
714 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
715 status_t status = sendConfigEvent_l(configEvent);
716 if (status == NO_ERROR) {
717 CreateAudioPatchConfigEventData *data =
718 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
719 *handle = data->mHandle;
720 }
721 return status;
722}
723
724status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
725 const audio_patch_handle_t handle)
726{
727 Mutex::Autolock _l(mLock);
728 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
729 return sendConfigEvent_l(configEvent);
730}
731
jiabinc52b1ff2019-10-31 17:20:42 -0700732status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
733 const DeviceDescriptorBaseVector& outDevices)
734{
735 if (type() != RECORD) {
736 // The update out device operation is only for record thread.
737 return INVALID_OPERATION;
738 }
739 Mutex::Autolock _l(mLock);
740 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
741 return sendConfigEvent_l(configEvent);
742}
743
Eric Laurentec376dc2021-04-08 20:41:22 +0200744void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
745{
746 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
747 sp<ConfigEvent> configEvent =
748 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
749 sendConfigEvent_l(configEvent);
750}
Eric Laurent1c333e22014-05-20 10:48:17 -0700751
Eric Laurentb3f315a2021-07-13 15:09:05 +0200752void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
753{
754 Mutex::Autolock _l(mLock);
755 sendCheckOutputStageEffectsEvent_l();
756}
757
758void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
759{
760 sp<ConfigEvent> configEvent =
761 (ConfigEvent *)new CheckOutputStageEffectsEvent();
762 sendConfigEvent_l(configEvent);
763}
764
Eric Laurent6f9534f2022-05-03 18:15:04 +0200765void AudioFlinger::ThreadBase::sendHalLatencyModesChangedEvent_l()
766{
767 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
768 sendConfigEvent_l(configEvent);
769}
770
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700771// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700772void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700773{
Eric Laurent10351942014-05-08 18:49:52 -0700774 bool configChanged = false;
775
Eric Laurent81784c32012-11-19 14:55:58 -0800776 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700777 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700778 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800779 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700780 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700781 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700782 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
783 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800784 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700785 true /*asynchronous*/);
786 if (err != 0) {
787 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700788 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700789 }
790 } break;
791 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700792 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700793 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700794 } break;
795 case CFG_EVENT_SET_PARAMETER: {
796 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
797 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
798 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700799 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000800 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700801 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700802 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700803 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700804 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700805 CreateAudioPatchConfigEventData *data =
806 (CreateAudioPatchConfigEventData *)event->mData.get();
807 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700808 const DeviceTypeSet newDevices = getDeviceTypes();
809 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
810 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
811 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 } break;
813 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700814 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700815 ReleaseAudioPatchConfigEventData *data =
816 (ReleaseAudioPatchConfigEventData *)event->mData.get();
817 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700818 const DeviceTypeSet newDevices = getDeviceTypes();
819 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
820 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
821 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
822 } break;
823 case CFG_EVENT_UPDATE_OUT_DEVICE: {
824 UpdateOutDevicesConfigEventData *data =
825 (UpdateOutDevicesConfigEventData *)event->mData.get();
826 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700827 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200828 case CFG_EVENT_RESIZE_BUFFER: {
829 ResizeBufferConfigEventData *data =
830 (ResizeBufferConfigEventData *)event->mData.get();
831 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
832 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200833
834 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
835 setCheckOutputStageEffects();
836 } break;
837
Eric Laurent6f9534f2022-05-03 18:15:04 +0200838 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
839 onHalLatencyModesChanged_l();
840 } break;
841
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700842 default:
Eric Laurent10351942014-05-08 18:49:52 -0700843 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700844 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800845 }
Eric Laurent10351942014-05-08 18:49:52 -0700846 {
847 Mutex::Autolock _l(event->mLock);
848 if (event->mWaitStatus) {
849 event->mWaitStatus = false;
850 event->mCond.signal();
851 }
852 }
853 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
854 }
855
856 if (configChanged) {
857 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800858 }
Eric Laurent81784c32012-11-19 14:55:58 -0800859}
860
Marco Nelissenb2208842014-02-07 14:00:50 -0800861String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
862 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700863 const audio_channel_representation_t representation =
864 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700865
866 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800867 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700868 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
869 if (output) {
870 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
871 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
872 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700873 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700874 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
875 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
876 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
877 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
878 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
880 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
881 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
882 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
883 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
884 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
885 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700886 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
887 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
888 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
889 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
890 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
891 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
892 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700893 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700894 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
895 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700896 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
897 } else {
898 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
899 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
900 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
901 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
902 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
903 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
904 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
905 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
906 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
907 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
908 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
909 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700910 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
911 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
912 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700913 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700914 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
915 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700916 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
917 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
918 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
919 }
920 const int len = s.length();
921 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700922 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700923 s.unlockBuffer(len - 2); // remove trailing ", "
924 }
925 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800926 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700927 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
928 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
929 return s;
930 default:
931 s.appendFormat("unknown mask, representation:%d bits:%#x",
932 representation, audio_channel_mask_get_bits(mask));
933 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800934 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800935}
936
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700937void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-10-06 12:09:49 -0700938NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800939{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800940 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
941 this, mThreadName, getTid(), type(), threadTypeToString(type()));
942
Eric Laurent81784c32012-11-19 14:55:58 -0800943 bool locked = AudioFlinger::dumpTryLock(mLock);
944 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800945 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800946 }
947
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700948 dumpBase_l(fd, args);
949 dumpInternals_l(fd, args);
950 dumpTracks_l(fd, args);
951 dumpEffectChains_l(fd, args);
952
953 if (locked) {
954 mLock.unlock();
955 }
956
957 dprintf(fd, " Local log:\n");
958 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700959
960 // --all does the statistics
961 bool dumpAll = false;
962 for (const auto &arg : args) {
963 if (arg == String16("--all")) {
964 dumpAll = true;
965 }
966 }
967 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700968 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700969 if (!sched.empty()) {
970 (void)write(fd, sched.c_str(), sched.size());
971 }
972 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700973}
974
975void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
976{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700977 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700978 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700979 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700980 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700981 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700982 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700983 dprintf(fd, " Channel count: %u\n", mChannelCount);
984 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000985 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700986 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700987 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700988 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800989 size_t numConfig = mConfigEvents.size();
990 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700991 const size_t SIZE = 256;
992 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800993 for (size_t i = 0; i < numConfig; i++) {
994 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700995 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800996 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700997 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800998 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700999 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001000 }
Andy Hung293558a2017-03-21 12:19:20 -07001001 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001002 dprintf(fd, " Output devices: %s (%s)\n",
1003 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1004 dprintf(fd, " Input device: %#x (%s)\n",
1005 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001006 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001007
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001008 // Dump timestamp statistics for the Thread types that support it.
1009 if (mType == RECORD
1010 || mType == MIXER
1011 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001012 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001013 || mType == OFFLOAD
1014 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001015 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001016 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001017 }
1018
Andy Hung446f4df2019-02-21 12:26:41 -08001019 if (mLastIoBeginNs > 0) { // MMAP may not set this
1020 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1021 isOutput() ? "write" : "read",
1022 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1023 }
1024
1025 if (mProcessTimeMs.getN() > 0) {
1026 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1027 }
1028
1029 if (mIoJitterMs.getN() > 0) {
1030 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1031 isOutput() ? "write" : "read",
1032 mIoJitterMs.toString().c_str());
1033 }
1034
Andy Hunge6c37112019-02-26 17:38:10 -08001035 if (mLatencyMs.getN() > 0) {
1036 dprintf(fd, " Threadloop %s latency stats: %s\n",
1037 isOutput() ? "write" : "read",
1038 mLatencyMs.toString().c_str());
1039 }
Robert Wu06db0a32021-08-10 19:05:34 +00001040
1041 if (mMonopipePipeDepthStats.getN() > 0) {
1042 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1043 isOutput() ? "write" : "read",
1044 mMonopipePipeDepthStats.toString().c_str());
1045 }
Eric Laurent81784c32012-11-19 14:55:58 -08001046}
1047
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001048void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001049{
1050 const size_t SIZE = 256;
1051 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001052
Marco Nelissenb2208842014-02-07 14:00:50 -08001053 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001054 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001055 write(fd, buffer, strlen(buffer));
1056
Marco Nelissenb2208842014-02-07 14:00:50 -08001057 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001058 sp<EffectChain> chain = mEffectChains[i];
1059 if (chain != 0) {
1060 chain->dump(fd, args);
1061 }
1062 }
1063}
1064
Andy Hungdae27702016-10-31 14:01:16 -07001065void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001066{
1067 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001068 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001069}
1070
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001071String16 AudioFlinger::ThreadBase::getWakeLockTag()
1072{
1073 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001074 case MIXER:
1075 return String16("AudioMix");
1076 case DIRECT:
1077 return String16("AudioDirectOut");
1078 case DUPLICATING:
1079 return String16("AudioDup");
1080 case RECORD:
1081 return String16("AudioIn");
1082 case OFFLOAD:
1083 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001084 case MMAP_PLAYBACK:
1085 return String16("MmapPlayback");
1086 case MMAP_CAPTURE:
1087 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001088 case SPATIALIZER:
1089 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001090 default:
1091 ALOG_ASSERT(false);
1092 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001093 }
1094}
1095
Andy Hungdae27702016-10-31 14:01:16 -07001096void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001098 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001099 if (mPowerManager != 0) {
1100 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001101 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001102 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1103 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001104 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001105 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001106 {} /* workSource */,
1107 {} /* historyTag */);
1108 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001109 mWakeLockToken = binder;
1110 }
Chris Ye6597d732020-02-28 22:38:25 -08001111 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001112 }
Wei Jia3f273d12015-11-24 09:06:49 -08001113
Andy Hung3f0c9022016-01-15 17:49:46 -08001114 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001115 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1116 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001117}
1118
1119void AudioFlinger::ThreadBase::releaseWakeLock()
1120{
1121 Mutex::Autolock _l(mLock);
1122 releaseWakeLock_l();
1123}
1124
1125void AudioFlinger::ThreadBase::releaseWakeLock_l()
1126{
Andy Hung3f0c9022016-01-15 17:49:46 -08001127 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001128 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001129 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001130 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001131 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001132 }
1133 mWakeLockToken.clear();
1134 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001135}
1136
1137void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001138 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001139 // use checkService() to avoid blocking if power service is not up yet
1140 sp<IBinder> binder =
1141 defaultServiceManager()->checkService(String16("power"));
1142 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001143 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001144 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001145 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001146 binder->linkToDeath(mDeathRecipient);
1147 }
1148 }
1149}
1150
Andy Hungd01b0f12016-11-07 16:10:30 -08001151void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001152 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001153
1154#if !LOG_NDEBUG
1155 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001156 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001157 s << uid << " ";
1158 }
1159 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1160#endif
1161
Andy Hung438e7572015-12-14 15:51:17 -08001162 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1163 if (mSystemReady) {
1164 ALOGE("no wake lock to update, but system ready!");
1165 } else {
1166 ALOGW("no wake lock to update, system not ready yet");
1167 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001168 return;
1169 }
1170 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001171 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001172 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1173 mWakeLockToken, uidsAsInt);
1174 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001175 }
1176}
1177
Eric Laurent81784c32012-11-19 14:55:58 -08001178void AudioFlinger::ThreadBase::clearPowerManager()
1179{
1180 Mutex::Autolock _l(mLock);
1181 releaseWakeLock_l();
1182 mPowerManager.clear();
1183}
1184
jiabinc52b1ff2019-10-31 17:20:42 -07001185void AudioFlinger::ThreadBase::updateOutDevices(
1186 const DeviceDescriptorBaseVector& outDevices __unused)
1187{
1188 ALOGE("%s should only be called in RecordThread", __func__);
1189}
1190
Eric Laurentec376dc2021-04-08 20:41:22 +02001191void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1192{
1193 ALOGE("%s should only be called in RecordThread", __func__);
1194}
1195
Glenn Kasten0f11b512014-01-31 16:18:54 -08001196void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001197{
1198 sp<ThreadBase> thread = mThread.promote();
1199 if (thread != 0) {
1200 thread->clearPowerManager();
1201 }
1202 ALOGW("power manager service died !!!");
1203}
1204
Eric Laurent81784c32012-11-19 14:55:58 -08001205void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001206 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001207{
1208 sp<EffectChain> chain = getEffectChain_l(sessionId);
1209 if (chain != 0) {
1210 if (type != NULL) {
1211 chain->setEffectSuspended_l(type, suspend);
1212 } else {
1213 chain->setEffectSuspendedAll_l(suspend);
1214 }
1215 }
1216
1217 updateSuspendedSessions_l(type, suspend, sessionId);
1218}
1219
1220void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1221{
1222 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1223 if (index < 0) {
1224 return;
1225 }
1226
1227 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1228 mSuspendedSessions.valueAt(index);
1229
1230 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001231 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001232 for (int j = 0; j < desc->mRefCount; j++) {
1233 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1234 chain->setEffectSuspendedAll_l(true);
1235 } else {
1236 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1237 desc->mType.timeLow);
1238 chain->setEffectSuspended_l(&desc->mType, true);
1239 }
1240 }
1241 }
1242}
1243
1244void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1245 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001246 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001247{
1248 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1249
1250 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1251
1252 if (suspend) {
1253 if (index >= 0) {
1254 sessionEffects = mSuspendedSessions.valueAt(index);
1255 } else {
1256 mSuspendedSessions.add(sessionId, sessionEffects);
1257 }
1258 } else {
1259 if (index < 0) {
1260 return;
1261 }
1262 sessionEffects = mSuspendedSessions.valueAt(index);
1263 }
1264
1265
1266 int key = EffectChain::kKeyForSuspendAll;
1267 if (type != NULL) {
1268 key = type->timeLow;
1269 }
1270 index = sessionEffects.indexOfKey(key);
1271
1272 sp<SuspendedSessionDesc> desc;
1273 if (suspend) {
1274 if (index >= 0) {
1275 desc = sessionEffects.valueAt(index);
1276 } else {
1277 desc = new SuspendedSessionDesc();
1278 if (type != NULL) {
1279 desc->mType = *type;
1280 }
1281 sessionEffects.add(key, desc);
1282 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1283 }
1284 desc->mRefCount++;
1285 } else {
1286 if (index < 0) {
1287 return;
1288 }
1289 desc = sessionEffects.valueAt(index);
1290 if (--desc->mRefCount == 0) {
1291 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1292 sessionEffects.removeItemsAt(index);
1293 if (sessionEffects.isEmpty()) {
1294 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1295 sessionId);
1296 mSuspendedSessions.removeItem(sessionId);
1297 }
1298 }
1299 }
1300 if (!sessionEffects.isEmpty()) {
1301 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1302 }
1303}
1304
Eric Laurent6b446ce2019-12-13 10:56:31 -08001305void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1306 audio_session_t sessionId,
Andy Hung71ba4b32022-10-06 12:09:49 -07001307 bool threadLocked)
1308NO_THREAD_SAFETY_ANALYSIS // manual locking
1309{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001310 if (!threadLocked) {
1311 mLock.lock();
1312 }
Eric Laurent81784c32012-11-19 14:55:58 -08001313
Eric Laurent81784c32012-11-19 14:55:58 -08001314 if (mType != RECORD) {
1315 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1316 // another session. This gives the priority to well behaved effect control panels
1317 // and applications not using global effects.
1318 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1319 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001320 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001321 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1322 }
1323 }
1324
Eric Laurent6b446ce2019-12-13 10:56:31 -08001325 if (!threadLocked) {
1326 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001327 }
1328}
1329
Eric Laurent4c415062016-06-17 16:14:16 -07001330// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1331status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1332 const effect_descriptor_t *desc, audio_session_t sessionId)
1333{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001334 // No global output effect sessions on record threads
1335 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1336 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001337 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1338 desc->name, mThreadName);
1339 return BAD_VALUE;
1340 }
1341 // only pre processing effects on record thread
1342 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1343 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1344 desc->name, mThreadName);
1345 return BAD_VALUE;
1346 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001347
1348 // always allow effects without processing load or latency
1349 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1350 return NO_ERROR;
1351 }
1352
Eric Laurent4c415062016-06-17 16:14:16 -07001353 audio_input_flags_t flags = mInput->flags;
1354 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1355 if (flags & AUDIO_INPUT_FLAG_RAW) {
1356 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1357 desc->name, mThreadName);
1358 return BAD_VALUE;
1359 }
1360 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1361 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1362 desc->name, mThreadName);
1363 return BAD_VALUE;
1364 }
1365 }
jiabineb3bda02020-06-30 14:07:03 -07001366
1367 if (EffectModule::isHapticGenerator(&desc->type)) {
1368 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1369 return BAD_VALUE;
1370 }
Eric Laurent4c415062016-06-17 16:14:16 -07001371 return NO_ERROR;
1372}
1373
1374// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1375status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1376 const effect_descriptor_t *desc, audio_session_t sessionId)
1377{
1378 // no preprocessing on playback threads
1379 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001380 ALOGW("%s: pre processing effect %s created on playback"
1381 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001382 return BAD_VALUE;
1383 }
1384
Eric Laurent3e4de772017-07-16 16:55:08 -07001385 // always allow effects without processing load or latency
1386 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1387 return NO_ERROR;
1388 }
1389
jiabineb3bda02020-06-30 14:07:03 -07001390 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1391 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1392 __func__);
1393 return BAD_VALUE;
1394 }
1395
Eric Laurentf690c462021-09-17 14:47:03 +02001396 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1397 && mType != SPATIALIZER) {
1398 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1399 __func__, mType);
1400 return BAD_VALUE;
1401 }
1402
Eric Laurent4c415062016-06-17 16:14:16 -07001403 switch (mType) {
1404 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001405 audio_output_flags_t flags = mOutput->flags;
1406 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1407 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1408 // global effects are applied only to non fast tracks if they are SW
1409 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1410 break;
1411 }
1412 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1413 // only post processing on output stage session
1414 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001415 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1416 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001417 return BAD_VALUE;
1418 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001419 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1420 // only post processing on output stage session
1421 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001422 ALOGW("%s: non post processing effect %s not allowed on device session",
1423 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001424 return BAD_VALUE;
1425 }
Eric Laurent4c415062016-06-17 16:14:16 -07001426 } else {
1427 // no restriction on effects applied on non fast tracks
1428 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1429 break;
1430 }
1431 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001432
Eric Laurent4c415062016-06-17 16:14:16 -07001433 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001434 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001435 return BAD_VALUE;
1436 }
1437 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001438 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1439 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001440 return BAD_VALUE;
1441 }
1442 }
1443 } break;
1444 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001445 // nothing actionable on offload threads, if the effect:
1446 // - is offloadable: the effect can be created
1447 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1448 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001449 break;
1450 case DIRECT:
1451 // Reject any effect on Direct output threads for now, since the format of
1452 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001453 ALOGW("%s: effect %s on DIRECT output thread %s",
1454 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001455 return BAD_VALUE;
1456 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001457 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001458 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1459 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001460 return BAD_VALUE;
1461 }
1462 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001463 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1464 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001465 return BAD_VALUE;
1466 }
1467 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001468 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1469 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001470 return BAD_VALUE;
1471 }
1472 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001473 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001474 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1475 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1476 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1477 // are supported and added after the spatializer.
1478 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1479 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1480 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001481 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001482 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1483 // only post processing , downmixer or spatializer effects on output stage session
1484 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1485 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1486 break;
1487 }
1488 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1489 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1490 __func__, desc->name);
1491 return BAD_VALUE;
1492 }
1493 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1494 // only post processing on output stage session
1495 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1496 ALOGW("%s: non post processing effect %s not allowed on device session",
1497 __func__, desc->name);
1498 return BAD_VALUE;
1499 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001500 }
1501 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001502 default:
1503 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1504 }
1505
1506 return NO_ERROR;
1507}
1508
Eric Laurent81784c32012-11-19 14:55:58 -08001509// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1510sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1511 const sp<AudioFlinger::Client>& client,
1512 const sp<IEffectClient>& effectClient,
1513 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001514 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001515 effect_descriptor_t *desc,
1516 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001517 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001518 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001519 bool probe,
1520 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001521{
1522 sp<EffectModule> effect;
1523 sp<EffectHandle> handle;
1524 status_t lStatus;
1525 sp<EffectChain> chain;
1526 bool chainCreated = false;
1527 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001528 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001529
1530 lStatus = initCheck();
1531 if (lStatus != NO_ERROR) {
1532 ALOGW("createEffect_l() Audio driver not initialized.");
1533 goto Exit;
1534 }
1535
Eric Laurent81784c32012-11-19 14:55:58 -08001536 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1537
1538 { // scope for mLock
1539 Mutex::Autolock _l(mLock);
1540
Eric Laurent4c415062016-06-17 16:14:16 -07001541 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001542 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001543 goto Exit;
1544 }
1545
Eric Laurent81784c32012-11-19 14:55:58 -08001546 // check for existing effect chain with the requested audio session
1547 chain = getEffectChain_l(sessionId);
1548 if (chain == 0) {
1549 // create a new chain for this session
1550 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1551 chain = new EffectChain(this, sessionId);
1552 addEffectChain_l(chain);
1553 chain->setStrategy(getStrategyForSession_l(sessionId));
1554 chainCreated = true;
1555 } else {
1556 effect = chain->getEffectFromDesc_l(desc);
1557 }
1558
1559 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1560
1561 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001562 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001563 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001564 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001565 if (lStatus != NO_ERROR) {
1566 goto Exit;
1567 }
1568 effectCreated = true;
1569
jiabinc52b1ff2019-10-31 17:20:42 -07001570 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001571 effect->setDevices(outDeviceTypeAddrs());
1572 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001573 effect->setMode(mAudioFlinger->getMode());
1574 effect->setAudioSource(mAudioSource);
1575 }
jiabin1319f5a2021-03-30 22:21:24 +00001576 if (effect->isHapticGenerator()) {
1577 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1578 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001579 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1580 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1581 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001582 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001583 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001584 }
1585 }
Eric Laurent81784c32012-11-19 14:55:58 -08001586 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001587 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001588 lStatus = handle->initCheck();
1589 if (lStatus == OK) {
1590 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001591 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001592 }
Eric Laurent81784c32012-11-19 14:55:58 -08001593 if (enabled != NULL) {
1594 *enabled = (int)effect->isEnabled();
1595 }
1596 }
1597
1598Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001599 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001600 Mutex::Autolock _l(mLock);
1601 if (effectCreated) {
1602 chain->removeEffect_l(effect);
1603 }
Eric Laurent81784c32012-11-19 14:55:58 -08001604 if (chainCreated) {
1605 removeEffectChain_l(chain);
1606 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001607 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001608 }
1609
Glenn Kasten9156ef32013-08-06 15:39:08 -07001610 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001611 return handle;
1612}
1613
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001614void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1615 bool unpinIfLast)
1616{
1617 bool remove = false;
1618 sp<EffectModule> effect;
1619 {
1620 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001621 sp<EffectBase> effectBase = handle->effect().promote();
1622 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001623 return;
1624 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001625 effect = effectBase->asEffectModule();
1626 if (effect == nullptr) {
1627 return;
1628 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001629 // restore suspended effects if the disconnected handle was enabled and the last one.
1630 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1631 if (remove) {
1632 removeEffect_l(effect, true);
1633 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001634 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001635 }
1636 if (remove) {
1637 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001638 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001639 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001640 }
1641 }
1642}
1643
Eric Laurent6b446ce2019-12-13 10:56:31 -08001644void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001645 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001646 Mutex::Autolock _l(mLock);
1647 broadcast_l();
1648 }
1649 if (!effect->isOffloadable()) {
1650 if (mType == ThreadBase::OFFLOAD) {
1651 PlaybackThread *t = (PlaybackThread *)this;
1652 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1653 }
1654 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1655 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1656 }
1657 }
1658}
1659
1660void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001661 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001662 Mutex::Autolock _l(mLock);
1663 broadcast_l();
1664 }
1665}
1666
Glenn Kastend848eb42016-03-08 13:42:11 -08001667sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1668 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001669{
1670 Mutex::Autolock _l(mLock);
1671 return getEffect_l(sessionId, effectId);
1672}
1673
Glenn Kastend848eb42016-03-08 13:42:11 -08001674sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1675 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001676{
1677 sp<EffectChain> chain = getEffectChain_l(sessionId);
1678 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1679}
1680
Eric Laurent6c796322019-04-09 14:13:17 -07001681std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1682{
1683 sp<EffectChain> chain = getEffectChain_l(sessionId);
1684 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1685}
1686
Eric Laurent81784c32012-11-19 14:55:58 -08001687// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1688// PlaybackThread::mLock held
1689status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1690{
1691 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001692 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001693 sp<EffectChain> chain = getEffectChain_l(sessionId);
1694 bool chainCreated = false;
1695
Eric Laurent5baf2af2013-09-12 17:37:00 -07001696 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001697 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001698 this, effect->desc().name, effect->desc().flags);
1699
Eric Laurent81784c32012-11-19 14:55:58 -08001700 if (chain == 0) {
1701 // create a new chain for this session
1702 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1703 chain = new EffectChain(this, sessionId);
1704 addEffectChain_l(chain);
1705 chain->setStrategy(getStrategyForSession_l(sessionId));
1706 chainCreated = true;
1707 }
1708 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1709
1710 if (chain->getEffectFromId_l(effect->id()) != 0) {
1711 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1712 this, effect->desc().name, chain.get());
1713 return BAD_VALUE;
1714 }
1715
Eric Laurent5baf2af2013-09-12 17:37:00 -07001716 effect->setOffloaded(mType == OFFLOAD, mId);
1717
Eric Laurent81784c32012-11-19 14:55:58 -08001718 status_t status = chain->addEffect_l(effect);
1719 if (status != NO_ERROR) {
1720 if (chainCreated) {
1721 removeEffectChain_l(chain);
1722 }
1723 return status;
1724 }
1725
jiabin8f278ee2019-11-11 12:16:27 -08001726 effect->setDevices(outDeviceTypeAddrs());
1727 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001728 effect->setMode(mAudioFlinger->getMode());
1729 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001730
Eric Laurent81784c32012-11-19 14:55:58 -08001731 return NO_ERROR;
1732}
1733
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001734void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001735
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001736 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001737 effect_descriptor_t desc = effect->desc();
1738 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1739 detachAuxEffect_l(effect->id());
1740 }
1741
Andy Hungfda44002021-06-03 17:23:16 -07001742 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001743 if (chain != 0) {
1744 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001746 removeEffectChain_l(chain);
1747 }
1748 } else {
1749 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1750 }
1751}
1752
1753void AudioFlinger::ThreadBase::lockEffectChains_l(
1754 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001755NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001756{
1757 effectChains = mEffectChains;
1758 for (size_t i = 0; i < mEffectChains.size(); i++) {
1759 mEffectChains[i]->lock();
1760 }
1761}
1762
1763void AudioFlinger::ThreadBase::unlockEffectChains(
1764 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001765NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001766{
1767 for (size_t i = 0; i < effectChains.size(); i++) {
1768 effectChains[i]->unlock();
1769 }
1770}
1771
Glenn Kastend848eb42016-03-08 13:42:11 -08001772sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001773{
1774 Mutex::Autolock _l(mLock);
1775 return getEffectChain_l(sessionId);
1776}
1777
Glenn Kastend848eb42016-03-08 13:42:11 -08001778sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1779 const
Eric Laurent81784c32012-11-19 14:55:58 -08001780{
1781 size_t size = mEffectChains.size();
1782 for (size_t i = 0; i < size; i++) {
1783 if (mEffectChains[i]->sessionId() == sessionId) {
1784 return mEffectChains[i];
1785 }
1786 }
1787 return 0;
1788}
1789
1790void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1791{
1792 Mutex::Autolock _l(mLock);
1793 size_t size = mEffectChains.size();
1794 for (size_t i = 0; i < size; i++) {
1795 mEffectChains[i]->setMode_l(mode);
1796 }
1797}
1798
Mikhail Naganovdc769682018-05-04 15:34:08 -07001799void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001800{
1801 config->type = AUDIO_PORT_TYPE_MIX;
1802 config->ext.mix.handle = mId;
1803 config->sample_rate = mSampleRate;
1804 config->format = mFormat;
1805 config->channel_mask = mChannelMask;
1806 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1807 AUDIO_PORT_CONFIG_FORMAT;
1808}
1809
Eric Laurent72e3f392015-05-20 14:43:50 -07001810void AudioFlinger::ThreadBase::systemReady()
1811{
1812 Mutex::Autolock _l(mLock);
1813 if (mSystemReady) {
1814 return;
1815 }
1816 mSystemReady = true;
1817
1818 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1819 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1820 }
1821 mPendingConfigEvents.clear();
1822}
1823
Andy Hungdae27702016-10-31 14:01:16 -07001824template <typename T>
1825ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1826 ssize_t index = mActiveTracks.indexOf(track);
1827 if (index >= 0) {
1828 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1829 return index;
1830 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001831 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001832 mActiveTracksGeneration++;
1833 mLatestActiveTrack = track;
1834 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001835 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001836 return mActiveTracks.add(track);
1837}
1838
1839template <typename T>
1840ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1841 ssize_t index = mActiveTracks.remove(track);
1842 if (index < 0) {
1843 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1844 return index;
1845 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001846 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001847 mActiveTracksGeneration++;
1848 --mBatteryCounter[track->uid()].second;
1849 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001850 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001851#ifdef TEE_SINK
1852 track->dumpTee(-1 /* fd */, "_REMOVE");
1853#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001854 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001855 return index;
1856}
1857
1858template <typename T>
1859void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1860 for (const sp<T> &track : mActiveTracks) {
1861 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001862 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001863 }
1864 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001865 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001866 mActiveTracks.clear();
1867 mLatestActiveTrack.clear();
1868 mBatteryCounter.clear();
1869}
1870
1871template <typename T>
1872void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001873 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001874 // Updates ActiveTracks client uids to the thread wakelock.
1875 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1876 thread->updateWakeLockUids_l(getWakeLockUids());
1877 mLastActiveTracksGeneration = mActiveTracksGeneration;
1878 }
1879
1880 // Updates BatteryNotifier uids
1881 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1882 const uid_t uid = it->first;
1883 ssize_t &previous = it->second.first;
1884 ssize_t &current = it->second.second;
1885 if (current > 0) {
1886 if (previous == 0) {
1887 BatteryNotifier::getInstance().noteStartAudio(uid);
1888 }
1889 previous = current;
1890 ++it;
1891 } else if (current == 0) {
1892 if (previous > 0) {
1893 BatteryNotifier::getInstance().noteStopAudio(uid);
1894 }
1895 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1896 } else /* (current < 0) */ {
1897 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1898 }
1899 }
1900}
Eric Laurent83b88082014-06-20 18:31:16 -07001901
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001902template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001903bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001904 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001905 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001906
1907 for (const sp<T> &track : mActiveTracks) {
1908 // Do not short-circuit as all hasChanged states must be reset
1909 // as all the metadata are going to be sent
1910 hasChanged |= track->readAndClearHasChanged();
1911 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001912 return hasChanged;
1913}
1914
1915template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001916void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1917 const char *funcName, const sp<T> &track) const {
1918 if (mLocalLog != nullptr) {
1919 String8 result;
1920 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00001921 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001922 }
1923}
1924
Eric Laurent6acd1d42017-01-04 14:23:29 -08001925void AudioFlinger::ThreadBase::broadcast_l()
1926{
1927 // Thread could be blocked waiting for async
1928 // so signal it to handle state changes immediately
1929 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1930 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1931 mSignalPending = true;
1932 mWaitWorkCV.broadcast();
1933}
1934
Andy Hungd0979812019-02-21 15:51:44 -08001935// Call only from threadLoop() or when it is idle.
1936// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1937void AudioFlinger::ThreadBase::sendStatistics(bool force)
1938{
1939 // Do not log if we have no stats.
1940 // We choose the timestamp verifier because it is the most likely item to be present.
1941 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1942 if (nstats == 0) {
1943 return;
1944 }
1945
1946 // Don't log more frequently than once per 12 hours.
1947 // We use BOOTTIME to include suspend time.
1948 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1949 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1950 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1951 return;
1952 }
1953
1954 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1955 mLastRecordedTimeNs = timeNs;
1956
Ray Essickf27e9872019-12-07 06:28:46 -08001957 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001958
1959#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1960
1961 // thread configuration
1962 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1963 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1964 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1965 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1966 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1967 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1968 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001969 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1970 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001971
1972 // thread statistics
1973 if (mIoJitterMs.getN() > 0) {
1974 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1975 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1976 }
1977 if (mProcessTimeMs.getN() > 0) {
1978 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1979 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1980 }
1981 const auto tsjitter = mTimestampVerifier.getJitterMs();
1982 if (tsjitter.getN() > 0) {
1983 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1984 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1985 }
1986 if (mLatencyMs.getN() > 0) {
1987 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1988 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1989 }
Robert Wu06db0a32021-08-10 19:05:34 +00001990 if (mMonopipePipeDepthStats.getN() > 0) {
1991 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1992 mMonopipePipeDepthStats.getMean());
1993 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1994 mMonopipePipeDepthStats.getStdDev());
1995 }
Andy Hungd0979812019-02-21 15:51:44 -08001996
1997 item->selfrecord();
1998}
1999
Eric Laurentd66d7a12021-07-13 13:35:32 +02002000product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
2001{
2002 if (!mAudioFlinger->isAudioPolicyReady()) {
2003 return PRODUCT_STRATEGY_NONE;
2004 }
2005 return AudioSystem::getStrategyForStream(stream);
2006}
2007
Eric Laurent81784c32012-11-19 14:55:58 -08002008// ----------------------------------------------------------------------------
2009// Playback
2010// ----------------------------------------------------------------------------
2011
2012AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
2013 AudioStreamOut* output,
2014 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002015 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002016 bool systemReady,
2017 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002018 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002019 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002020 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002021 mMixerBuffer(NULL),
2022 mMixerBufferSize(0),
2023 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2024 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002025 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002026 mEffectBuffer(NULL),
2027 mEffectBufferSize(0),
2028 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2029 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002030 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002031 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002032 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002033 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002034 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002035 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002036 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002037 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002038 mMixerStatus(MIXER_IDLE),
2039 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002040 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002041 mBytesRemaining(0),
2042 mCurrentWriteLength(0),
2043 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002044 mWriteAckSequence(0),
2045 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002046 mScreenState(AudioFlinger::mScreenState),
2047 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002048 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002049 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002050 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002051 mDownStreamPatch{},
Eric Laurent01eb1642022-12-16 11:45:07 +01002052 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs),
2053 mBluetoothLatencyModesEnabled(true)
Eric Laurent81784c32012-11-19 14:55:58 -08002054{
Glenn Kastend7dca052015-03-05 16:05:54 -08002055 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2056 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002057
2058 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2059 // it would be safer to explicitly pass initial masterVolume/masterMute as
2060 // parameter.
2061 //
2062 // If the HAL we are using has support for master volume or master mute,
2063 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2064 // and the mute set to false).
2065 mMasterVolume = audioFlinger->masterVolume_l();
2066 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002067 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002068 if (mOutput->audioHwDev->canSetMasterVolume()) {
2069 mMasterVolume = 1.0;
2070 }
2071
2072 if (mOutput->audioHwDev->canSetMasterMute()) {
2073 mMasterMute = false;
2074 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002075 mIsMsdDevice = strcmp(
2076 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002077 }
2078
Eric Laurentf1f22e72021-07-13 14:04:14 +02002079 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2080 mMixerChannelMask = mixerConfig->channel_mask;
2081 }
2082
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002083 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002084
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002085 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002086 && mMixerChannelMask != mChannelMask) {
2087 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2088 mChannelMask, mMixerChannelMask);
2089 }
2090
Andy Hungc8fddf32018-08-08 18:32:37 -07002091 // TODO: We may also match on address as well as device type for
2092 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002093 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002094 // TODO: This property should be ensure that only contains one single device type.
2095 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2096 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002097 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2098 : AUDIO_DEVICE_NONE));
2099 }
2100
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002101 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2102 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002103 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002104 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2105 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002106 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002107 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2108 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002109 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2110 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002111}
2112
2113AudioFlinger::PlaybackThread::~PlaybackThread()
2114{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002115 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002116 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002117 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002118 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002119 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002120}
2121
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002122// Thread virtuals
2123
2124void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002125{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002126 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002127 ALOGE("The stream is not open yet"); // This should not happen.
2128 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002129 // Callbacks take strong or weak pointers as a parameter.
2130 // Since PlaybackThread passes itself as a callback handler, it can only
2131 // be done outside of the constructor. Creating weak and especially strong
2132 // pointers to a refcounted object in its own constructor is strongly
2133 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2134 // Even if a function takes a weak pointer, it is possible that it will
2135 // need to convert it to a strong pointer down the line.
2136 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2137 mOutput->stream->setCallback(this) == OK) {
2138 mUseAsyncWrite = true;
2139 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2140 }
2141
jiabinf6eb4c32020-02-25 14:06:25 -08002142 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002143 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002144 }
2145 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002146 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002147 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002148}
2149
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002150// ThreadBase virtuals
2151void AudioFlinger::PlaybackThread::preExit()
2152{
2153 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002154 status_t result = mOutput->stream->exit();
2155 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002156}
2157
2158void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002159{
Eric Laurent81784c32012-11-19 14:55:58 -08002160 String8 result;
2161
Marco Nelissenb2208842014-02-07 14:00:50 -08002162 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002163 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2164 const stream_type_t *st = &mStreamTypes[i];
2165 if (i > 0) {
2166 result.appendFormat(", ");
2167 }
2168 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2169 if (st->mute) {
2170 result.append("M");
2171 }
2172 }
2173 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002174 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002175 result.clear();
2176
Eric Laurent81784c32012-11-19 14:55:58 -08002177 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2178 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002179 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002180 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002181
2182 size_t numtracks = mTracks.size();
2183 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002184 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002185 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002186 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002187 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002188 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002189 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002190 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002191 for (size_t i = 0; i < numtracks; ++i) {
2192 sp<Track> track = mTracks[i];
2193 if (track != 0) {
2194 bool active = mActiveTracks.indexOf(track) >= 0;
2195 if (active) {
2196 numactiveseen++;
2197 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002198 result.append(prefix);
2199 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002200 }
2201 }
2202 } else {
2203 result.append("\n");
2204 }
2205 if (numactiveseen != numactive) {
2206 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002207 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002208 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002209 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002210 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002211 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002212 sp<Track> track = mActiveTracks[i];
2213 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002214 result.append(prefix);
2215 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002216 }
2217 }
2218 }
2219
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002220 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002221}
2222
Andy Hung61589a42021-06-16 09:37:53 -07002223void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002224{
Andy Hung04cb8f72020-03-20 13:44:33 -07002225 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002226 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002227 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2228 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002229 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2230 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2231 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2232 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002233 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002234 dprintf(fd, " Total writes: %d\n", mNumWrites);
2235 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2236 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2237 dprintf(fd, " Suspend count: %d\n", mSuspended);
2238 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2239 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2240 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2241 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002242 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002243 AudioStreamOut *output = mOutput;
2244 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002245 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002246 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002247 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2248 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2249 if (mPipeSink.get() != nullptr) {
2250 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2251 }
2252 if (output != nullptr) {
2253 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002254 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002255 }
Eric Laurent81784c32012-11-19 14:55:58 -08002256}
2257
Eric Laurent81784c32012-11-19 14:55:58 -08002258// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2259sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2260 const sp<AudioFlinger::Client>& client,
2261 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002262 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002263 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002264 audio_format_t format,
2265 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002266 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002267 size_t *pNotificationFrameCount,
2268 uint32_t notificationsPerBuffer,
2269 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002270 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002271 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002272 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002273 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002274 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002275 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002276 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002277 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002278 const sp<media::IAudioTrackCallback>& callback,
2279 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002280{
Glenn Kasten74935e42013-12-19 08:56:45 -08002281 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002282 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002283 sp<Track> track;
2284 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002285 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002286 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002287 uint32_t sampleRate;
2288
2289 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2290 lStatus = BAD_VALUE;
2291 goto Exit;
2292 }
Eric Laurent21da6472017-11-09 16:29:26 -08002293
2294 if (*pSampleRate == 0) {
2295 *pSampleRate = mSampleRate;
2296 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002297 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002298
2299 // special case for FAST flag considered OK if fast mixer is present
2300 if (hasFastMixer()) {
2301 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2302 }
2303
2304 // Check if requested flags are compatible with output stream flags
2305 if ((*flags & outputFlags) != *flags) {
2306 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2307 *flags, outputFlags);
2308 *flags = (audio_output_flags_t)(*flags & outputFlags);
2309 }
Eric Laurent81784c32012-11-19 14:55:58 -08002310
Eric Laurent81784c32012-11-19 14:55:58 -08002311 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002312 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002313 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002314 // PCM data
2315 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002316 // TODO: extract as a data library function that checks that a computationally
2317 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002318 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002319 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2320 (channelMask == AUDIO_CHANNEL_OUT_MONO
2321 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002322 // hardware sample rate
2323 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002324 // normal mixer has an associated fast mixer
2325 hasFastMixer() &&
2326 // there are sufficient fast track slots available
2327 (mFastTrackAvailMask != 0)
2328 // FIXME test that MixerThread for this fast track has a capable output HAL
2329 // FIXME add a permission test also?
2330 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002331 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2332 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002333 // read the fast track multiplier property the first time it is needed
2334 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2335 if (ok != 0) {
2336 ALOGE("%s pthread_once failed: %d", __func__, ok);
2337 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002338 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002339 }
Eric Laurent4c415062016-06-17 16:14:16 -07002340
2341 // check compatibility with audio effects.
2342 { // scope for mLock
2343 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002344 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002345 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002346 AUDIO_SESSION_OUTPUT_STAGE,
2347 AUDIO_SESSION_OUTPUT_MIX,
2348 sessionId,
2349 }) {
2350 sp<EffectChain> chain = getEffectChain_l(session);
2351 if (chain.get() != nullptr) {
2352 audio_output_flags_t old = *flags;
2353 chain->checkOutputFlagCompatibility(flags);
2354 if (old != *flags) {
2355 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2356 (int)session, (int)old, (int)*flags);
2357 }
Eric Laurent4c415062016-06-17 16:14:16 -07002358 }
2359 }
2360 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002361 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002362 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2363 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002364 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002365 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002366 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002367 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002368 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002369 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002370 audio_is_linear_pcm(format), channelMask, sampleRate,
2371 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002372 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002373 }
2374 }
Eric Laurent21da6472017-11-09 16:29:26 -08002375
2376 if (!audio_has_proportional_frames(format)) {
2377 if (sharedBuffer != 0) {
2378 // Same comment as below about ignoring frameCount parameter for set()
2379 frameCount = sharedBuffer->size();
2380 } else if (frameCount == 0) {
2381 frameCount = mNormalFrameCount;
2382 }
2383 if (notificationFrameCount != frameCount) {
2384 notificationFrameCount = frameCount;
2385 }
2386 } else if (sharedBuffer != 0) {
2387 // FIXME: Ensure client side memory buffers need
2388 // not have additional alignment beyond sample
2389 // (e.g. 16 bit stereo accessed as 32 bit frame).
2390 size_t alignment = audio_bytes_per_sample(format);
2391 if (alignment & 1) {
2392 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2393 alignment = 1;
2394 }
2395 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2396 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2397 if (channelCount > 1) {
2398 // More than 2 channels does not require stronger alignment than stereo
2399 alignment <<= 1;
2400 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002401 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002402 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002403 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002404 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002405 goto Exit;
2406 }
Eric Laurent21da6472017-11-09 16:29:26 -08002407
2408 // When initializing a shared buffer AudioTrack via constructors,
2409 // there's no frameCount parameter.
2410 // But when initializing a shared buffer AudioTrack via set(),
2411 // there _is_ a frameCount parameter. We silently ignore it.
2412 frameCount = sharedBuffer->size() / frameSize;
2413 } else {
2414 size_t minFrameCount = 0;
2415 // For fast tracks we try to respect the application's request for notifications per buffer.
2416 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2417 if (notificationsPerBuffer > 0) {
2418 // Avoid possible arithmetic overflow during multiplication.
2419 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2420 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2421 notificationsPerBuffer, mFrameCount);
2422 } else {
2423 minFrameCount = mFrameCount * notificationsPerBuffer;
2424 }
2425 }
2426 } else {
2427 // For normal PCM streaming tracks, update minimum frame count.
2428 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2429 // cover audio hardware latency.
2430 // This is probably too conservative, but legacy application code may depend on it.
2431 // If you change this calculation, also review the start threshold which is related.
2432 uint32_t latencyMs = latency_l();
2433 if (latencyMs == 0) {
2434 ALOGE("Error when retrieving output stream latency");
2435 lStatus = UNKNOWN_ERROR;
2436 goto Exit;
2437 }
2438
2439 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2440 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2441
Eric Laurent81784c32012-11-19 14:55:58 -08002442 }
Eric Laurent21da6472017-11-09 16:29:26 -08002443 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002444 frameCount = minFrameCount;
2445 }
Eric Laurent81784c32012-11-19 14:55:58 -08002446 }
Eric Laurent21da6472017-11-09 16:29:26 -08002447
2448 // Make sure that application is notified with sufficient margin before underrun.
2449 // The client can divide the AudioTrack buffer into sub-buffers,
2450 // and expresses its desire to server as the notification frame count.
2451 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2452 size_t maxNotificationFrames;
2453 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2454 // notify every HAL buffer, regardless of the size of the track buffer
2455 maxNotificationFrames = mFrameCount;
2456 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002457 // Triple buffer the notification period for a triple buffered mixer period;
2458 // otherwise, double buffering for the notification period is fine.
2459 //
2460 // TODO: This should be moved to AudioTrack to modify the notification period
2461 // on AudioTrack::setBufferSizeInFrames() changes.
2462 const int nBuffering =
2463 (uint64_t{frameCount} * mSampleRate)
2464 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2465
Eric Laurent21da6472017-11-09 16:29:26 -08002466 maxNotificationFrames = frameCount / nBuffering;
2467 // If client requested a fast track but this was denied, then use the smaller maximum.
2468 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2469 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2470 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2471 maxNotificationFrames = maxNotificationFramesFastDenied;
2472 }
2473 }
2474 }
2475 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2476 if (notificationFrameCount == 0) {
2477 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2478 maxNotificationFrames, frameCount);
2479 } else {
2480 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2481 notificationFrameCount, maxNotificationFrames, frameCount);
2482 }
2483 notificationFrameCount = maxNotificationFrames;
2484 }
2485 }
2486
Glenn Kasten74935e42013-12-19 08:56:45 -08002487 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002488 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002489
Glenn Kastenc3df8382014-03-13 15:05:25 -07002490 switch (mType) {
2491
2492 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002493 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002494 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002495 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2496 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002497 sampleRate, format, channelMask, mOutput, mFormat);
2498 lStatus = BAD_VALUE;
2499 goto Exit;
2500 }
2501 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002502 break;
2503
2504 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002505 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002506 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2507 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002508 sampleRate, format, channelMask, mOutput, mFormat);
2509 lStatus = BAD_VALUE;
2510 goto Exit;
2511 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002512 break;
2513
2514 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002515 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002516 ALOGE("createTrack_l() Bad parameter: format %#x \""
2517 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002518 format, mOutput, mFormat);
2519 lStatus = BAD_VALUE;
2520 goto Exit;
2521 }
Andy Hungcd044842014-08-07 11:04:34 -07002522 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002523 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2524 lStatus = BAD_VALUE;
2525 goto Exit;
2526 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002527 break;
2528
Eric Laurent81784c32012-11-19 14:55:58 -08002529 }
2530
2531 lStatus = initCheck();
2532 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002533 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002534 goto Exit;
2535 }
2536
2537 { // scope for mLock
2538 Mutex::Autolock _l(mLock);
2539
2540 // all tracks in same audio session must share the same routing strategy otherwise
2541 // conflicts will happen when tracks are moved from one output to another by audio policy
2542 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002543 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002544 for (size_t i = 0; i < mTracks.size(); ++i) {
2545 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002546 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002547 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002548 if (sessionId == t->sessionId() && strategy != actual) {
2549 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2550 strategy, actual);
2551 lStatus = BAD_VALUE;
2552 goto Exit;
2553 }
2554 }
2555 }
2556
yucliuc9c49cd2020-07-13 16:25:21 -07002557 // Set DIRECT flag if current thread is DirectOutputThread. This can
2558 // happen when the playback is rerouted to direct output thread by
2559 // dynamic audio policy.
2560 // Do NOT report the flag changes back to client, since the client
2561 // doesn't explicitly request a direct flag.
2562 audio_output_flags_t trackFlags = *flags;
2563 if (mType == DIRECT) {
2564 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2565 }
2566
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002567 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002568 channelMask, frameCount,
2569 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002570 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002571 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2572 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002573
Glenn Kasten03003332013-08-06 15:40:54 -07002574 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2575 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002576 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002577 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002578 goto Exit;
2579 }
2580 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002581 {
2582 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2583 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002584 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002585 }
2586 }
Eric Laurent81784c32012-11-19 14:55:58 -08002587
2588 sp<EffectChain> chain = getEffectChain_l(sessionId);
2589 if (chain != 0) {
2590 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2591 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002592 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002593 chain->incTrackCnt();
2594 }
2595
Eric Laurent05067782016-06-01 18:27:28 -07002596 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002597 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2598 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2599 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002600 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002601 }
2602 }
2603
2604 lStatus = NO_ERROR;
2605
2606Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002607 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002608 return track;
2609}
2610
Andy Hung1bc088a2018-02-09 15:57:31 -08002611template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002612ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2613{
Andy Hungc0691382018-09-12 18:01:57 -07002614 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002615 const ssize_t index = mTracks.remove(track);
2616 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002617 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002618 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002619 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002620 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002621 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002622 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002623 }
2624 return index;
2625}
2626
Eric Laurent81784c32012-11-19 14:55:58 -08002627uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2628{
2629 return latency;
2630}
2631
2632uint32_t AudioFlinger::PlaybackThread::latency() const
2633{
2634 Mutex::Autolock _l(mLock);
2635 return latency_l();
2636}
2637uint32_t AudioFlinger::PlaybackThread::latency_l() const
2638{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002639 uint32_t latency;
2640 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2641 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002642 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002643 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002644}
2645
2646void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2647{
2648 Mutex::Autolock _l(mLock);
2649 // Don't apply master volume in SW if our HAL can do it for us.
2650 if (mOutput && mOutput->audioHwDev &&
2651 mOutput->audioHwDev->canSetMasterVolume()) {
2652 mMasterVolume = 1.0;
2653 } else {
2654 mMasterVolume = value;
2655 }
2656}
2657
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002658void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2659{
2660 mMasterBalance.store(balance);
2661}
2662
Eric Laurent81784c32012-11-19 14:55:58 -08002663void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2664{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002665 if (isDuplicating()) {
2666 return;
2667 }
Eric Laurent81784c32012-11-19 14:55:58 -08002668 Mutex::Autolock _l(mLock);
2669 // Don't apply master mute in SW if our HAL can do it for us.
2670 if (mOutput && mOutput->audioHwDev &&
2671 mOutput->audioHwDev->canSetMasterMute()) {
2672 mMasterMute = false;
2673 } else {
2674 mMasterMute = muted;
2675 }
2676}
2677
2678void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2679{
2680 Mutex::Autolock _l(mLock);
2681 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002682 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002683}
2684
2685void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2686{
2687 Mutex::Autolock _l(mLock);
2688 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002689 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002690}
2691
2692float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2693{
2694 Mutex::Autolock _l(mLock);
2695 return mStreamTypes[stream].volume;
2696}
2697
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002698void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2699{
2700 mOutput->stream->setVolume(left, right);
2701}
2702
Eric Laurent81784c32012-11-19 14:55:58 -08002703// addTrack_l() must be called with ThreadBase::mLock held
2704status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002705NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002706{
2707 status_t status = ALREADY_EXISTS;
2708
Eric Laurent81784c32012-11-19 14:55:58 -08002709 if (mActiveTracks.indexOf(track) < 0) {
2710 // the track is newly added, make sure it fills up all its
2711 // buffers before playing. This is to ensure the client will
2712 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002713 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002714 TrackBase::track_state state = track->mState;
2715 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002716 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002717 mLock.lock();
2718 // abort track was stopped/paused while we released the lock
2719 if (state != track->mState) {
2720 if (status == NO_ERROR) {
2721 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002722 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002723 mLock.lock();
2724 }
2725 return INVALID_OPERATION;
2726 }
2727 // abort if start is rejected by audio policy manager
2728 if (status != NO_ERROR) {
2729 return PERMISSION_DENIED;
2730 }
2731#ifdef ADD_BATTERY_DATA
2732 // to track the speaker usage
2733 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2734#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002735 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002736 }
2737
Eric Laurent51716182016-02-29 18:00:56 -08002738 // set retry count for buffer fill
2739 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002740 if (track->isStopping_1()) {
2741 track->mRetryCount = kMaxTrackStopRetriesOffload;
2742 } else {
2743 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2744 }
2745 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002746 } else {
2747 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002748 track->mFillingUpStatus =
2749 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002750 }
2751
jiabineb3bda02020-06-30 14:07:03 -07002752 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2753 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2754 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2755 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002756 // Unlock due to VibratorService will lock for this call and will
2757 // call Tracks.mute/unmute which also require thread's lock.
2758 mLock.unlock();
2759 const int intensity = AudioFlinger::onExternalVibrationStart(
2760 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002761 std::optional<media::AudioVibratorInfo> vibratorInfo;
2762 {
2763 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2764 // used to play this track.
2765 Mutex::Autolock _l(mAudioFlinger->mLock);
2766 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2767 }
jiabin57303cc2018-12-18 15:45:57 -08002768 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002769 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002770 if (vibratorInfo) {
2771 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2772 }
2773
jiabin57303cc2018-12-18 15:45:57 -08002774 // Haptic playback should be enabled by vibrator service.
2775 if (track->getHapticPlaybackEnabled()) {
2776 // Disable haptic playback of all active track to ensure only
2777 // one track playing haptic if current track should play haptic.
2778 for (const auto &t : mActiveTracks) {
2779 t->setHapticPlaybackEnabled(false);
2780 }
jiabin245cdd92018-12-07 17:55:15 -08002781 }
jiabine70bc7f2020-06-30 22:07:55 -07002782
2783 // Set haptic intensity for effect
2784 if (chain != nullptr) {
2785 chain->setHapticIntensity_l(track->id(), intensity);
2786 }
jiabin245cdd92018-12-07 17:55:15 -08002787 }
2788
Eric Laurent81784c32012-11-19 14:55:58 -08002789 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002790 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002791 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002792 if (chain != 0) {
2793 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2794 track->sessionId());
2795 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002796 }
2797
Andy Hungc2b11cb2020-04-22 09:04:01 -07002798 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002799 status = NO_ERROR;
2800 }
2801
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002802 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002803 return status;
2804}
2805
Eric Laurentbfb1b832013-01-07 09:53:42 -08002806bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002807{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002808 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002809 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002810 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2811 track->mState = TrackBase::STOPPED;
2812 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002813 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002814 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002815 if (track->isPausePending()) {
2816 track->pauseAck();
2817 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002819 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820
2821 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002822}
2823
2824void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2825{
2826 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002827
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002828 String8 result;
2829 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002830 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002831
Eric Laurent81784c32012-11-19 14:55:58 -08002832 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002833 {
2834 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2835 mAudioTrackCallbacks.erase(track);
2836 }
Eric Laurent81784c32012-11-19 14:55:58 -08002837 if (track->isFastTrack()) {
2838 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002839 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002840 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2841 mFastTrackAvailMask |= 1 << index;
2842 // redundant as track is about to be destroyed, for dumpsys only
2843 track->mFastIndex = -1;
2844 }
2845 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2846 if (chain != 0) {
2847 chain->decTrackCnt();
2848 }
2849}
2850
2851String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2852{
Eric Laurent81784c32012-11-19 14:55:58 -08002853 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002854 String8 out_s8;
2855 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2856 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002857 }
Andy Hung71ba4b32022-10-06 12:09:49 -07002858 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002859}
2860
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002861status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2862 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002863 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002864 return NO_INIT;
2865 }
2866 return mOutput->stream->selectPresentation(presentationId, programId);
2867}
2868
Mikhail Naganov88536df2021-07-26 17:30:29 -07002869void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002870 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002871 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002872 sp<AudioIoDescriptor> desc;
2873 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002874 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002875 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002876 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002877 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002878 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2879 mSampleRate, mFormat, mChannelMask,
2880 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2881 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002882 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002883 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002884 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002885 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002886 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002887 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002888 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002889 break;
2890 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002891 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002892}
2893
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002894void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002896 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897}
2898
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002899void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002901 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902}
2903
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002904void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002905{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002906 mCallbackThread->setAsyncError();
2907}
2908
jiabinf6eb4c32020-02-25 14:06:25 -08002909void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2910 const std::basic_string<uint8_t>& metadataBs)
2911{
Kuowei Li9e2f6162022-11-23 16:25:26 +08002912 wp<AudioFlinger::PlaybackThread> weakPointerThis = this;
2913 std::thread([this, metadataBs, weakPointerThis]() {
2914 sp<AudioFlinger::PlaybackThread> playbackThread = weakPointerThis.promote();
2915 if (playbackThread == nullptr) {
2916 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2917 return;
2918 }
2919
jiabinf6eb4c32020-02-25 14:06:25 -08002920 audio_utils::metadata::Data metadata =
2921 audio_utils::metadata::dataFromByteString(metadataBs);
2922 if (metadata.empty()) {
2923 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2924 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2925 (int)metadataBs.size());
2926 return;
2927 }
2928
2929 audio_utils::metadata::ByteString metaDataStr =
2930 audio_utils::metadata::byteStringFromData(metadata);
2931 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2932 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002933 for (const auto& callbackPair : mAudioTrackCallbacks) {
2934 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002935 }
2936 }).detach();
2937}
2938
Eric Laurent3b4529e2013-09-05 18:09:19 -07002939void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002940{
2941 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002942 // reject out of sequence requests
2943 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2944 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002945 mWaitWorkCV.signal();
2946 }
2947}
2948
Eric Laurent3b4529e2013-09-05 18:09:19 -07002949void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950{
2951 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002952 // reject out of sequence requests
2953 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002954 // Register discontinuity when HW drain is completed because that can cause
2955 // the timestamp frame position to reset to 0 for direct and offload threads.
2956 // (Out of sequence requests are ignored, since the discontinuity would be handled
2957 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002958 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002959 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960 mWaitWorkCV.signal();
2961 }
2962}
2963
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002964void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002965{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002966 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002967 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2968 mSampleRate = audioConfig.sample_rate;
2969 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002970 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002971 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002972 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002973 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002974 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2975 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002976 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002977
2978 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2979 mMixerChannelMask = mChannelMask;
2980 }
2981
Andy Hunge5412692014-05-16 11:25:07 -07002982 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002983 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002984
Eric Laurentf1f22e72021-07-13 14:04:14 +02002985 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2986
Phil Burkca5e6142015-07-14 09:42:29 -07002987 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002988 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002989 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002990 // Get format from the shim, which will be different than the HAL format
2991 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002992 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002993 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002994 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002995 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002996 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002997 LOG_FATAL("HAL format %#x not supported for mixed output",
2998 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002999 }
Phil Burk062e67a2015-02-11 13:40:50 -08003000 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003001 result = mOutput->stream->getBufferSize(&mBufferSize);
3002 LOG_ALWAYS_FATAL_IF(result != OK,
3003 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003004 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003005 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003006 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003007 mFrameCount);
3008 }
3009
Eric Laurentd1f69b02014-12-15 14:33:13 -08003010 mHwSupportsPause = false;
3011 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003012 bool supportsPause = false, supportsResume = false;
3013 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3014 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003015 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003016 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003017 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003018 } else if (supportsResume) {
3019 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003020 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003021 }
3022 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003023 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3024 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3025 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003026
Andy Hungfbfc3952015-01-15 13:33:51 -08003027 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3028 // For best precision, we use float instead of the associated output
3029 // device format (typically PCM 16 bit).
3030
3031 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3032 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3033 mBufferSize = mFrameSize * mFrameCount;
3034
3035 // TODO: We currently use the associated output device channel mask and sample rate.
3036 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3037 // (if a valid mask) to avoid premature downmix.
3038 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3039 // instead of the output device sample rate to avoid loss of high frequency information.
3040 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3041 }
3042
Andy Hung09a50072014-02-27 14:30:47 -08003043 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003044 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003045 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003046 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3047 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003048 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3049 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003050
Eric Laurent81784c32012-11-19 14:55:58 -08003051 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3052 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3053 maxNormalFrameCount = maxNormalFrameCount & ~15;
3054 if (maxNormalFrameCount < minNormalFrameCount) {
3055 maxNormalFrameCount = minNormalFrameCount;
3056 }
3057 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3058 if (multiplier <= 1.0) {
3059 multiplier = 1.0;
3060 } else if (multiplier <= 2.0) {
3061 if (2 * mFrameCount <= maxNormalFrameCount) {
3062 multiplier = 2.0;
3063 } else {
3064 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3065 }
3066 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003067 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003068 }
3069 }
3070 mNormalFrameCount = multiplier * mFrameCount;
3071 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003072 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003073 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3074 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003075 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003076 mNormalFrameCount);
3077
Andy Hung08fb1742015-05-31 23:22:10 -07003078 // Check if we want to throttle the processing to no more than 2x normal rate
3079 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003080 mThreadThrottleTimeMs = 0;
3081 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003082 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3083
Andy Hung010a1a12014-03-13 13:57:33 -07003084 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3085 // Originally this was int16_t[] array, need to remove legacy implications.
3086 free(mSinkBuffer);
3087 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003088
Andy Hung5b10a202014-03-13 13:59:29 -07003089 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3090 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3091 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003092 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003093
Andy Hung69aed5f2014-02-25 17:24:40 -08003094 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3095 // drives the output.
3096 free(mMixerBuffer);
3097 mMixerBuffer = NULL;
3098 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003099 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003100 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003101 * audio_bytes_per_sample(mMixerBufferFormat);
3102 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3103 }
Andy Hung98ef9782014-03-04 14:46:50 -08003104 free(mEffectBuffer);
3105 mEffectBuffer = NULL;
3106 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003107 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003108 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003109 * audio_bytes_per_sample(mEffectBufferFormat);
3110 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3111 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003112
Eric Laurentb62d0362021-10-26 17:40:18 +02003113 if (mType == SPATIALIZER) {
3114 free(mPostSpatializerBuffer);
3115 mPostSpatializerBuffer = nullptr;
3116 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3117 * audio_bytes_per_sample(mEffectBufferFormat);
3118 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3119 }
3120
Mikhail Naganov55773032020-10-01 15:08:13 -07003121 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3122 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003123 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3124 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003125 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003126
Eric Laurent81784c32012-11-19 14:55:58 -08003127 // force reconfiguration of effect chains and engines to take new buffer size and audio
3128 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003129 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003130 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3131 // matter.
3132 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3133 Vector< sp<EffectChain> > effectChains = mEffectChains;
3134 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003135 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3136 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003137 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003138
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003139 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003140 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003141 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3142 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3143 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3144 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3145 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3146 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3147 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3148 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3149 (int32_t)mHapticChannelMask)
3150 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3151 (int32_t)mHapticChannelCount)
3152 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3153 formatToString(mHALFormat).c_str())
3154 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3155 (int32_t)mFrameCount) // sic - added HAL
3156 ;
3157 uint32_t latencyMs;
3158 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3159 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3160 }
3161 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003162}
3163
Kevin Rocard069c2712018-03-29 19:09:14 -07003164void AudioFlinger::PlaybackThread::updateMetadata_l()
3165{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003166 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003167 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003168 }
3169 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003170 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003171 for (const sp<Track> &track : mActiveTracks) {
3172 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003173 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003174 }
Kevin Rocard12381092018-04-11 09:19:59 -07003175 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003176}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003177
Kevin Rocard12381092018-04-11 09:19:59 -07003178void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3179 const StreamOutHalInterface::SourceMetadata& metadata)
3180{
3181 mOutput->stream->updateSourceMetadata(metadata);
3182};
3183
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003184status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003185{
3186 if (halFrames == NULL || dspFrames == NULL) {
3187 return BAD_VALUE;
3188 }
3189 Mutex::Autolock _l(mLock);
3190 if (initCheck() != NO_ERROR) {
3191 return INVALID_OPERATION;
3192 }
Andy Hung818e7a32016-02-16 18:08:07 -08003193 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003194 *halFrames = framesWritten;
3195
3196 if (isSuspended()) {
3197 // return an estimation of rendered frames when the output is suspended
3198 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003199 *dspFrames = (uint32_t)
3200 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003201 return NO_ERROR;
3202 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003203 status_t status;
3204 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003205 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003206 *dspFrames = (size_t)frames;
3207 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003208 }
3209}
3210
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003211product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003212{
3213 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3214 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3215 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003216 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003217 }
3218 for (size_t i = 0; i < mTracks.size(); i++) {
3219 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003220 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003221 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003222 }
3223 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003224 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003225}
3226
3227
Phil Burk062e67a2015-02-11 13:40:50 -08003228AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003229{
3230 Mutex::Autolock _l(mLock);
3231 return mOutput;
3232}
3233
Phil Burk062e67a2015-02-11 13:40:50 -08003234AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003235{
3236 Mutex::Autolock _l(mLock);
3237 AudioStreamOut *output = mOutput;
3238 mOutput = NULL;
3239 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3240 // must push a NULL and wait for ack
3241 mOutputSink.clear();
3242 mPipeSink.clear();
3243 mNormalSink.clear();
3244 return output;
3245}
3246
3247// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003248sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003249{
3250 if (mOutput == NULL) {
3251 return NULL;
3252 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003253 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003254}
3255
3256uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3257{
3258 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3259}
3260
Andy Hung068e08e2023-05-15 19:02:55 -07003261status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<audioflinger::SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003262{
3263 if (!isValidSyncEvent(event)) {
3264 return BAD_VALUE;
3265 }
3266
3267 Mutex::Autolock _l(mLock);
3268
3269 for (size_t i = 0; i < mTracks.size(); ++i) {
3270 sp<Track> track = mTracks[i];
3271 if (event->triggerSession() == track->sessionId()) {
3272 (void) track->setSyncEvent(event);
3273 return NO_ERROR;
3274 }
3275 }
3276
3277 return NAME_NOT_FOUND;
3278}
3279
Andy Hung068e08e2023-05-15 19:02:55 -07003280bool AudioFlinger::PlaybackThread::isValidSyncEvent(
3281 const sp<audioflinger::SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003282{
3283 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3284}
3285
3286void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
Jing Mike537412f2023-03-12 11:01:47 +08003287 [[maybe_unused]] const Vector< sp<Track> >& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003288{
Andy Hungfe726a62018-09-27 15:17:25 -07003289 // Miscellaneous track cleanup when removed from the active list,
3290 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003291#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003292 for (const auto& track : tracksToRemove) {
3293 if (track->isExternalTrack()) {
3294 // to track the speaker usage
3295 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003296 }
3297 }
Andy Hungfe726a62018-09-27 15:17:25 -07003298#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003299}
3300
3301void AudioFlinger::PlaybackThread::checkSilentMode_l()
3302{
3303 if (!mMasterMute) {
3304 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003305 if (mOutDeviceTypeAddrs.empty()) {
3306 ALOGD("ro.audio.silent is ignored since no output device is set");
3307 return;
3308 }
jiabinc52b1ff2019-10-31 17:20:42 -07003309 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003310 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3311 return;
3312 }
Eric Laurent81784c32012-11-19 14:55:58 -08003313 if (property_get("ro.audio.silent", value, "0") > 0) {
3314 char *endptr;
3315 unsigned long ul = strtoul(value, &endptr, 0);
3316 if (*endptr == '\0' && ul != 0) {
3317 ALOGD("Silence is golden");
3318 // The setprop command will not allow a property to be changed after
3319 // the first time it is set, so we don't have to worry about un-muting.
3320 setMasterMute_l(true);
3321 }
3322 }
3323 }
3324}
3325
3326// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003327ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003328{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003329 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003330 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003331 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003332 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003333
3334 // If an NBAIO sink is present, use it to write the normal mixer's submix
3335 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003336
Andy Hung010a1a12014-03-13 13:57:33 -07003337 const size_t count = mBytesRemaining / mFrameSize;
3338
Simon Wilson2d590962012-11-29 15:18:50 -08003339 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003340 // update the setpoint when AudioFlinger::mScreenState changes
3341 uint32_t screenState = AudioFlinger::mScreenState;
3342 if (screenState != mScreenState) {
3343 mScreenState = screenState;
3344 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3345 if (pipe != NULL) {
3346 pipe->setAvgFrames((mScreenState & 1) ?
3347 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3348 }
3349 }
Andy Hung010a1a12014-03-13 13:57:33 -07003350 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003351 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003352 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003353 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003354#ifdef TEE_SINK
3355 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3356#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003357 } else {
3358 bytesWritten = framesWritten;
3359 }
3360 // otherwise use the HAL / AudioStreamOut directly
3361 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003362 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003363
Eric Laurentbfb1b832013-01-07 09:53:42 -08003364 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003365 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3366 mWriteAckSequence += 2;
3367 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003368 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003369 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003370 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003371 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003372 // FIXME We should have an implementation of timestamps for direct output threads.
3373 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003374 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003375 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003376
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 if (mUseAsyncWrite &&
3378 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3379 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003380 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003381 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003382 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003383 }
Eric Laurent81784c32012-11-19 14:55:58 -08003384 }
3385
Eric Laurent81784c32012-11-19 14:55:58 -08003386 mNumWrites++;
3387 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003388 if (mStandby) {
3389 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003390 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003391 mStandby = false;
3392 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003393 return bytesWritten;
3394}
3395
3396void AudioFlinger::PlaybackThread::threadLoop_drain()
3397{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003398 bool supportsDrain = false;
3399 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003400 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3401 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003402 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3403 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003404 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003405 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003406 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003407 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003408 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409 }
3410}
3411
3412void AudioFlinger::PlaybackThread::threadLoop_exit()
3413{
Eric Laurent275e8e92014-11-30 15:14:47 -08003414 {
3415 Mutex::Autolock _l(mLock);
3416 for (size_t i = 0; i < mTracks.size(); i++) {
3417 sp<Track> track = mTracks[i];
3418 track->invalidate();
3419 }
Andy Hungdae27702016-10-31 14:01:16 -07003420 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3421 // After we exit there are no more track changes sent to BatteryNotifier
3422 // because that requires an active threadLoop.
3423 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3424 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003425 }
Eric Laurent81784c32012-11-19 14:55:58 -08003426}
3427
3428/*
3429The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003430 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003431 - mActiveSleepTimeUs from activeSleepTimeUs()
3432 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003433 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3434 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003435 - maxPeriod from frame count and sample rate (MIXER only)
3436
3437The parameters that affect these derived values are:
3438 - frame count
3439 - frame size
3440 - sample rate
3441 - device type: A2DP or not
3442 - device latency
3443 - format: PCM or not
3444 - active sleep time
3445 - idle sleep time
3446*/
3447
3448void AudioFlinger::PlaybackThread::cacheParameters_l()
3449{
Andy Hung25c2dac2014-02-27 14:56:00 -08003450 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003451 mActiveSleepTimeUs = activeSleepTimeUs();
3452 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003453
3454 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3455 // truncating audio when going to standby.
3456 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003457 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003458 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3459 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3460 }
3461 }
Eric Laurent81784c32012-11-19 14:55:58 -08003462}
3463
Eric Laurent13084622016-05-17 10:51:49 -07003464bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003465{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003466 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003467 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003468 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003469 size_t size = mTracks.size();
3470 for (size_t i = 0; i < size; i++) {
3471 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003472 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003473 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003474 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003475 }
3476 }
Eric Laurent13084622016-05-17 10:51:49 -07003477 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003478}
3479
Haynes Mathew George05317d22016-05-03 16:34:26 -07003480void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3481{
3482 Mutex::Autolock _l(mLock);
3483 invalidateTracks_l(streamType);
3484}
3485
jiabinf042b9b2021-05-07 23:46:28 +00003486// getTrackById_l must be called with holding thread lock
3487AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3488 audio_port_handle_t trackPortId) {
3489 for (size_t i = 0; i < mTracks.size(); i++) {
3490 if (mTracks[i]->portId() == trackPortId) {
3491 return mTracks[i].get();
3492 }
3493 }
3494 return nullptr;
3495}
3496
Eric Laurent81784c32012-11-19 14:55:58 -08003497status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3498{
Glenn Kastend848eb42016-03-08 13:42:11 -08003499 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003500 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003501 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003502
Andy Hungd3639922022-04-28 18:00:49 -07003503 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003504 if (!audio_is_global_session(session)) {
3505 // player sessions on a spatializer output will use a dedicated input buffer and
3506 // will either output multi channel to mEffectBuffer if the track is spatilaized
3507 // or stereo to mPostSpatializerBuffer if not spatialized.
3508 uint32_t channelMask;
3509 bool isSessionSpatialized =
3510 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3511 if (isSessionSpatialized) {
3512 channelMask = mMixerChannelMask;
3513 } else {
3514 channelMask = mChannelMask;
3515 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003516 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003517 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003518 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003519 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003520 &halInBuffer);
3521 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003522
3523 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3524 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3525 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3526 &halOutBuffer);
3527 if (result != OK) return result;
3528
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003529 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003530
Mikhail Naganov022b9952017-01-04 16:36:51 -08003531 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3532 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003533 } else {
3534 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3535 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3536 // mPostSpatializerBuffer as output buffer
3537 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3538 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3539 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3540 if (result != OK) return result;
3541 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3542 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3543 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003544
Eric Laurentb62d0362021-10-26 17:40:18 +02003545 if (session == AUDIO_SESSION_DEVICE) {
3546 halInBuffer = halOutBuffer;
3547 }
3548 }
3549 } else {
3550 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3551 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3552 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3553 &halInBuffer);
3554 if (result != OK) return result;
3555 halOutBuffer = halInBuffer;
3556 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3557 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003558 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003559 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003560 // Only one effect chain can be present in direct output thread and it uses
3561 // the sink buffer as input
3562 if (mType != DIRECT) {
3563 size_t numSamples = mNormalFrameCount
3564 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3565 + mHapticChannelCount);
Andy Hung71ba4b32022-10-06 12:09:49 -07003566 const status_t allocateStatus = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003567 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003568 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003569 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003570
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003571 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003572 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3573 buffer, session);
3574 }
3575 }
3576 }
3577
3578 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003579 // Attach all tracks with same session ID to this chain.
3580 for (size_t i = 0; i < mTracks.size(); ++i) {
3581 sp<Track> track = mTracks[i];
3582 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003583 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3584 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003585 track->setMainBuffer(buffer);
3586 chain->incTrackCnt();
3587 }
3588 }
3589
3590 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003591 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003592 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003593 ALOGV("addEffectChain_l() activating track %p on session %d",
3594 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003595 chain->incActiveTrackCnt();
3596 }
3597 }
3598 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003599
Eric Laurentaaa44472014-09-12 17:41:50 -07003600 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003601 chain->setInBuffer(halInBuffer);
3602 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003603 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3604 // chains list in order to be processed last as it contains output device effects.
3605 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3606 // processing effects specific to an output stream before effects applied to all streams
3607 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003608 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3609 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003610 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003611 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003612 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003613 // Effect chain for other sessions are inserted at beginning of effect
3614 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003615 // sessions is not important.
3616 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003617 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3618 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003619 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003620 size_t size = mEffectChains.size();
3621 size_t i = 0;
3622 for (i = 0; i < size; i++) {
3623 if (mEffectChains[i]->sessionId() < session) {
3624 break;
3625 }
3626 }
3627 mEffectChains.insertAt(chain, i);
3628 checkSuspendOnAddEffectChain_l(chain);
3629
3630 return NO_ERROR;
3631}
3632
3633size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3634{
Glenn Kastend848eb42016-03-08 13:42:11 -08003635 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003636
3637 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3638
3639 for (size_t i = 0; i < mEffectChains.size(); i++) {
3640 if (chain == mEffectChains[i]) {
3641 mEffectChains.removeAt(i);
3642 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003643 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003644 if (session == track->sessionId()) {
3645 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3646 chain.get(), session);
3647 chain->decActiveTrackCnt();
3648 }
3649 }
3650
3651 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003652 for (size_t j = 0; j < mTracks.size(); ++j) {
3653 sp<Track> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003654 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003655 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003656 chain->decTrackCnt();
3657 }
3658 }
3659 break;
3660 }
3661 }
3662 return mEffectChains.size();
3663}
3664
3665status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003666 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003667{
3668 Mutex::Autolock _l(mLock);
3669 return attachAuxEffect_l(track, EffectId);
3670}
3671
3672status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003673 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003674{
3675 status_t status = NO_ERROR;
3676
3677 if (EffectId == 0) {
3678 track->setAuxBuffer(0, NULL);
3679 } else {
3680 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3681 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3682 if (effect != 0) {
3683 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3684 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3685 } else {
3686 status = INVALID_OPERATION;
3687 }
3688 } else {
3689 status = BAD_VALUE;
3690 }
3691 }
3692 return status;
3693}
3694
3695void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3696{
3697 for (size_t i = 0; i < mTracks.size(); ++i) {
3698 sp<Track> track = mTracks[i];
3699 if (track->auxEffectId() == effectId) {
3700 attachAuxEffect_l(track, 0);
3701 }
3702 }
3703}
3704
3705bool AudioFlinger::PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003706NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003707{
Andy Hung4bf583b2023-05-30 18:10:23 -07003708 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003709
Eric Laurent81784c32012-11-19 14:55:58 -08003710 Vector< sp<Track> > tracksToRemove;
3711
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003712 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003713 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003714
3715 // MIXER
3716 nsecs_t lastWarning = 0;
3717
3718 // DUPLICATING
3719 // FIXME could this be made local to while loop?
3720 writeFrames = 0;
3721
3722 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003723 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003724
Andy Hungd3639922022-04-28 18:00:49 -07003725 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003726 sleepTimeShift = 0;
3727 }
3728
3729 CpuStats cpuStats;
3730 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3731
3732 acquireWakeLock();
3733
Glenn Kasteneef598c2017-04-03 14:41:13 -07003734 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3735 // thread associated with this PlaybackThread.
3736 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3737 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003738 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3739 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003740 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003741 const char *logString = NULL;
3742
rago1bb90822017-05-02 18:31:48 -07003743 // Estimated time for next buffer to be written to hal. This is used only on
3744 // suspended mode (for now) to help schedule the wait time until next iteration.
3745 nsecs_t timeLoopNextNs = 0;
3746
Eric Laurent664539d2013-09-23 18:24:31 -07003747 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003748
Andy Hung2dbffc22018-08-08 18:50:41 -07003749 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003750
Eric Laurentb3f315a2021-07-13 15:09:05 +02003751 sendCheckOutputStageEffectsEvent();
3752
Andy Hung446f4df2019-02-21 12:26:41 -08003753 // loopCount is used for statistics and diagnostics.
3754 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003755 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003756 // Log merge requests are performed during AudioFlinger binder transactions, but
3757 // that does not cover audio playback. It's requested here for that reason.
3758 mAudioFlinger->requestLogMerge();
3759
Eric Laurent81784c32012-11-19 14:55:58 -08003760 cpuStats.sample(myName);
3761
3762 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003763 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003764 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003765 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003766
Andy Hung2dbffc22018-08-08 18:50:41 -07003767 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3768 //
jiabinc52b1ff2019-10-31 17:20:42 -07003769 // Note: we access outDeviceTypes() outside of mLock.
3770 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003771 // Here, we try for the AF lock, but do not block on it as the latency
3772 // is more informational.
3773 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3774 std::vector<PatchPanel::SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003775 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003776 status_t status = INVALID_OPERATION;
3777 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3778 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3779 && swPatches.size() > 0) {
3780 status = swPatches[0].getLatencyMs_l(&latencyMs);
3781 downstreamPatchHandle = swPatches[0].getPatchHandle();
3782 }
3783 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003784 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003785 lastDownstreamPatchHandle = downstreamPatchHandle;
3786 }
3787 if (status == OK) {
3788 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003789 // latency of 5 seconds).
3790 const double minLatency = 0., maxLatency = 5000.;
3791 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003792 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003793 } else {
3794 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07003795 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003796 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003797 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003798 }
3799 mAudioFlinger->mLock.unlock();
3800 }
3801 } else {
3802 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3803 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003804 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003805 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3806 }
3807 }
3808
Eric Laurentb3f315a2021-07-13 15:09:05 +02003809 if (mCheckOutputStageEffects.exchange(false)) {
3810 checkOutputStageEffects();
3811 }
3812
Eric Laurent81784c32012-11-19 14:55:58 -08003813 { // scope for mLock
3814
3815 Mutex::Autolock _l(mLock);
3816
Eric Laurent021cf962014-05-13 10:18:14 -07003817 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003818 if (mCheckOutputStageEffects.load()) {
3819 continue;
3820 }
Eric Laurent10351942014-05-08 18:49:52 -07003821
Glenn Kasteneef598c2017-04-03 14:41:13 -07003822 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003823 if (logString != NULL) {
3824 mNBLogWriter->logTimestamp();
3825 mNBLogWriter->log(logString);
3826 logString = NULL;
3827 }
3828
Dean Wheatley12473e92021-03-18 23:00:55 +11003829 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003830
Eric Laurent81784c32012-11-19 14:55:58 -08003831 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003832 if (mSignalPending) {
3833 // A signal was raised while we were unlocked
3834 mSignalPending = false;
3835 } else if (waitingAsyncCallback_l()) {
3836 if (exitPending()) {
3837 break;
3838 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003839 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003840 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003841 releaseWakeLock_l();
3842 released = true;
3843 }
Andy Hung10cbff12017-02-21 17:30:14 -08003844
3845 const int64_t waitNs = computeWaitTimeNs_l();
3846 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3847 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3848 if (status == TIMED_OUT) {
3849 mSignalPending = true; // if timeout recheck everything
3850 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003851 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003852 if (released) {
3853 acquireWakeLock_l();
3854 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003855 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3856 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003857
3858 continue;
3859 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003860 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003861 isSuspended()) {
3862 // put audio hardware into standby after short delay
3863 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003864
3865 threadLoop_standby();
3866
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003867 // This is where we go into standby
3868 if (!mStandby) {
3869 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003870 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003871 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003872 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003873 }
Andy Hungd0979812019-02-21 15:51:44 -08003874 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 }
3876
Eric Tan39ec8d62018-07-24 09:49:29 -07003877 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003878 // we're about to wait, flush the binder command buffer
3879 IPCThreadState::self()->flushCommands();
3880
3881 clearOutputTracks();
3882
3883 if (exitPending()) {
3884 break;
3885 }
3886
3887 releaseWakeLock_l();
3888 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003889 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08003890 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003891 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08003892 acquireWakeLock_l();
3893
3894 mMixerStatus = MIXER_IDLE;
3895 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3896 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003898 checkSilentMode_l();
3899
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003900 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3901 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003902 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003903 sleepTimeShift = 0;
3904 }
3905
3906 continue;
3907 }
3908 }
Eric Laurent81784c32012-11-19 14:55:58 -08003909 // mMixerStatusIgnoringFastTracks is also updated internally
3910 mMixerStatus = prepareTracks_l(&tracksToRemove);
3911
Andy Hungdae27702016-10-31 14:01:16 -07003912 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003913
Kevin Rocard069c2712018-03-29 19:09:14 -07003914 updateMetadata_l();
3915
Eric Laurent81784c32012-11-19 14:55:58 -08003916 // prevent any changes in effect chain list and in each effect chain
3917 // during mixing and effect process as the audio buffers could be deleted
3918 // or modified if an effect is created or deleted
3919 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003920
3921 // Determine which session to pick up haptic data.
3922 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003923 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003924 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003925 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003926 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003927 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003928 if (effectChain != nullptr
3929 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003930 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003931 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003932 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003933 break;
3934 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003935 if (activeHapticSessionId == AUDIO_SESSION_NONE
3936 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003937 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003938 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003939 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003940 }
3941 }
3942 }
3943
Andy Hungc1646382019-04-30 16:12:10 -07003944 // Acquire a local copy of active tracks with lock (release w/o lock).
3945 //
3946 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3947 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3948 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3949 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02003950
3951 setHalLatencyMode_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003952 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003953
Eric Laurentbfb1b832013-01-07 09:53:42 -08003954 if (mBytesRemaining == 0) {
3955 mCurrentWriteLength = 0;
3956 if (mMixerStatus == MIXER_TRACKS_READY) {
3957 // threadLoop_mix() sets mCurrentWriteLength
3958 threadLoop_mix();
3959 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3960 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003961 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003962 // must be written to HAL
3963 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003964 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003965 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003966
3967 // Tally underrun frames as we are inserting 0s here.
3968 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003969 if (track->mFillingUpStatus == Track::FS_ACTIVE
3970 && !track->isStopped()
3971 && !track->isPaused()
3972 && !track->isTerminated()) {
3973 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3974 __func__, track->id(), track->getTrackStateAsString(),
3975 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003976 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3977 }
3978 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003979 }
3980 }
Andy Hung98ef9782014-03-04 14:46:50 -08003981 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003982 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003983 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3984 // or mSinkBuffer (if there are no effects).
3985 //
3986 // This is done pre-effects computation; if effects change to
3987 // support higher precision, this needs to move.
3988 //
3989 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003990 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003991 uint32_t mixerChannelCount = mEffectBufferValid ?
3992 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003993 if (mMixerBufferValid) {
3994 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3995 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3996
David Li88ee0902022-06-22 10:01:21 +08003997 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
3998 // do these processes after effects are applied.
3999 if (!mEffectBufferValid) {
4000 // mono blend occurs for mixer threads only (not direct or offloaded)
4001 // and is handled here if we're going directly to the sink.
4002 if (requireMonoBlend()) {
4003 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4004 mNormalFrameCount, true /*limit*/);
4005 }
Andy Hung2ddee192015-12-18 17:34:44 -08004006
David Li88ee0902022-06-22 10:01:21 +08004007 if (!hasFastMixer()) {
4008 // Balance must take effect after mono conversion.
4009 // We do it here if there is no FastMixer.
4010 // mBalance detects zero balance within the class for speed
4011 // (not needed here).
4012 mBalance.setBalance(mMasterBalance.load());
4013 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4014 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004015 }
4016
Andy Hung98ef9782014-03-04 14:46:50 -08004017 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004018 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004019
4020 // If we're going directly to the sink and there are haptic channels,
4021 // we should adjust channels as the sample data is partially interleaved
4022 // in this case.
4023 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4024 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4025 mChannelCount + mHapticChannelCount,
4026 audio_bytes_per_sample(format),
4027 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4028 }
Andy Hung98ef9782014-03-04 14:46:50 -08004029 }
4030
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 mBytesRemaining = mCurrentWriteLength;
4032 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004033 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4034 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4035 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4036 mBytesWritten += mBytesRemaining;
4037 mFramesWritten += framesRemaining;
4038 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004039 mBytesRemaining = 0;
4040 }
Eric Laurent81784c32012-11-19 14:55:58 -08004041
Eric Laurentbfb1b832013-01-07 09:53:42 -08004042 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004043 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004044 for (size_t i = 0; i < effectChains.size(); i ++) {
4045 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004046 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004047 if (activeHapticSessionId != AUDIO_SESSION_NONE
4048 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004049 // Haptic data is active in this case, copy it directly from
4050 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004051 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4052 audio_channel_count_from_out_mask(mMixerChannelMask) :
4053 mChannelCount;
4054 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4055 hapticSessionChannelCount = mChannelCount;
4056 }
4057
jiabin47affe52019-04-04 18:02:07 -07004058 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004059 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004060 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004061 memcpy_by_audio_format(
4062 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004063 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004064 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004065 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004066 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004067 }
Eric Laurent81784c32012-11-19 14:55:58 -08004068 }
4069 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004070 // Process effect chains for offloaded thread even if no audio
4071 // was read from audio track: process only updates effect state
4072 // and thus does have to be synchronized with audio writes but may have
4073 // to be called while waiting for async write callback
4074 if (mType == OFFLOAD) {
4075 for (size_t i = 0; i < effectChains.size(); i ++) {
4076 effectChains[i]->process_l();
4077 }
4078 }
Eric Laurent81784c32012-11-19 14:55:58 -08004079
Andy Hung98ef9782014-03-04 14:46:50 -08004080 // Only if the Effects buffer is enabled and there is data in the
4081 // Effects buffer (buffer valid), we need to
4082 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004083 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004084 if (mEffectBufferValid) {
4085 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004086 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004087 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004088 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004089 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004090 }
4091
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004092 if (!hasFastMixer()) {
4093 // Balance must take effect after mono conversion.
4094 // We do it here if there is no FastMixer.
4095 // mBalance detects zero balance within the class for speed (not needed here).
4096 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004097 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004098 }
4099
Eric Laurentb62d0362021-10-26 17:40:18 +02004100 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4101 // mPostSpatializerBuffer if the haptics track is spatialized.
4102 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4103 // For other thread types, the haptics channels are already in mEffectBuffer.
4104 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4105 const size_t srcBufferSize = mNormalFrameCount *
4106 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4107 mEffectBufferFormat);
4108 const size_t dstBufferSize = mNormalFrameCount
4109 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4110
4111 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4112 mEffectBufferFormat,
4113 (uint8_t*)mEffectBuffer + srcBufferSize,
4114 mEffectBufferFormat,
4115 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004116 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004117 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4118 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4119 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4120 // Clamp PCM float values more than this distance from 0 to insulate
4121 // a HAL which doesn't handle NaN correctly.
4122 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4123 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4124 static_cast<const float*>(effectBuffer),
4125 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4126 } else {
4127 memcpy_by_audio_format(mSinkBuffer, mFormat,
4128 effectBuffer, mEffectBufferFormat, framesToCopy);
4129 }
jiabin245cdd92018-12-07 17:55:15 -08004130 // The sample data is partially interleaved when haptic channels exist,
4131 // we need to adjust channels here.
4132 if (mHapticChannelCount > 0) {
4133 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4134 mChannelCount + mHapticChannelCount,
4135 audio_bytes_per_sample(mFormat),
4136 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4137 }
Andy Hung98ef9782014-03-04 14:46:50 -08004138 }
4139
Eric Laurent81784c32012-11-19 14:55:58 -08004140 // enable changes in effect chain
4141 unlockEffectChains(effectChains);
4142
Eric Laurentbfb1b832013-01-07 09:53:42 -08004143 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004144 // mSleepTimeUs == 0 means we must write to audio hardware
4145 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004146 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004147 // writePeriodNs is updated >= 0 when ret > 0.
4148 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004149 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004150 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004151 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004152 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004153 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004154 if (ret < 0) {
4155 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004156 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004157 mBytesWritten += ret;
4158 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004159 const int64_t frames = ret / mFrameSize;
4160 mFramesWritten += frames;
4161
4162 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4163 // process information relating to write time.
4164 if (audio_has_proportional_frames(mFormat)) {
4165 // we are in a continuous mixing cycle
4166 if (mMixerStatus == MIXER_TRACKS_READY &&
4167 loopCount == lastLoopCountWritten + 1) {
4168
4169 const double jitterMs =
4170 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4171 {frames, writePeriodNs},
4172 {0, 0} /* lastTimestamp */, mSampleRate);
4173 const double processMs =
4174 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4175
4176 Mutex::Autolock _l(mLock);
4177 mIoJitterMs.add(jitterMs);
4178 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004179
4180 if (mPipeSink.get() != nullptr) {
4181 // Using the Monopipe availableToWrite, we estimate the current
4182 // buffer size.
4183 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4184 const ssize_t
4185 availableToWrite = mPipeSink->availableToWrite();
4186 const size_t pipeFrames = monoPipe->maxFrames();
4187 const size_t
4188 remainingFrames = pipeFrames - max(availableToWrite, 0);
4189 mMonopipePipeDepthStats.add(remainingFrames);
4190 }
Andy Hung446f4df2019-02-21 12:26:41 -08004191 }
4192
4193 // write blocked detection
4194 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004195 if ((mType == MIXER || mType == SPATIALIZER)
4196 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004197 mNumDelayedWrites++;
4198 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4199 ATRACE_NAME("underrun");
4200 ALOGW("write blocked for %lld msecs, "
4201 "%d delayed writes, thread %d",
4202 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4203 mNumDelayedWrites, mId);
4204 lastWarning = lastIoEndNs;
4205 }
4206 }
4207 }
4208 // update timing info.
4209 mLastIoBeginNs = lastIoBeginNs;
4210 mLastIoEndNs = lastIoEndNs;
4211 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004212 }
4213 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4214 (mMixerStatus == MIXER_DRAIN_ALL)) {
4215 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004216 }
Andy Hungd3639922022-04-28 18:00:49 -07004217 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004218
4219 if (mThreadThrottle
4220 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004221 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004222 // Limit MixerThread data processing to no more than twice the
4223 // expected processing rate.
4224 //
4225 // This helps prevent underruns with NuPlayer and other applications
4226 // which may set up buffers that are close to the minimum size, or use
4227 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4228 //
4229 // The throttle smooths out sudden large data drains from the device,
4230 // e.g. when it comes out of standby, which often causes problems with
4231 // (1) mixer threads without a fast mixer (which has its own warm-up)
4232 // (2) minimum buffer sized tracks (even if the track is full,
4233 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004234 //
4235 // Total time spent in last processing cycle equals time spent in
4236 // 1. threadLoop_write, as well as time spent in
4237 // 2. threadLoop_mix (significant for heavy mixing, especially
4238 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004239
Andy Hung446f4df2019-02-21 12:26:41 -08004240 // it's OK if deltaMs is an overestimate.
4241
4242 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004243
Ivan Lozanoea04d392017-11-07 14:37:07 -08004244 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004245 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004246 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004247
Andy Hung08fb1742015-05-31 23:22:10 -07004248 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004249 // notify of throttle start on verbose log
4250 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4251 "mixer(%p) throttle begin:"
4252 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004253 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004254 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004255 // Throttle must be attributed to the previous mixer loop's write time
4256 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004257 // This also ensures proper timing statistics.
4258 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004259 } else {
4260 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4261 if (diff > 0) {
4262 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004263 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004264 ALOGD_IF(!isSingleDeviceType(
4265 outDeviceTypes(), audio_is_a2dp_out_device) &&
4266 !isSingleDeviceType(
4267 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004268 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004269 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4270 }
Andy Hung08fb1742015-05-31 23:22:10 -07004271 }
4272 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 }
Eric Laurent81784c32012-11-19 14:55:58 -08004274
Eric Laurentbfb1b832013-01-07 09:53:42 -08004275 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004276 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004277 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004278 // suspended requires accurate metering of sleep time.
4279 if (isSuspended()) {
4280 // advance by expected sleepTime
4281 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4282 const nsecs_t nowNs = systemTime();
4283
4284 // compute expected next time vs current time.
4285 // (negative deltas are treated as delays).
4286 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4287 if (deltaNs < -kMaxNextBufferDelayNs) {
4288 // Delays longer than the max allowed trigger a reset.
4289 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4290 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4291 timeLoopNextNs = nowNs + deltaNs;
4292 } else if (deltaNs < 0) {
4293 // Delays within the max delay allowed: zero the delta/sleepTime
4294 // to help the system catch up in the next iteration(s)
4295 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4296 deltaNs = 0;
4297 }
4298 // update sleep time (which is >= 0)
4299 mSleepTimeUs = deltaNs / 1000;
4300 }
Eric Laurente93cc032016-05-05 10:15:10 -07004301 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4302 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004303 }
Glenn Kastene7754022014-10-31 12:11:26 -07004304 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004305 }
Eric Laurent81784c32012-11-19 14:55:58 -08004306 }
4307
4308 // Finally let go of removed track(s), without the lock held
4309 // since we can't guarantee the destructors won't acquire that
4310 // same lock. This will also mutate and push a new fast mixer state.
4311 threadLoop_removeTracks(tracksToRemove);
4312 tracksToRemove.clear();
4313
4314 // FIXME I don't understand the need for this here;
4315 // it was in the original code but maybe the
4316 // assignment in saveOutputTracks() makes this unnecessary?
4317 clearOutputTracks();
4318
4319 // Effect chains will be actually deleted here if they were removed from
4320 // mEffectChains list during mixing or effects processing
4321 effectChains.clear();
4322
4323 // FIXME Note that the above .clear() is no longer necessary since effectChains
4324 // is now local to this block, but will keep it for now (at least until merge done).
4325 }
4326
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327 threadLoop_exit();
4328
Eric Laurentcf817a22014-08-04 20:36:31 -07004329 if (!mStandby) {
4330 threadLoop_standby();
4331 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004332 }
4333
4334 releaseWakeLock();
4335
4336 ALOGV("Thread %p type %d exiting", this, mType);
4337 return false;
4338}
4339
Dean Wheatley12473e92021-03-18 23:00:55 +11004340void AudioFlinger::PlaybackThread::collectTimestamps_l()
4341{
Dean Wheatley12473e92021-03-18 23:00:55 +11004342 if (mStandby) {
4343 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4344 return;
4345 } else if (mHwPaused) {
4346 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4347 return;
4348 }
4349
4350 // Gather the framesReleased counters for all active tracks,
4351 // and associate with the sink frames written out. We need
4352 // this to convert the sink timestamp to the track timestamp.
4353 bool kernelLocationUpdate = false;
4354 ExtendedTimestamp timestamp; // use private copy to fetch
4355
4356 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4357 // HAL may be draining some small duration buffered data for fade out.
4358 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4359 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4360 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4361 mSampleRate);
4362
4363 if (isTimestampCorrectionEnabled()) {
4364 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4365 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4366 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4367 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4368 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4369 = correctedTimestamp.mFrames;
4370 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4371 = correctedTimestamp.mTimeNs;
4372 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4373 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4374 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4375
4376 // Note: Downstream latency only added if timestamp correction enabled.
4377 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4378 const int64_t newPosition =
4379 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4380 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4381 // prevent retrograde
4382 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4383 newPosition,
4384 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4385 - mSuspendedFrames));
4386 }
4387 }
4388
4389 // We always fetch the timestamp here because often the downstream
4390 // sink will block while writing.
4391
4392 // We keep track of the last valid kernel position in case we are in underrun
4393 // and the normal mixer period is the same as the fast mixer period, or there
4394 // is some error from the HAL.
4395 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4396 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4397 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4398 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4399 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4400
4401 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4402 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4403 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4404 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4405 }
4406
4407 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4408 kernelLocationUpdate = true;
4409 } else {
4410 ALOGVV("getTimestamp error - no valid kernel position");
4411 }
4412
4413 // copy over kernel info
4414 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4415 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4416 + mSuspendedFrames; // add frames discarded when suspended
4417 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4418 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4419 } else {
4420 mTimestampVerifier.error();
4421 }
4422
4423 // mFramesWritten for non-offloaded tracks are contiguous
4424 // even after standby() is called. This is useful for the track frame
4425 // to sink frame mapping.
4426 bool serverLocationUpdate = false;
4427 if (mFramesWritten != mLastFramesWritten) {
4428 serverLocationUpdate = true;
4429 mLastFramesWritten = mFramesWritten;
4430 }
4431 // Only update timestamps if there is a meaningful change.
4432 // Either the kernel timestamp must be valid or we have written something.
4433 if (kernelLocationUpdate || serverLocationUpdate) {
4434 if (serverLocationUpdate) {
4435 // use the time before we called the HAL write - it is a bit more accurate
4436 // to when the server last read data than the current time here.
4437 //
4438 // If we haven't written anything, mLastIoBeginNs will be -1
4439 // and we use systemTime().
4440 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4441 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4442 ? systemTime() : mLastIoBeginNs;
4443 }
4444
4445 for (const sp<Track> &t : mActiveTracks) {
4446 if (!t->isFastTrack()) {
4447 t->updateTrackFrameInfo(
4448 t->mAudioTrackServerProxy->framesReleased(),
4449 mFramesWritten,
4450 mSampleRate,
4451 mTimestamp);
4452 }
4453 }
4454 }
4455
4456 if (audio_has_proportional_frames(mFormat)) {
4457 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4458 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4459 mLatencyMs.add(latencyMs);
4460 }
4461 }
4462#if 0
4463 // logFormat example
4464 if (z % 100 == 0) {
4465 timespec ts;
4466 clock_gettime(CLOCK_MONOTONIC, &ts);
4467 LOGT("This is an integer %d, this is a float %f, this is my "
4468 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4469 LOGT("A deceptive null-terminated string %\0");
4470 }
4471 ++z;
4472#endif
4473}
4474
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475// removeTracks_l() must be called with ThreadBase::mLock held
4476void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004477NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004478{
Andy Hungfe726a62018-09-27 15:17:25 -07004479 for (const auto& track : tracksToRemove) {
4480 mActiveTracks.remove(track);
4481 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4482 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4483 if (chain != 0) {
4484 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4485 __func__, track->id(), chain.get(), track->sessionId());
4486 chain->decActiveTrackCnt();
4487 }
4488 // If an external client track, inform APM we're no longer active, and remove if needed.
4489 // We do this under lock so that the state is consistent if the Track is destroyed.
4490 if (track->isExternalTrack()) {
4491 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004492 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004493 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 }
4495 }
Andy Hungfe726a62018-09-27 15:17:25 -07004496 if (track->isTerminated()) {
4497 // remove from our tracks vector
4498 removeTrack_l(track);
4499 }
jiabineb3bda02020-06-30 14:07:03 -07004500 if (mHapticChannelCount > 0 &&
4501 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4502 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004503 mLock.unlock();
4504 // Unlock due to VibratorService will lock for this call and will
4505 // call Tracks.mute/unmute which also require thread's lock.
4506 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4507 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004508
4509 // When the track is stop, set the haptic intensity as MUTE
4510 // for the HapticGenerator effect.
4511 if (chain != nullptr) {
4512 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4513 }
jiabin245cdd92018-12-07 17:55:15 -08004514 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004515 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516}
Eric Laurent81784c32012-11-19 14:55:58 -08004517
Eric Laurentaccc1472013-09-20 09:36:34 -07004518status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4519{
4520 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004521 ExtendedTimestamp ets;
4522 status_t status = mNormalSink->getTimestamp(ets);
4523 if (status == NO_ERROR) {
4524 status = ets.getBestTimestamp(&timestamp);
4525 }
4526 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004527 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004528 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004529 collectTimestamps_l();
4530 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4531 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004532 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004533 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4534 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4535 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4536 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4537 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004538 }
4539 return INVALID_OPERATION;
4540}
Eric Laurent1c333e22014-05-20 10:48:17 -07004541
Eric Laurenteab90452019-06-24 15:17:46 -07004542// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4543// still applied by the mixer.
4544// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4545// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4546// if more than one track are active
4547status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4548{
4549 status_t result = NO_ERROR;
4550 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4551 if (*volume != mLeftVolFloat) {
4552 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004553 // HAL can return INVALID_OPERATION if operation is not supported.
4554 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004555 "Error when setting output stream volume: %d", result);
4556 if (result == NO_ERROR) {
4557 mLeftVolFloat = *volume;
4558 }
4559 }
4560 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4561 // remove stream volume contribution from software volume.
4562 if (mLeftVolFloat == *volume) {
4563 *volume = 1.0f;
4564 }
4565 }
4566 return result;
4567}
4568
Eric Laurent054d9d32015-04-24 08:48:48 -07004569status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4570 audio_patch_handle_t *handle)
4571{
Andy Hungf60abce2016-08-26 11:37:54 -07004572 status_t status;
4573 if (property_get_bool("af.patch_park", false /* default_value */)) {
4574 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4575 // or if HAL does not properly lock against access.
4576 AutoPark<FastMixer> park(mFastMixer);
4577 status = PlaybackThread::createAudioPatch_l(patch, handle);
4578 } else {
4579 status = PlaybackThread::createAudioPatch_l(patch, handle);
4580 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004581 return status;
4582}
4583
Eric Laurent1c333e22014-05-20 10:48:17 -07004584status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4585 audio_patch_handle_t *handle)
4586{
4587 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004588
4589 // store new device and send to effects
4590 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004591 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004592 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004593 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4594 && !mOutput->audioHwDev->supportsAudioPatches(),
4595 "Enumerated device type(%#x) must not be used "
4596 "as it does not support audio patches",
4597 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004598 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004599 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4600 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004601 }
4602
François Gaffie0c280aa2018-07-25 10:02:15 +02004603 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004604#ifdef ADD_BATTERY_DATA
4605 // when changing the audio output device, call addBatteryData to notify
4606 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004607 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004608 uint32_t params = 0;
4609 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004610 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004611 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004612 }
4613
Eric Laurent054d9d32015-04-24 08:48:48 -07004614 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004615 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004616 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4617 }
4618
4619 if (params != 0) {
4620 addBatteryData(params);
4621 }
4622 }
4623#endif
4624
4625 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004626 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004627 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004628
jiabinc52b1ff2019-10-31 17:20:42 -07004629 // mPatch.num_sinks is not set when the thread is created so that
4630 // the first patch creation triggers an ioConfigChanged callback
4631 bool configChanged = (mPatch.num_sinks == 0) ||
4632 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004633 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004634 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004635 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004636
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004637 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004638 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4639 status = hwDevice->createAudioPatch(patch->num_sources,
4640 patch->sources,
4641 patch->num_sinks,
4642 patch->sinks,
4643 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004644 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004645 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004646 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004647 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004648 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004649
4650 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004651 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004652 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004653 // also dispatch to active AudioTracks for MediaMetrics
4654 for (const auto &track : mActiveTracks) {
4655 track->logEndInterval();
4656 track->logBeginInterval(patchSinksAsString);
4657 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004658
Eric Laurente8726fe2015-06-26 09:39:24 -07004659 if (configChanged) {
4660 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4661 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004662 return status;
4663}
4664
Eric Laurent054d9d32015-04-24 08:48:48 -07004665status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4666{
Andy Hungf60abce2016-08-26 11:37:54 -07004667 status_t status;
4668 if (property_get_bool("af.patch_park", false /* default_value */)) {
4669 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4670 // or if HAL does not properly lock against access.
4671 AutoPark<FastMixer> park(mFastMixer);
4672 status = PlaybackThread::releaseAudioPatch_l(handle);
4673 } else {
4674 status = PlaybackThread::releaseAudioPatch_l(handle);
4675 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004676 return status;
4677}
4678
Eric Laurent1c333e22014-05-20 10:48:17 -07004679status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4680{
4681 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004682
jiabinc52b1ff2019-10-31 17:20:42 -07004683 mPatch = audio_patch{};
4684 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004685
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004686 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004687 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4688 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004689 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004690 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004691 }
4692 return status;
4693}
4694
Eric Laurent83b88082014-06-20 18:31:16 -07004695void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4696{
4697 Mutex::Autolock _l(mLock);
4698 mTracks.add(track);
4699}
4700
4701void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4702{
4703 Mutex::Autolock _l(mLock);
4704 destroyTrack_l(track);
4705}
4706
Mikhail Naganovdc769682018-05-04 15:34:08 -07004707void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004708{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004709 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004710 config->role = AUDIO_PORT_ROLE_SOURCE;
4711 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4712 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004713 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4714 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4715 config->flags.output = mOutput->flags;
4716 }
Eric Laurent83b88082014-06-20 18:31:16 -07004717}
4718
Eric Laurent81784c32012-11-19 14:55:58 -08004719// ----------------------------------------------------------------------------
4720
4721AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004722 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4723 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004724 // mAudioMixer below
4725 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004726 mFastMixerFutex(0),
4727 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004728 // mOutputSink below
4729 // mPipeSink below
4730 // mNormalSink below
4731{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004732 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004733 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004734 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004735 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004736 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4737 mNormalFrameCount);
4738 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4739
Andy Hungfbfc3952015-01-15 13:33:51 -08004740 if (type == DUPLICATING) {
4741 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4742 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4743 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4744 return;
4745 }
Eric Laurent81784c32012-11-19 14:55:58 -08004746 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004747 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004748 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004749 const NBAIO_Format offers[1] = {Format_from_SR_C(
4750 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004751#if !LOG_NDEBUG
4752 ssize_t index =
4753#else
4754 (void)
4755#endif
4756 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004757 ALOG_ASSERT(index == 0);
4758
4759 // initialize fast mixer depending on configuration
4760 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004761 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004762 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004763 } else {
4764 switch (kUseFastMixer) {
4765 case FastMixer_Never:
4766 initFastMixer = false;
4767 break;
4768 case FastMixer_Always:
4769 initFastMixer = true;
4770 break;
4771 case FastMixer_Static:
4772 case FastMixer_Dynamic:
4773 initFastMixer = mFrameCount < mNormalFrameCount;
4774 break;
4775 }
4776 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4777 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4778 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004779 }
4780 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004781 audio_format_t fastMixerFormat;
4782 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4783 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4784 } else {
4785 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4786 }
4787 if (mFormat != fastMixerFormat) {
4788 // change our Sink format to accept our intermediate precision
4789 mFormat = fastMixerFormat;
4790 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004791 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004792 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4793 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4794 }
Eric Laurent81784c32012-11-19 14:55:58 -08004795
4796 // create a MonoPipe to connect our submix to FastMixer
4797 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004798
Andy Hung1258c1a2014-05-23 21:22:17 -07004799 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004800 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004801 format.mFormat = fastMixerFormat;
4802 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4803
Eric Laurent81784c32012-11-19 14:55:58 -08004804 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4805 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4806 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4807 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07004808 const NBAIO_Format offersFast[1] = {format};
4809 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004810#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004811 ssize_t index =
4812#else
4813 (void)
4814#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07004815 monoPipe->negotiate(offersFast, std::size(offersFast),
4816 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004817 ALOG_ASSERT(index == 0);
4818 monoPipe->setAvgFrames((mScreenState & 1) ?
4819 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4820 mPipeSink = monoPipe;
4821
Eric Laurent81784c32012-11-19 14:55:58 -08004822 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004823 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004824 FastMixerStateQueue *sq = mFastMixer->sq();
4825#ifdef STATE_QUEUE_DUMP
4826 sq->setObserverDump(&mStateQueueObserverDump);
4827 sq->setMutatorDump(&mStateQueueMutatorDump);
4828#endif
4829 FastMixerState *state = sq->begin();
4830 FastTrack *fastTrack = &state->mFastTracks[0];
4831 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4832 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4833 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004834 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4835 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4836 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004837 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004838 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004839 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004840 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004841 fastTrack->mGeneration++;
4842 state->mFastTracksGen++;
4843 state->mTrackMask = 1;
4844 // fast mixer will use the HAL output sink
4845 state->mOutputSink = mOutputSink.get();
4846 state->mOutputSinkGen++;
4847 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004848 // specify sink channel mask when haptic channel mask present as it can not
4849 // be calculated directly from channel count
4850 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004851 ? AUDIO_CHANNEL_NONE
4852 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004853 state->mCommand = FastMixerState::COLD_IDLE;
4854 // already done in constructor initialization list
4855 //mFastMixerFutex = 0;
4856 state->mColdFutexAddr = &mFastMixerFutex;
4857 state->mColdGen++;
4858 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004859 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4860 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004861 sq->end();
4862 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4863
Eric Tan0513b5d2018-09-17 10:32:48 -07004864 NBLog::thread_info_t info;
4865 info.id = mId;
4866 info.type = NBLog::FASTMIXER;
4867 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4868
Eric Laurent81784c32012-11-19 14:55:58 -08004869 // start the fast mixer
4870 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4871 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004872 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004873 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004874
4875#ifdef AUDIO_WATCHDOG
4876 // create and start the watchdog
4877 mAudioWatchdog = new AudioWatchdog();
4878 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4879 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4880 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004881 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004882#endif
Andy Hung8946a282018-04-19 20:04:56 -07004883 } else {
4884#ifdef TEE_SINK
4885 // Only use the MixerThread tee if there is no FastMixer.
4886 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4887 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4888#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004889 }
4890
4891 switch (kUseFastMixer) {
4892 case FastMixer_Never:
4893 case FastMixer_Dynamic:
4894 mNormalSink = mOutputSink;
4895 break;
4896 case FastMixer_Always:
4897 mNormalSink = mPipeSink;
4898 break;
4899 case FastMixer_Static:
4900 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4901 break;
4902 }
4903}
4904
4905AudioFlinger::MixerThread::~MixerThread()
4906{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004907 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004908 FastMixerStateQueue *sq = mFastMixer->sq();
4909 FastMixerState *state = sq->begin();
4910 if (state->mCommand == FastMixerState::COLD_IDLE) {
4911 int32_t old = android_atomic_inc(&mFastMixerFutex);
4912 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004913 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004914 }
4915 }
4916 state->mCommand = FastMixerState::EXIT;
4917 sq->end();
4918 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4919 mFastMixer->join();
4920 // Though the fast mixer thread has exited, it's state queue is still valid.
4921 // We'll use that extract the final state which contains one remaining fast track
4922 // corresponding to our sub-mix.
4923 state = sq->begin();
4924 ALOG_ASSERT(state->mTrackMask == 1);
4925 FastTrack *fastTrack = &state->mFastTracks[0];
4926 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4927 delete fastTrack->mBufferProvider;
4928 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004929 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004930#ifdef AUDIO_WATCHDOG
4931 if (mAudioWatchdog != 0) {
4932 mAudioWatchdog->requestExit();
4933 mAudioWatchdog->requestExitAndWait();
4934 mAudioWatchdog.clear();
4935 }
4936#endif
4937 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004938 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004939 delete mAudioMixer;
4940}
4941
4942
4943uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4944{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004945 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004946 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4947 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4948 }
4949 return latency;
4950}
4951
Eric Laurentbfb1b832013-01-07 09:53:42 -08004952ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004953{
4954 // FIXME we should only do one push per cycle; confirm this is true
4955 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004956 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004957 FastMixerStateQueue *sq = mFastMixer->sq();
4958 FastMixerState *state = sq->begin();
4959 if (state->mCommand != FastMixerState::MIX_WRITE &&
4960 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4961 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004962
4963 // FIXME workaround for first HAL write being CPU bound on some devices
4964 ATRACE_BEGIN("write");
4965 mOutput->write((char *)mSinkBuffer, 0);
4966 ATRACE_END();
4967
Eric Laurent81784c32012-11-19 14:55:58 -08004968 int32_t old = android_atomic_inc(&mFastMixerFutex);
4969 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004970 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004971 }
4972#ifdef AUDIO_WATCHDOG
4973 if (mAudioWatchdog != 0) {
4974 mAudioWatchdog->resume();
4975 }
4976#endif
4977 }
4978 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004979#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004980 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004981 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004982#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004983 sq->end();
4984 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4985 if (kUseFastMixer == FastMixer_Dynamic) {
4986 mNormalSink = mPipeSink;
4987 }
4988 } else {
4989 sq->end(false /*didModify*/);
4990 }
4991 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004992 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004993}
4994
4995void AudioFlinger::MixerThread::threadLoop_standby()
4996{
4997 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004998 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004999 FastMixerStateQueue *sq = mFastMixer->sq();
5000 FastMixerState *state = sq->begin();
5001 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005002 // Report any frames trapped in the Monopipe
5003 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5004 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5005 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5006 "monoPipeWritten:%lld monoPipeLeft:%lld",
5007 (long long)mFramesWritten, (long long)mSuspendedFrames,
5008 (long long)mPipeSink->framesWritten(), pipeFrames);
5009 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5010
Eric Laurent81784c32012-11-19 14:55:58 -08005011 state->mCommand = FastMixerState::COLD_IDLE;
5012 state->mColdFutexAddr = &mFastMixerFutex;
5013 state->mColdGen++;
5014 mFastMixerFutex = 0;
5015 sq->end();
5016 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5017 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5018 if (kUseFastMixer == FastMixer_Dynamic) {
5019 mNormalSink = mOutputSink;
5020 }
5021#ifdef AUDIO_WATCHDOG
5022 if (mAudioWatchdog != 0) {
5023 mAudioWatchdog->pause();
5024 }
5025#endif
5026 } else {
5027 sq->end(false /*didModify*/);
5028 }
5029 }
5030 PlaybackThread::threadLoop_standby();
5031}
5032
Eric Laurentbfb1b832013-01-07 09:53:42 -08005033bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5034{
5035 return false;
5036}
5037
5038bool AudioFlinger::PlaybackThread::shouldStandby_l()
5039{
5040 return !mStandby;
5041}
5042
5043bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5044{
5045 Mutex::Autolock _l(mLock);
5046 return waitingAsyncCallback_l();
5047}
5048
Eric Laurent81784c32012-11-19 14:55:58 -08005049// shared by MIXER and DIRECT, overridden by DUPLICATING
5050void AudioFlinger::PlaybackThread::threadLoop_standby()
5051{
5052 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005053 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005054 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005055 // discard any pending drain or write ack by incrementing sequence
5056 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5057 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005058 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005059 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5060 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005061 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005063 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005064}
5065
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005066void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5067{
5068 ALOGV("signal playback thread");
5069 broadcast_l();
5070}
5071
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005072void AudioFlinger::PlaybackThread::onAsyncError()
5073{
5074 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5075 invalidateTracks((audio_stream_type_t)i);
5076 }
5077}
5078
Eric Laurent81784c32012-11-19 14:55:58 -08005079void AudioFlinger::MixerThread::threadLoop_mix()
5080{
Eric Laurent81784c32012-11-19 14:55:58 -08005081 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005082 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005083 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005084 // increase sleep time progressively when application underrun condition clears.
5085 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5086 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5087 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005088 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005089 sleepTimeShift--;
5090 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005091 mSleepTimeUs = 0;
5092 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005093 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005094
Eric Laurent81784c32012-11-19 14:55:58 -08005095}
5096
5097void AudioFlinger::MixerThread::threadLoop_sleepTime()
5098{
5099 // If no tracks are ready, sleep once for the duration of an output
5100 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005101 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005102 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005103 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5104 // Using the Monopipe availableToWrite, we estimate the
5105 // sleep time to retry for more data (before we underrun).
5106 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5107 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5108 const size_t pipeFrames = monoPipe->maxFrames();
5109 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5110 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5111 const size_t framesDelay = std::min(
5112 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5113 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5114 pipeFrames, framesLeft, framesDelay);
5115 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5116 } else {
5117 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5118 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5119 mSleepTimeUs = kMinThreadSleepTimeUs;
5120 }
5121 // reduce sleep time in case of consecutive application underruns to avoid
5122 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5123 // duration we would end up writing less data than needed by the audio HAL if
5124 // the condition persists.
5125 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5126 sleepTimeShift++;
5127 }
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
5129 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005130 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005131 }
5132 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005133 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5134 // before effects processing or output.
5135 if (mMixerBufferValid) {
5136 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005137 if (mType == SPATIALIZER) {
5138 memset(mSinkBuffer, 0, mSinkBufferSize);
5139 }
Andy Hung98ef9782014-03-04 14:46:50 -08005140 } else {
5141 memset(mSinkBuffer, 0, mSinkBufferSize);
5142 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005143 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005144 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5145 "anticipated start");
5146 }
5147 // TODO add standby time extension fct of effect tail
5148}
5149
5150// prepareTracks_l() must be called with ThreadBase::mLock held
5151AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5152 Vector< sp<Track> > *tracksToRemove)
5153{
Andy Hungc0691382018-09-12 18:01:57 -07005154 // clean up deleted track ids in AudioMixer before allocating new tracks
5155 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5156 // for each trackId, destroy it in the AudioMixer
5157 if (mAudioMixer->exists(trackId)) {
5158 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005159 }
5160 });
Andy Hungc0691382018-09-12 18:01:57 -07005161 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005162
5163 mixer_state mixerStatus = MIXER_IDLE;
5164 // find out which tracks need to be processed
5165 size_t count = mActiveTracks.size();
5166 size_t mixedTracks = 0;
5167 size_t tracksWithEffect = 0;
5168 // counts only _active_ fast tracks
5169 size_t fastTracks = 0;
5170 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5171
5172 float masterVolume = mMasterVolume;
5173 bool masterMute = mMasterMute;
5174
5175 if (masterMute) {
5176 masterVolume = 0;
5177 }
5178 // Delegate master volume control to effect in output mix effect chain if needed
5179 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5180 if (chain != 0) {
5181 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5182 chain->setVolume_l(&v, &v);
5183 masterVolume = (float)((v + (1 << 23)) >> 24);
5184 chain.clear();
5185 }
5186
5187 // prepare a new state to push
5188 FastMixerStateQueue *sq = NULL;
5189 FastMixerState *state = NULL;
5190 bool didModify = false;
5191 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005192 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005193 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005194 sq = mFastMixer->sq();
5195 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005196 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005197 }
5198
Andy Hung69aed5f2014-02-25 17:24:40 -08005199 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005200 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005201
Andy Hungbd3b2b02018-05-21 10:53:11 -07005202 // DeferredOperations handles statistics after setting mixerStatus.
5203 class DeferredOperations {
5204 public:
Andy Hungea840382020-05-05 21:50:17 -07005205 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5206 : mMixerStatus(mixerStatus)
5207 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005208
5209 // when leaving scope, tally frames properly.
5210 ~DeferredOperations() {
5211 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5212 // because that is when the underrun occurs.
5213 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005214 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005215 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005216 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005217 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005218 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005219 }
5220 }
Andy Hungea840382020-05-05 21:50:17 -07005221 // send the max underrun frames for this mixer period
5222 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005223 }
5224
5225 // tallyUnderrunFrames() is called to update the track counters
5226 // with the number of underrun frames for a particular mixer period.
5227 // We defer tallying until we know the final mixer status.
Andy Hung71ba4b32022-10-06 12:09:49 -07005228 void tallyUnderrunFrames(const sp<Track>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005229 mUnderrunFrames.emplace_back(track, underrunFrames);
5230 }
5231
5232 private:
5233 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005234 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005235 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005236 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005237 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005238
jiabin245cdd92018-12-07 17:55:15 -08005239 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005240 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005241 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005242
5243 // this const just means the local variable doesn't change
5244 Track* const track = t.get();
5245
5246 // process fast tracks
5247 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005248 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5249 "%s(%d): FastTrack(%d) present without FastMixer",
5250 __func__, id(), track->id());
5251
jiabin245cdd92018-12-07 17:55:15 -08005252 if (track->getHapticPlaybackEnabled()) {
5253 noFastHapticTrack = false;
5254 }
Eric Laurent81784c32012-11-19 14:55:58 -08005255
5256 // It's theoretically possible (though unlikely) for a fast track to be created
5257 // and then removed within the same normal mix cycle. This is not a problem, as
5258 // the track never becomes active so it's fast mixer slot is never touched.
5259 // The converse, of removing an (active) track and then creating a new track
5260 // at the identical fast mixer slot within the same normal mix cycle,
5261 // is impossible because the slot isn't marked available until the end of each cycle.
5262 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005263 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005264 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5265 FastTrack *fastTrack = &state->mFastTracks[j];
5266
5267 // Determine whether the track is currently in underrun condition,
5268 // and whether it had a recent underrun.
5269 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5270 FastTrackUnderruns underruns = ftDump->mUnderruns;
5271 uint32_t recentFull = (underruns.mBitFields.mFull -
5272 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5273 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5274 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5275 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5276 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5277 uint32_t recentUnderruns = recentPartial + recentEmpty;
5278 track->mObservedUnderruns = underruns;
5279 // don't count underruns that occur while stopping or pausing
5280 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005281 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005282 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5283 recentUnderruns > 0) {
5284 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005285 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005286 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005287 // Immediately account for FastTrack underruns.
5288 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005289
5290 // This is similar to the state machine for normal tracks,
5291 // with a few modifications for fast tracks.
5292 bool isActive = true;
5293 switch (track->mState) {
5294 case TrackBase::STOPPING_1:
5295 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005296 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005297 track->mState = TrackBase::STOPPING_2;
5298 }
5299 break;
5300 case TrackBase::PAUSING:
5301 // ramp down is not yet implemented
5302 track->setPaused();
5303 break;
5304 case TrackBase::RESUMING:
5305 // ramp up is not yet implemented
5306 track->mState = TrackBase::ACTIVE;
5307 break;
5308 case TrackBase::ACTIVE:
5309 if (recentFull > 0 || recentPartial > 0) {
5310 // track has provided at least some frames recently: reset retry count
5311 track->mRetryCount = kMaxTrackRetries;
5312 }
5313 if (recentUnderruns == 0) {
5314 // no recent underruns: stay active
5315 break;
5316 }
5317 // there has recently been an underrun of some kind
5318 if (track->sharedBuffer() == 0) {
5319 // were any of the recent underruns "empty" (no frames available)?
5320 if (recentEmpty == 0) {
5321 // no, then ignore the partial underruns as they are allowed indefinitely
5322 break;
5323 }
5324 // there has recently been an "empty" underrun: decrement the retry counter
5325 if (--(track->mRetryCount) > 0) {
5326 break;
5327 }
5328 // indicate to client process that the track was disabled because of underrun;
5329 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005330 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005331 // remove from active list, but state remains ACTIVE [confusing but true]
5332 isActive = false;
5333 break;
5334 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005335 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005336 case TrackBase::STOPPING_2:
5337 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005338 case TrackBase::STOPPED:
5339 case TrackBase::FLUSHED: // flush() while active
5340 // Check for presentation complete if track is inactive
5341 // We have consumed all the buffers of this track.
5342 // This would be incomplete if we auto-paused on underrun
5343 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005344 uint32_t latency = 0;
5345 status_t result = mOutput->stream->getLatency(&latency);
5346 ALOGE_IF(result != OK,
5347 "Error when retrieving output stream latency: %d", result);
5348 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005349 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005350 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5351 // track stays in active list until presentation is complete
5352 break;
5353 }
5354 }
5355 if (track->isStopping_2()) {
5356 track->mState = TrackBase::STOPPED;
5357 }
5358 if (track->isStopped()) {
5359 // Can't reset directly, as fast mixer is still polling this track
5360 // track->reset();
5361 // So instead mark this track as needing to be reset after push with ack
5362 resetMask |= 1 << i;
5363 }
5364 isActive = false;
5365 break;
5366 case TrackBase::IDLE:
5367 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005368 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005369 }
5370
5371 if (isActive) {
5372 // was it previously inactive?
5373 if (!(state->mTrackMask & (1 << j))) {
5374 ExtendedAudioBufferProvider *eabp = track;
5375 VolumeProvider *vp = track;
5376 fastTrack->mBufferProvider = eabp;
5377 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005378 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005379 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005380 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005381 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005382 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005383 fastTrack->mGeneration++;
5384 state->mTrackMask |= 1 << j;
5385 didModify = true;
5386 // no acknowledgement required for newly active tracks
5387 }
Kevin Rocard12381092018-04-11 09:19:59 -07005388 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005389 float volume;
5390 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5391 volume = 0.f;
5392 } else {
5393 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5394 }
5395
5396 handleVoipVolume_l(&volume);
5397
Eric Laurent81784c32012-11-19 14:55:58 -08005398 // cache the combined master volume and stream type volume for fast mixer; this
5399 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005400 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005401 proxy->framesReleased()).first;
5402 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005403 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005404 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5405 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5406 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005407
Kevin Rocard12381092018-04-11 09:19:59 -07005408 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005409 ++fastTracks;
5410 } else {
5411 // was it previously active?
5412 if (state->mTrackMask & (1 << j)) {
5413 fastTrack->mBufferProvider = NULL;
5414 fastTrack->mGeneration++;
5415 state->mTrackMask &= ~(1 << j);
5416 didModify = true;
5417 // If any fast tracks were removed, we must wait for acknowledgement
5418 // because we're about to decrement the last sp<> on those tracks.
5419 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5420 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005421 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5422 // AudioTrack may start (which may not be with a start() but with a write()
5423 // after underrun) and immediately paused or released. In that case the
5424 // FastTrack state hasn't had time to update.
5425 // TODO Remove the ALOGW when this theory is confirmed.
5426 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005427 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005428 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005429 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005430 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005431 }
5432 tracksToRemove->add(track);
5433 // Avoids a misleading display in dumpsys
5434 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5435 }
jiabin245cdd92018-12-07 17:55:15 -08005436 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5437 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5438 didModify = true;
5439 }
Eric Laurent81784c32012-11-19 14:55:58 -08005440 continue;
5441 }
5442
5443 { // local variable scope to avoid goto warning
5444
5445 audio_track_cblk_t* cblk = track->cblk();
5446
5447 // The first time a track is added we wait
5448 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005449 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005450
5451 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005452 // use the trackId as the AudioMixer name.
5453 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005454 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005455 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005456 track->mChannelMask,
5457 track->mFormat,
5458 track->mSessionId);
5459 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005460 ALOGW("%s(): AudioMixer cannot create track(%d)"
5461 " mask %#x, format %#x, sessionId %d",
5462 __func__, trackId,
5463 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005464 tracksToRemove->add(track);
5465 track->invalidate(); // consider it dead.
5466 continue;
5467 }
5468 }
5469
Eric Laurent81784c32012-11-19 14:55:58 -08005470 // make sure that we have enough frames to mix one full buffer.
5471 // enforce this condition only once to enable draining the buffer in case the client
5472 // app does not call stop() and relies on underrun to stop:
5473 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5474 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005475 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005476 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Andy Hung71ba4b32022-10-06 12:09:49 -07005477 const AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005478
5479 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005480 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005481 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5482 // add frames already consumed but not yet released by the resampler
5483 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005484 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005485
Eric Laurent81784c32012-11-19 14:55:58 -08005486 uint32_t minFrames = 1;
5487 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5488 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005489 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005490 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005491
5492 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005493 if (ATRACE_ENABLED()) {
5494 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005495 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005496 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005497 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005498 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005499 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005500 !track->isPaused() && !track->isTerminated())
5501 {
Andy Hungc0691382018-09-12 18:01:57 -07005502 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005503
5504 mixedTracks++;
5505
Andy Hung69aed5f2014-02-25 17:24:40 -08005506 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5507 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005508 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005509 if (track->mainBuffer() != mSinkBuffer &&
5510 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005511 if (mEffectBufferEnabled) {
5512 mEffectBufferValid = true; // Later can set directly.
5513 }
Eric Laurent81784c32012-11-19 14:55:58 -08005514 chain = getEffectChain_l(track->sessionId());
5515 // Delegate volume control to effect in track effect chain if needed
5516 if (chain != 0) {
5517 tracksWithEffect++;
5518 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005519 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005520 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005521 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005522 }
5523 }
5524
5525
5526 int param = AudioMixer::VOLUME;
5527 if (track->mFillingUpStatus == Track::FS_FILLED) {
5528 // no ramp for the first volume setting
5529 track->mFillingUpStatus = Track::FS_ACTIVE;
5530 if (track->mState == TrackBase::RESUMING) {
5531 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005532 // If a new track is paused immediately after start, do not ramp on resume.
5533 if (cblk->mServer != 0) {
5534 param = AudioMixer::RAMP_VOLUME;
5535 }
Eric Laurent81784c32012-11-19 14:55:58 -08005536 }
Andy Hungc0691382018-09-12 18:01:57 -07005537 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005538 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005539 // FIXME should not make a decision based on mServer
5540 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005541 // If the track is stopped before the first frame was mixed,
5542 // do not apply ramp
5543 param = AudioMixer::RAMP_VOLUME;
5544 }
5545
5546 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005547 uint32_t vl, vr; // in U8.24 integer format
5548 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005549 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005550 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005551 // Always fetch volumeshaper volume to ensure state is updated.
5552 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5553 const float vh = track->getVolumeHandler()->getVolume(
5554 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005555
Eric Laurenteab90452019-06-24 15:17:46 -07005556 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5557 v = 0;
5558 }
5559
5560 handleVoipVolume_l(&v);
5561
5562 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005563 vl = vr = 0;
5564 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005565 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005566 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005567 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005568 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5569 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005570 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005571 if (vlf > GAIN_FLOAT_UNITY) {
5572 ALOGV("Track left volume out of range: %.3g", vlf);
5573 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005574 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005575 if (vrf > GAIN_FLOAT_UNITY) {
5576 ALOGV("Track right volume out of range: %.3g", vrf);
5577 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005578 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005579 // now apply the master volume and stream type volume and shaper volume
5580 vlf *= v * vh;
5581 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005582 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005583 // then derive vl and vr as U8.24 versions for the effect chain
5584 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5585 vl = (uint32_t) (scaleto8_24 * vlf);
5586 vr = (uint32_t) (scaleto8_24 * vrf);
5587 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005588 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005589 // send level comes from shared memory and so may be corrupt
5590 if (sendLevel > MAX_GAIN_INT) {
5591 ALOGV("Track send level out of range: %04X", sendLevel);
5592 sendLevel = MAX_GAIN_INT;
5593 }
Andy Hung6be49402014-05-30 10:42:03 -07005594 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5595 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005596 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005597
Kevin Rocard12381092018-04-11 09:19:59 -07005598 track->setFinalVolume((vrf + vlf) / 2.f);
5599
Eric Laurent81784c32012-11-19 14:55:58 -08005600 // Delegate volume control to effect in track effect chain if needed
5601 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5602 // Do not ramp volume if volume is controlled by effect
5603 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005604 // Update remaining floating point volume levels
5605 vlf = (float)vl / (1 << 24);
5606 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005607 track->mHasVolumeController = true;
5608 } else {
5609 // force no volume ramp when volume controller was just disabled or removed
5610 // from effect chain to avoid volume spike
5611 if (track->mHasVolumeController) {
5612 param = AudioMixer::VOLUME;
5613 }
5614 track->mHasVolumeController = false;
5615 }
5616
Eric Laurent81784c32012-11-19 14:55:58 -08005617 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005618 mAudioMixer->setBufferProvider(trackId, track);
5619 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005620
Andy Hungc0691382018-09-12 18:01:57 -07005621 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5622 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5623 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005624 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005625 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005626 AudioMixer::TRACK,
5627 AudioMixer::FORMAT, (void *)track->format());
5628 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005629 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005630 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005631 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005632
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005633 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005634 mAudioMixer->setParameter(
5635 trackId,
5636 AudioMixer::TRACK,
5637 AudioMixer::MIXER_CHANNEL_MASK,
5638 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5639 } else {
5640 mAudioMixer->setParameter(
5641 trackId,
5642 AudioMixer::TRACK,
5643 AudioMixer::MIXER_CHANNEL_MASK,
5644 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5645 }
5646
Glenn Kastene3aa6592012-12-04 12:22:46 -08005647 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005648 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005649 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005650 if (reqSampleRate == 0) {
5651 reqSampleRate = mSampleRate;
5652 } else if (reqSampleRate > maxSampleRate) {
5653 reqSampleRate = maxSampleRate;
5654 }
Eric Laurent81784c32012-11-19 14:55:58 -08005655 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005656 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005657 AudioMixer::RESAMPLE,
5658 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005659 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005660
Andy Hung8edb8dc2015-03-26 19:13:55 -07005661 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005662 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005663 AudioMixer::TIMESTRETCH,
5664 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005665 // cast away constness for this generic API.
5666 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005667
Andy Hung69aed5f2014-02-25 17:24:40 -08005668 /*
5669 * Select the appropriate output buffer for the track.
5670 *
Andy Hung98ef9782014-03-04 14:46:50 -08005671 * Tracks with effects go into their own effects chain buffer
5672 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005673 *
5674 * Other tracks can use mMixerBuffer for higher precision
5675 * channel accumulation. If this buffer is enabled
5676 * (mMixerBufferEnabled true), then selected tracks will accumulate
5677 * into it.
5678 *
5679 */
5680 if (mMixerBufferEnabled
5681 && (track->mainBuffer() == mSinkBuffer
5682 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005683 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005684 mAudioMixer->setParameter(
5685 trackId,
5686 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005687 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005688 mAudioMixer->setParameter(
5689 trackId,
5690 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005691 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005692 } else {
5693 mAudioMixer->setParameter(
5694 trackId,
5695 AudioMixer::TRACK,
5696 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5697 mAudioMixer->setParameter(
5698 trackId,
5699 AudioMixer::TRACK,
5700 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5701 // TODO: override track->mainBuffer()?
5702 mMixerBufferValid = true;
5703 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005704 } else {
5705 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005706 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005707 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005708 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005709 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005710 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005711 AudioMixer::TRACK,
5712 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5713 }
Eric Laurent81784c32012-11-19 14:55:58 -08005714 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005715 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005716 AudioMixer::TRACK,
5717 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005718 mAudioMixer->setParameter(
5719 trackId,
5720 AudioMixer::TRACK,
5721 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005722 mAudioMixer->setParameter(
5723 trackId,
5724 AudioMixer::TRACK,
5725 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005726 mAudioMixer->setParameter(
5727 trackId,
5728 AudioMixer::TRACK,
5729 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005730
5731 // reset retry count
5732 track->mRetryCount = kMaxTrackRetries;
5733
5734 // If one track is ready, set the mixer ready if:
5735 // - the mixer was not ready during previous round OR
5736 // - no other track is not ready
5737 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5738 mixerStatus != MIXER_TRACKS_ENABLED) {
5739 mixerStatus = MIXER_TRACKS_READY;
5740 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005741
5742 // Enable the next few lines to instrument a test for underrun log handling.
5743 // TODO: Remove when we have a better way of testing the underrun log.
5744#if 0
5745 static int i;
5746 if ((++i & 0xf) == 0) {
5747 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5748 }
5749#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005750 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005751 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005752 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005753 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5754 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005755 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005756 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005757 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005758
Eric Laurent81784c32012-11-19 14:55:58 -08005759 // clear effect chain input buffer if an active track underruns to avoid sending
5760 // previous audio buffer again to effects
5761 chain = getEffectChain_l(track->sessionId());
5762 if (chain != 0) {
5763 chain->clearInputBuffer();
5764 }
5765
Andy Hungc0691382018-09-12 18:01:57 -07005766 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005767 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5768 track->isStopped() || track->isPaused()) {
5769 // We have consumed all the buffers of this track.
5770 // Remove it from the list of active tracks.
5771 // TODO: use actual buffer filling status instead of latency when available from
5772 // audio HAL
5773 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005774 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005775 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5776 if (track->isStopped()) {
5777 track->reset();
5778 }
5779 tracksToRemove->add(track);
5780 }
5781 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005782 // No buffers for this track. Give it a few chances to
5783 // fill a buffer, then remove it from active list.
5784 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005785 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5786 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005787 tracksToRemove->add(track);
5788 // indicate to client process that the track was disabled because of underrun;
5789 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005790 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005791 // If one track is not ready, mark the mixer also not ready if:
5792 // - the mixer was ready during previous round OR
5793 // - no other track is ready
5794 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5795 mixerStatus != MIXER_TRACKS_READY) {
5796 mixerStatus = MIXER_TRACKS_ENABLED;
5797 }
5798 }
Andy Hungc0691382018-09-12 18:01:57 -07005799 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005800 }
5801
5802 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005803
5804 }
5805
jiabin245cdd92018-12-07 17:55:15 -08005806 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5807 // When there is no fast track playing haptic and FastMixer exists,
5808 // enabling the first FastTrack, which provides mixed data from normal
5809 // tracks, to play haptic data.
5810 FastTrack *fastTrack = &state->mFastTracks[0];
5811 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5812 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5813 didModify = true;
5814 }
5815 }
5816
Eric Laurent81784c32012-11-19 14:55:58 -08005817 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08005818 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005819 if (didModify) {
5820 state->mFastTracksGen++;
5821 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5822 if (kUseFastMixer == FastMixer_Dynamic &&
5823 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5824 state->mCommand = FastMixerState::COLD_IDLE;
5825 state->mColdFutexAddr = &mFastMixerFutex;
5826 state->mColdGen++;
5827 mFastMixerFutex = 0;
5828 if (kUseFastMixer == FastMixer_Dynamic) {
5829 mNormalSink = mOutputSink;
5830 }
5831 // If we go into cold idle, need to wait for acknowledgement
5832 // so that fast mixer stops doing I/O.
5833 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5834 pauseAudioWatchdog = true;
5835 }
Eric Laurent81784c32012-11-19 14:55:58 -08005836 }
5837 if (sq != NULL) {
5838 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005839 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5840 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5841 // when bringing the output sink into standby.)
5842 //
5843 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5844 //
5845 // This occurs with BT suspend when we idle the FastMixer with
5846 // active tracks, which may be added or removed.
5847 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005848 }
5849#ifdef AUDIO_WATCHDOG
5850 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5851 mAudioWatchdog->pause();
5852 }
5853#endif
5854
5855 // Now perform the deferred reset on fast tracks that have stopped
5856 while (resetMask != 0) {
5857 size_t i = __builtin_ctz(resetMask);
5858 ALOG_ASSERT(i < count);
5859 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005860 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005861 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5862 track->reset();
5863 }
5864
Andy Hung80d03d22018-04-10 10:32:11 -07005865 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5866 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5867 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5868 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5869 // See also the implementation of destroyTrack_l().
5870 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005871 const int trackId = track->id();
5872 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5873 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005874 }
5875 }
5876
Eric Laurent81784c32012-11-19 14:55:58 -08005877 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005878 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005879
Eric Laurentb3f315a2021-07-13 15:09:05 +02005880 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5881 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005882 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005883 }
5884
5885 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005886 // as long as there are effects we should clear the effects buffer, to avoid
5887 // passing a non-clean buffer to the effect chain
5888 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005889 if (mType == SPATIALIZER) {
5890 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5891 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005892 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005893 // sink or mix buffer must be cleared if all tracks are connected to an
5894 // effect chain as in this case the mixer will not write to the sink or mix buffer
5895 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005896 // always clear sink buffer for spatializer output as the output of the spatializer
5897 // effect will be accumulated into it
5898 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5899 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005900 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005901 if (mMixerBufferValid) {
5902 memset(mMixerBuffer, 0, mMixerBufferSize);
5903 // TODO: In testing, mSinkBuffer below need not be cleared because
5904 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5905 // after mixing.
5906 //
5907 // To enforce this guarantee:
5908 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5909 // (mixedTracks == 0 && fastTracks > 0))
5910 // must imply MIXER_TRACKS_READY.
5911 // Later, we may clear buffers regardless, and skip much of this logic.
5912 }
Andy Hung98ef9782014-03-04 14:46:50 -08005913 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005914 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005915 }
5916
5917 // if any fast tracks, then status is ready
5918 mMixerStatusIgnoringFastTracks = mixerStatus;
5919 if (fastTracks > 0) {
5920 mixerStatus = MIXER_TRACKS_READY;
5921 }
5922 return mixerStatus;
5923}
5924
Eric Laurentad7dd962016-09-22 12:38:37 -07005925// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005926uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005927{
5928 uint32_t trackCount = 0;
5929 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005930 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005931 trackCount++;
5932 }
5933 }
5934 return trackCount;
5935}
5936
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005937bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005938{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005939 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5940 // could falsely detect that the frame position has stalled due to underrun because we haven't
5941 // given the Audio HAL enough time to update.
5942 const nsecs_t nowNs = systemTime();
5943 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5944 return mLatchedValue;
5945 }
5946 mPreviousNs = nowNs;
5947 mLatchedValue = false;
5948 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005949 uint64_t position = 0;
5950 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005951 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005952 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005953 if (position != mPreviousPosition) {
5954 mPreviousPosition = position;
5955 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005956 }
5957 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005958 return mLatchedValue;
5959}
5960
5961void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5962{
5963 mLatchedValue = true;
5964 mPreviousPosition = 0;
5965 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005966}
5967
Andy Hung1bc088a2018-02-09 15:57:31 -08005968// isTrackAllowed_l() must be called with ThreadBase::mLock held
5969bool AudioFlinger::MixerThread::isTrackAllowed_l(
5970 audio_channel_mask_t channelMask, audio_format_t format,
5971 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005972{
Andy Hung1bc088a2018-02-09 15:57:31 -08005973 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5974 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005975 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005976 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005977 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005978 ALOGW("%s: invalid format: %#x", __func__, format);
5979 return false;
5980 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005981 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005982 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5983 return false;
5984 }
5985 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005986}
5987
Eric Laurent10351942014-05-08 18:49:52 -07005988// checkForNewParameter_l() must be called with ThreadBase::mLock held
5989bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5990 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005991{
Eric Laurent81784c32012-11-19 14:55:58 -08005992 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005993 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005994
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005995 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005996
Eric Laurent10351942014-05-08 18:49:52 -07005997 AudioParameter param = AudioParameter(keyValuePair);
5998 int value;
5999 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6000 reconfig = true;
6001 }
6002 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006003 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006004 status = BAD_VALUE;
6005 } else {
6006 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006007 reconfig = true;
6008 }
Eric Laurent10351942014-05-08 18:49:52 -07006009 }
6010 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006011 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006012 status = BAD_VALUE;
6013 } else {
6014 // no need to save value, since it's constant
6015 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006016 }
Eric Laurent10351942014-05-08 18:49:52 -07006017 }
6018 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6019 // do not accept frame count changes if tracks are open as the track buffer
6020 // size depends on frame count and correct behavior would not be guaranteed
6021 // if frame count is changed after track creation
6022 if (!mTracks.isEmpty()) {
6023 status = INVALID_OPERATION;
6024 } else {
6025 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006026 }
Eric Laurent10351942014-05-08 18:49:52 -07006027 }
6028 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006029 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006030 }
Eric Laurent81784c32012-11-19 14:55:58 -08006031
Eric Laurent10351942014-05-08 18:49:52 -07006032 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006033 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006034 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006035 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6036 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006037 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006038 mThreadMetrics.logEndInterval();
6039 mThreadSnapshot.onEnd();
6040 mStandby = true;
Eric Laurent10351942014-05-08 18:49:52 -07006041 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006042 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006043 }
Eric Laurent10351942014-05-08 18:49:52 -07006044 if (status == NO_ERROR && reconfig) {
6045 readOutputParameters_l();
6046 delete mAudioMixer;
6047 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006048 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006049 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006050 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006051 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006052 track->mChannelMask,
6053 track->mFormat,
6054 track->mSessionId);
Andy Hung71ba4b32022-10-06 12:09:49 -07006055 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006056 "%s(): AudioMixer cannot create track(%d)"
6057 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006058 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006059 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006060 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006061 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006062 }
Eric Laurent81784c32012-11-19 14:55:58 -08006063 }
6064
Dean Wheatley68918102021-03-19 22:09:19 +11006065 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006066}
6067
6068
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006069void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006070{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006071 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006072 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006073 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006074 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006075 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6076 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6077 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006078 if (hasFastMixer()) {
6079 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6080
6081 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6082 // while we are dumping it. It may be inconsistent, but it won't mutate!
6083 // This is a large object so we place it on the heap.
6084 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006085 const std::unique_ptr<FastMixerDumpState> copy =
6086 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006087 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006088
6089#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006090 // Similar for state queue
6091 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6092 observerCopy.dump(fd);
6093 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6094 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006095#endif
6096
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006097#ifdef AUDIO_WATCHDOG
6098 if (mAudioWatchdog != 0) {
6099 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6100 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6101 wdCopy.dump(fd);
6102 }
6103#endif
6104
6105 } else {
6106 dprintf(fd, " No FastMixer\n");
6107 }
Eric Laurent81784c32012-11-19 14:55:58 -08006108}
6109
6110uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6111{
6112 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6113}
6114
6115uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6116{
6117 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6118}
6119
6120void AudioFlinger::MixerThread::cacheParameters_l()
6121{
6122 PlaybackThread::cacheParameters_l();
6123
6124 // FIXME: Relaxed timing because of a certain device that can't meet latency
6125 // Should be reduced to 2x after the vendor fixes the driver issue
6126 // increase threshold again due to low power audio mode. The way this warning
6127 // threshold is calculated and its usefulness should be reconsidered anyway.
6128 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6129}
6130
6131// ----------------------------------------------------------------------------
6132
6133AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006134 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6135 const audio_offload_info_t& offloadInfo)
jiabinc52b1ff2019-10-31 17:20:42 -07006136 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006137 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006139 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006140}
6141
Eric Laurent81784c32012-11-19 14:55:58 -08006142AudioFlinger::DirectOutputThread::~DirectOutputThread()
6143{
6144}
6145
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006146void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006147{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006148 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006149 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6150 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6151}
6152
6153void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6154{
6155 Mutex::Autolock _l(mLock);
6156 if (mMasterBalance != balance) {
6157 mMasterBalance.store(balance);
6158 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6159 broadcast_l();
6160 }
6161}
6162
Eric Laurent5850c4c2016-11-10 13:04:31 -08006163void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006164{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006165 float left, right;
6166
Andy Hung333ab962019-05-28 20:23:35 -07006167 // Ensure volumeshaper state always advances even when muted.
6168 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hungee86cee2022-12-13 19:19:53 -08006169
Andy Hungee86cee2022-12-13 19:19:53 -08006170 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6171 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6172
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006173 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6174 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006175
6176 const int64_t volumeShaperFrames =
6177 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6178 const auto [shaperVolume, shaperActive] =
6179 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006180 mVolumeShaperActive = shaperActive;
6181
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006182 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006183 left = right = 0;
6184 } else {
6185 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006186 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006187
Glenn Kastenc56f3422014-03-21 17:53:17 -07006188 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6189 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6190 if (left > GAIN_FLOAT_UNITY) {
6191 left = GAIN_FLOAT_UNITY;
6192 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006193 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6194 if (right > GAIN_FLOAT_UNITY) {
6195 right = GAIN_FLOAT_UNITY;
6196 }
zhangjincheng73e73872023-01-16 17:17:38 +08006197 left *= v;
6198 right *= v;
6199 if (mAudioFlinger->getMode() != AUDIO_MODE_IN_COMMUNICATION
6200 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6201 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6202 right *= mMasterBalanceRight;
6203 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006204 }
6205
6206 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006207 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006208 if (left != mLeftVolFloat || right != mRightVolFloat) {
6209 mLeftVolFloat = left;
6210 mRightVolFloat = right;
6211
Eric Laurentbfb1b832013-01-07 09:53:42 -08006212 // Delegate volume control to effect in track effect chain if needed
6213 // only one effect chain can be present on DirectOutputThread, so if
6214 // there is one, the track is connected to it
6215 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006216 // if effect chain exists, volume is handled by it.
6217 // Convert volumes from float to 8.24
6218 uint32_t vl = (uint32_t)(left * (1 << 24));
6219 uint32_t vr = (uint32_t)(right * (1 << 24));
6220 // Direct/Offload effect chains set output volume in setVolume_l().
6221 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6222 } else {
6223 // otherwise we directly set the volume.
6224 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006225 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006226 }
6227 }
6228}
6229
Phil Burk43b4dcc2015-06-09 16:53:44 -07006230void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6231{
6232 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006233 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006234
Eric Laurent0f0631e2015-07-06 18:01:25 -07006235 if (previousTrack != 0 && latestTrack != 0) {
6236 if (mType == DIRECT) {
6237 if (previousTrack.get() != latestTrack.get()) {
6238 mFlushPending = true;
6239 }
6240 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006241 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6242 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006243 mFlushPending = true;
6244 }
6245 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006246 } else if (previousTrack == 0) {
6247 // there could be an old track added back during track transition for direct
6248 // output, so always issues flush to flush data of the previous track if it
6249 // was already destroyed with HAL paused, then flush can resume the playback
6250 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006251 }
6252 PlaybackThread::onAddNewTrack_l();
6253}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006254
Eric Laurent81784c32012-11-19 14:55:58 -08006255AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6256 Vector< sp<Track> > *tracksToRemove
6257)
6258{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006259 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006260 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006261 bool doHwPause = false;
6262 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006263
6264 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006265 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006266 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006267 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006268 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006269 continue;
6270 }
6271
Eric Laurent5850c4c2016-11-10 13:04:31 -08006272 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006273#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006274 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006275#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006276 // Only consider last track started for volume and mixer state control.
6277 // In theory an older track could underrun and restart after the new one starts
6278 // but as we only care about the transition phase between two tracks on a
6279 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006280 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006281 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006282
Kuowei Li23666472021-01-20 10:23:25 +08006283 if (track->isPausePending()) {
6284 track->pauseAck();
6285 // It is possible a track might have been flushed or stopped.
6286 // Other operations such as flush pending might occur on the next prepare.
6287 if (track->isPausing()) {
6288 track->setPaused();
6289 }
6290 // Always perform pause, as an immediate flush will change
6291 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006292 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006293 doHwPause = true;
6294 mHwPaused = true;
6295 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006296 } else if (track->isFlushPending()) {
6297 track->flushAck();
6298 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006299 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006300 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006301 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006302 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006303 if (last) {
6304 mLeftVolFloat = mRightVolFloat = -1.0;
6305 if (mHwPaused) {
6306 doHwResume = true;
6307 mHwPaused = false;
6308 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006309 }
6310 }
6311
Eric Laurent81784c32012-11-19 14:55:58 -08006312 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006313 // for all its buffers to be filled before processing it.
6314 // Allow draining the buffer in case the client
6315 // app does not call stop() and relies on underrun to stop:
6316 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006317 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6318 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6319 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006320 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006321
6322 // target retry count that we will use is based on the time we wait for retries.
6323 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6324 // the retry threshold is when we accept any size for PCM data. This is slightly
6325 // smaller than the retry count so we can push small bits of data without a glitch.
6326 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006327 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006328 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006329 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006330 minFrames = mNormalFrameCount;
6331 } else {
6332 minFrames = 1;
6333 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006334
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006335 const size_t framesReady = track->framesReady();
6336 const int trackId = track->id();
6337 if (ATRACE_ENABLED()) {
6338 std::string traceName("nRdy");
6339 traceName += std::to_string(trackId);
6340 ATRACE_INT(traceName.c_str(), framesReady);
6341 }
6342 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006343 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006344 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006345 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006346
6347 if (track->mFillingUpStatus == Track::FS_FILLED) {
6348 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006349 if (last) {
6350 // make sure processVolume_l() will apply new volume even if 0
6351 mLeftVolFloat = mRightVolFloat = -1.0;
6352 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006353 if (!mHwSupportsPause) {
6354 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006355 }
6356 }
6357
6358 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006359 processVolume_l(track, last);
6360 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006361 sp<Track> previousTrack = mPreviousTrack.promote();
6362 if (previousTrack != 0) {
6363 if (track != previousTrack.get()) {
6364 // Flush any data still being written from last track
6365 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006366 // Invalidate previous track to force a seek when resuming.
6367 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006368 }
6369 }
6370 mPreviousTrack = track;
6371
Eric Laurentd595b7c2013-04-03 17:27:56 -07006372 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006373 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006374 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006375 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006376 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006377 doHwResume = true;
6378 mHwPaused = false;
6379 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006380 }
Eric Laurent81784c32012-11-19 14:55:58 -08006381 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006382 // clear effect chain input buffer if the last active track started underruns
6383 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006384 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006385 mEffectChains[0]->clearInputBuffer();
6386 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006387 if (track->isStopping_1()) {
6388 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006389 if (last && mHwPaused) {
6390 doHwResume = true;
6391 mHwPaused = false;
6392 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006393 }
6394 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6395 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006396 // We have consumed all the buffers of this track.
6397 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006398 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006399 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006400 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006401 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006402 if (presComplete) {
6403 mOutput->presentationComplete();
6404 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006405 if (track->isStopping_2()) {
6406 track->mState = TrackBase::STOPPED;
6407 }
Eric Laurent81784c32012-11-19 14:55:58 -08006408 if (track->isStopped()) {
6409 track->reset();
6410 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006411 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006412 }
6413 } else {
6414 // No buffers for this track. Give it a few chances to
6415 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006416 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006417 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006418 if (!isTunerStream() // tuner streams remain active in underrun
6419 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006420 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006421 track->mRetryCount = kMaxTrackRetriesOffload;
6422 } else {
6423 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6424 tracksToRemove->add(track);
6425 // indicate to client process that the track was disabled because of
6426 // underrun; it will then automatically call start() when data is available
6427 track->disable();
6428 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6429 // unlike mixerthread, HAL can be paused for direct output
6430 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6431 "minFrames = %u, mFormat = %#x",
6432 framesReady, minFrames, mFormat);
6433 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6434 doHwPause = true;
6435 mHwPaused = true;
6436 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006437 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006438 } else if (last) {
6439 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006440 }
6441 }
6442 }
6443 }
6444
Eric Laurentd1f69b02014-12-15 14:33:13 -08006445 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006446 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006447 for (size_t i = 0; i < mTracks.size(); i++) {
6448 if (mTracks[i]->isFlushPending()) {
6449 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006450 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006451 }
6452 }
6453 }
6454
6455 // make sure the pause/flush/resume sequence is executed in the right order.
6456 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6457 // before flush and then resume HW. This can happen in case of pause/flush/resume
6458 // if resume is received before pause is executed.
6459 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006460 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006461 status_t result = mOutput->stream->pause();
6462 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006463 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006464 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006465 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006466 flushHw_l();
6467 }
6468 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006469 status_t result = mOutput->stream->resume();
6470 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006471 }
Eric Laurent81784c32012-11-19 14:55:58 -08006472 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006473 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006474
6475 return mixerStatus;
6476}
6477
6478void AudioFlinger::DirectOutputThread::threadLoop_mix()
6479{
Eric Laurent81784c32012-11-19 14:55:58 -08006480 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006481 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006482 // output audio to hardware
6483 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006484 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006485 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006486 status_t status = mActiveTrack->getNextBuffer(&buffer);
6487 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006488 // no need to pad with 0 for compressed audio
6489 if (audio_has_proportional_frames(mFormat)) {
6490 memset(curBuf, 0, frameCount * mFrameSize);
6491 }
Eric Laurent81784c32012-11-19 14:55:58 -08006492 break;
6493 }
6494 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6495 frameCount -= buffer.frameCount;
6496 curBuf += buffer.frameCount * mFrameSize;
6497 mActiveTrack->releaseBuffer(&buffer);
6498 }
Andy Hung2098f272014-02-27 14:00:06 -08006499 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006500 mSleepTimeUs = 0;
6501 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006502 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006503}
6504
6505void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6506{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006507 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006508 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006509 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006510 return;
6511 }
Andy Hung85ba3332021-04-27 17:40:26 -07006512 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6513 mSleepTimeUs = mActiveSleepTimeUs;
6514 } else {
6515 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006516 }
Andy Hung85ba3332021-04-27 17:40:26 -07006517 // Note: In S or later, we do not write zeroes for
6518 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006519}
6520
Eric Laurentd1f69b02014-12-15 14:33:13 -08006521void AudioFlinger::DirectOutputThread::threadLoop_exit()
6522{
6523 {
6524 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006525 for (size_t i = 0; i < mTracks.size(); i++) {
6526 if (mTracks[i]->isFlushPending()) {
6527 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006528 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006529 }
6530 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006531 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006532 flushHw_l();
6533 }
6534 }
6535 PlaybackThread::threadLoop_exit();
6536}
6537
6538// must be called with thread mutex locked
6539bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6540{
6541 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006542 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006543
6544 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6545 // after a timeout and we will enter standby then.
6546 if (mTracks.size() > 0) {
6547 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006548 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6549 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006550 }
6551
Eric Laurent5cff4032015-05-26 13:49:58 -07006552 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006553}
6554
Eric Laurent10351942014-05-08 18:49:52 -07006555// checkForNewParameter_l() must be called with ThreadBase::mLock held
6556bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6557 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006558{
6559 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006560 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006561
Eric Laurent10351942014-05-08 18:49:52 -07006562 AudioParameter param = AudioParameter(keyValuePair);
6563 int value;
6564 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006565 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006566 }
Eric Laurent10351942014-05-08 18:49:52 -07006567 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6568 // do not accept frame count changes if tracks are open as the track buffer
6569 // size depends on frame count and correct behavior would not be garantied
6570 // if frame count is changed after track creation
6571 if (!mTracks.isEmpty()) {
6572 status = INVALID_OPERATION;
6573 } else {
6574 reconfig = true;
6575 }
6576 }
6577 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006578 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006579 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006580 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006581 if (!mStandby) {
6582 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006583 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006584 mStandby = true;
6585 }
Eric Laurent10351942014-05-08 18:49:52 -07006586 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006587 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006588 }
6589 if (status == NO_ERROR && reconfig) {
6590 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006591 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006592 }
6593 }
6594
Dean Wheatley68918102021-03-19 22:09:19 +11006595 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006596}
6597
6598uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6599{
6600 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006601 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006602 time = PlaybackThread::activeSleepTimeUs();
6603 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006604 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006605 }
6606 return time;
6607}
6608
6609uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6610{
6611 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006612 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006613 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6614 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006615 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006616 }
6617 return time;
6618}
6619
6620uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6621{
6622 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006623 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006624 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6625 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006626 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006627 }
6628 return time;
6629}
6630
6631void AudioFlinger::DirectOutputThread::cacheParameters_l()
6632{
6633 PlaybackThread::cacheParameters_l();
6634
6635 // use shorter standby delay as on normal output to release
6636 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006637 // no delay on outputs with HW A/V sync
6638 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006639 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006640 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006641 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006642 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006643 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006644 }
Eric Laurent81784c32012-11-19 14:55:58 -08006645}
6646
Eric Laurente659ef42014-09-29 13:06:46 -07006647void AudioFlinger::DirectOutputThread::flushHw_l()
6648{
ziyangch8f194f12021-12-01 13:48:04 -08006649 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006650 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006651 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006652 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006653 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006654 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08006655 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006656}
6657
Andy Hung10cbff12017-02-21 17:30:14 -08006658int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6659 // If a VolumeShaper is active, we must wake up periodically to update volume.
6660 const int64_t NS_PER_MS = 1000000;
6661 return mVolumeShaperActive ?
6662 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6663}
6664
Eric Laurent81784c32012-11-19 14:55:58 -08006665// ----------------------------------------------------------------------------
6666
Eric Laurentbfb1b832013-01-07 09:53:42 -08006667AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006668 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006669 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006670 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006671 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006672 mDrainSequence(0),
6673 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006674{
6675}
6676
6677AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6678{
6679}
6680
6681void AudioFlinger::AsyncCallbackThread::onFirstRef()
6682{
6683 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6684}
6685
6686bool AudioFlinger::AsyncCallbackThread::threadLoop()
6687{
6688 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006689 uint32_t writeAckSequence;
6690 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006691 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006692
6693 {
6694 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006695 while (!((mWriteAckSequence & 1) ||
6696 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006697 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006698 exitPending())) {
6699 mWaitWorkCV.wait(mLock);
6700 }
6701
Eric Laurentbfb1b832013-01-07 09:53:42 -08006702 if (exitPending()) {
6703 break;
6704 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006705 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6706 mWriteAckSequence, mDrainSequence);
6707 writeAckSequence = mWriteAckSequence;
6708 mWriteAckSequence &= ~1;
6709 drainSequence = mDrainSequence;
6710 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006711 asyncError = mAsyncError;
6712 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006713 }
6714 {
Eric Laurent4de95592013-09-26 15:28:21 -07006715 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6716 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006717 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006718 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006719 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006720 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006721 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006723 if (asyncError) {
6724 playbackThread->onAsyncError();
6725 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006726 }
6727 }
6728 }
6729 return false;
6730}
6731
6732void AudioFlinger::AsyncCallbackThread::exit()
6733{
6734 ALOGV("AsyncCallbackThread::exit");
6735 Mutex::Autolock _l(mLock);
6736 requestExit();
6737 mWaitWorkCV.broadcast();
6738}
6739
Eric Laurent3b4529e2013-09-05 18:09:19 -07006740void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006741{
6742 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006743 // bit 0 is cleared
6744 mWriteAckSequence = sequence << 1;
6745}
6746
6747void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6748{
6749 Mutex::Autolock _l(mLock);
6750 // ignore unexpected callbacks
6751 if (mWriteAckSequence & 2) {
6752 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006753 mWaitWorkCV.signal();
6754 }
6755}
6756
Eric Laurent3b4529e2013-09-05 18:09:19 -07006757void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006758{
6759 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006760 // bit 0 is cleared
6761 mDrainSequence = sequence << 1;
6762}
6763
6764void AudioFlinger::AsyncCallbackThread::resetDraining()
6765{
6766 Mutex::Autolock _l(mLock);
6767 // ignore unexpected callbacks
6768 if (mDrainSequence & 2) {
6769 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006770 mWaitWorkCV.signal();
6771 }
6772}
6773
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006774void AudioFlinger::AsyncCallbackThread::setAsyncError()
6775{
6776 Mutex::Autolock _l(mLock);
6777 mAsyncError = true;
6778 mWaitWorkCV.signal();
6779}
6780
Eric Laurentbfb1b832013-01-07 09:53:42 -08006781
6782// ----------------------------------------------------------------------------
6783AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006784 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6785 const audio_offload_info_t& offloadInfo)
6786 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08006787 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006788{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006789 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006790 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006791 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006792}
6793
Eric Laurentbfb1b832013-01-07 09:53:42 -08006794void AudioFlinger::OffloadThread::threadLoop_exit()
6795{
6796 if (mFlushPending || mHwPaused) {
6797 // If a flush is pending or track was paused, just discard buffered data
6798 flushHw_l();
6799 } else {
6800 mMixerStatus = MIXER_DRAIN_ALL;
6801 threadLoop_drain();
6802 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006803 if (mUseAsyncWrite) {
6804 ALOG_ASSERT(mCallbackThread != 0);
6805 mCallbackThread->exit();
6806 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006807 PlaybackThread::threadLoop_exit();
6808}
6809
6810AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6811 Vector< sp<Track> > *tracksToRemove
6812)
6813{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006814 size_t count = mActiveTracks.size();
6815
6816 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006817 bool doHwPause = false;
6818 bool doHwResume = false;
6819
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006820 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006821
Eric Laurentbfb1b832013-01-07 09:53:42 -08006822 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006823 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006824 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006825#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006826 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006827#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006828 // Only consider last track started for volume and mixer state control.
6829 // In theory an older track could underrun and restart after the new one starts
6830 // but as we only care about the transition phase between two tracks on a
6831 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006832 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006833 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006834
Haynes Mathew George7844f672014-01-15 12:32:55 -08006835 if (track->isInvalid()) {
6836 ALOGW("An invalidated track shouldn't be in active list");
6837 tracksToRemove->add(track);
6838 continue;
6839 }
6840
6841 if (track->mState == TrackBase::IDLE) {
6842 ALOGW("An idle track shouldn't be in active list");
6843 continue;
6844 }
6845
Kuowei Li23666472021-01-20 10:23:25 +08006846 if (track->isPausePending()) {
6847 track->pauseAck();
6848 // It is possible a track might have been flushed or stopped.
6849 // Other operations such as flush pending might occur on the next prepare.
6850 if (track->isPausing()) {
6851 track->setPaused();
6852 }
6853 // Always perform pause if last, as an immediate flush will change
6854 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006855 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006856 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006857 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006858 mHwPaused = true;
6859 }
6860 // If we were part way through writing the mixbuffer to
6861 // the HAL we must save this until we resume
6862 // BUG - this will be wrong if a different track is made active,
6863 // in that case we want to discard the pending data in the
6864 // mixbuffer and tell the client to present it again when the
6865 // track is resumed
6866 mPausedWriteLength = mCurrentWriteLength;
6867 mPausedBytesRemaining = mBytesRemaining;
6868 mBytesRemaining = 0; // stop writing
6869 }
6870 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006871 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006872 if (track->isStopping_1()) {
6873 track->mRetryCount = kMaxTrackStopRetriesOffload;
6874 } else {
6875 track->mRetryCount = kMaxTrackRetriesOffload;
6876 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006877 track->flushAck();
6878 if (last) {
6879 mFlushPending = true;
6880 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006881 } else if (track->isResumePending()){
6882 track->resumeAck();
6883 if (last) {
6884 if (mPausedBytesRemaining) {
6885 // Need to continue write that was interrupted
6886 mCurrentWriteLength = mPausedWriteLength;
6887 mBytesRemaining = mPausedBytesRemaining;
6888 mPausedBytesRemaining = 0;
6889 }
6890 if (mHwPaused) {
6891 doHwResume = true;
6892 mHwPaused = false;
6893 // threadLoop_mix() will handle the case that we need to
6894 // resume an interrupted write
6895 }
6896 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006897 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006898
Eric Laurent3df841a2016-07-15 15:15:40 -07006899 mLeftVolFloat = mRightVolFloat = -1.0;
6900
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006901 // Do not handle new data in this iteration even if track->framesReady()
6902 mixerStatus = MIXER_TRACKS_ENABLED;
6903 }
6904 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006905 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006906 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006907 if (track->mFillingUpStatus == Track::FS_FILLED) {
6908 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006909 if (last) {
6910 // make sure processVolume_l() will apply new volume even if 0
6911 mLeftVolFloat = mRightVolFloat = -1.0;
6912 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006913 }
6914
6915 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006916 sp<Track> previousTrack = mPreviousTrack.promote();
6917 if (previousTrack != 0) {
6918 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006919 // Flush any data still being written from last track
6920 mBytesRemaining = 0;
6921 if (mPausedBytesRemaining) {
6922 // Last track was paused so we also need to flush saved
6923 // mixbuffer state and invalidate track so that it will
6924 // re-submit that unwritten data when it is next resumed
6925 mPausedBytesRemaining = 0;
6926 // Invalidate is a bit drastic - would be more efficient
6927 // to have a flag to tell client that some of the
6928 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006929 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006930 }
6931 // flush data already sent to the DSP if changing audio session as audio
6932 // comes from a different source. Also invalidate previous track to force a
6933 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006934 if (previousTrack->sessionId() != track->sessionId()) {
6935 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006936 }
6937 }
6938 }
6939 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006940 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006941 if (track->isStopping_1()) {
6942 track->mRetryCount = kMaxTrackStopRetriesOffload;
6943 } else {
6944 track->mRetryCount = kMaxTrackRetriesOffload;
6945 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006946 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006947 mixerStatus = MIXER_TRACKS_READY;
6948 }
6949 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006950 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006951 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006952 if (--(track->mRetryCount) <= 0) {
6953 // Hardware buffer can hold a large amount of audio so we must
6954 // wait for all current track's data to drain before we say
6955 // that the track is stopped.
6956 if (mBytesRemaining == 0) {
6957 // Only start draining when all data in mixbuffer
6958 // has been written
6959 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6960 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6961 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6962 if (last && !mStandby) {
6963 // do not modify drain sequence if we are already draining. This happens
6964 // when resuming from pause after drain.
6965 if ((mDrainSequence & 1) == 0) {
6966 mSleepTimeUs = 0;
6967 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6968 mixerStatus = MIXER_DRAIN_TRACK;
6969 mDrainSequence += 2;
6970 }
6971 if (mHwPaused) {
6972 // It is possible to move from PAUSED to STOPPING_1 without
6973 // a resume so we must ensure hardware is running
6974 doHwResume = true;
6975 mHwPaused = false;
6976 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006977 }
6978 }
Eric Laurente93cc032016-05-05 10:15:10 -07006979 } else if (last) {
6980 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6981 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006982 }
6983 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006984 // Drain has completed or we are in standby, signal presentation complete
6985 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006986 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006987 mOutput->presentationComplete();
6988 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006989 track->reset();
6990 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006991 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006992 if (!mUseAsyncWrite) {
6993 // If we don't get explicit drain notification we must
6994 // register discontinuity regardless of whether this is
6995 // the previous (!last) or the upcoming (last) track
6996 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006997 mTimestampVerifier.discontinuity(
6998 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006999 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007000 }
7001 } else {
7002 // No buffers for this track. Give it a few chances to
7003 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007004 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007005 if (!isTunerStream() // tuner streams remain active in underrun
7006 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007007 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07007008 track->mRetryCount = kMaxTrackRetriesOffload;
7009 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007010 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7011 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007012 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007013 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007014 // it will then automatically call start() when data is available
7015 track->disable();
7016 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007017 } else if (last){
7018 mixerStatus = MIXER_TRACKS_ENABLED;
7019 }
7020 }
7021 }
7022 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007023 if (track->isReady()) { // check ready to prevent premature start.
7024 processVolume_l(track, last);
7025 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007026 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007027
Eric Laurentea0fade2013-10-04 16:23:48 -07007028 // make sure the pause/flush/resume sequence is executed in the right order.
7029 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7030 // before flush and then resume HW. This can happen in case of pause/flush/resume
7031 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007032 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007033 status_t result = mOutput->stream->pause();
7034 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007035 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007036 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007037 if (mFlushPending) {
7038 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007039 }
Eric Laurentfd477972013-10-25 18:10:40 -07007040 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007041 status_t result = mOutput->stream->resume();
7042 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007043 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007044
Eric Laurentbfb1b832013-01-07 09:53:42 -08007045 // remove all the tracks that need to be...
7046 removeTracks_l(*tracksToRemove);
7047
7048 return mixerStatus;
7049}
7050
Eric Laurentbfb1b832013-01-07 09:53:42 -08007051// must be called with thread mutex locked
7052bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7053{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007054 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7055 mWriteAckSequence, mDrainSequence);
7056 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007057 return true;
7058 }
7059 return false;
7060}
7061
Eric Laurentbfb1b832013-01-07 09:53:42 -08007062bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7063{
7064 Mutex::Autolock _l(mLock);
7065 return waitingAsyncCallback_l();
7066}
7067
7068void AudioFlinger::OffloadThread::flushHw_l()
7069{
Eric Laurente659ef42014-09-29 13:06:46 -07007070 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007071 // Flush anything still waiting in the mixbuffer
7072 mCurrentWriteLength = 0;
7073 mBytesRemaining = 0;
7074 mPausedWriteLength = 0;
7075 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007076 // reset bytes written count to reflect that DSP buffers are empty after flush.
7077 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007078
Eric Laurentbfb1b832013-01-07 09:53:42 -08007079 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007080 // discard any pending drain or write ack by incrementing sequence
7081 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7082 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007083 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007084 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7085 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007086 }
7087}
7088
Haynes Mathew George05317d22016-05-03 16:34:26 -07007089void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7090{
7091 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007092 if (PlaybackThread::invalidateTracks_l(streamType)) {
7093 mFlushPending = true;
7094 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007095}
7096
Eric Laurentbfb1b832013-01-07 09:53:42 -08007097// ----------------------------------------------------------------------------
7098
Eric Laurent81784c32012-11-19 14:55:58 -08007099AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007100 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007101 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007102 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007103 mWaitTimeMs(UINT_MAX)
7104{
7105 addOutputTrack(mainThread);
7106}
7107
7108AudioFlinger::DuplicatingThread::~DuplicatingThread()
7109{
7110 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7111 mOutputTracks[i]->destroy();
7112 }
7113}
7114
7115void AudioFlinger::DuplicatingThread::threadLoop_mix()
7116{
7117 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007118 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007119 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007120 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007121 if (mMixerBufferValid) {
7122 memset(mMixerBuffer, 0, mMixerBufferSize);
7123 } else {
7124 memset(mSinkBuffer, 0, mSinkBufferSize);
7125 }
Eric Laurent81784c32012-11-19 14:55:58 -08007126 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007127 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007128 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007129 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007130 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007131}
7132
7133void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7134{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007135 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007136 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007137 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007138 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007139 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007140 }
7141 } else if (mBytesWritten != 0) {
7142 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7143 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007144 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007145 } else {
7146 // flush remaining overflow buffers in output tracks
7147 writeFrames = 0;
7148 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007149 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007150 }
7151}
7152
Eric Laurentbfb1b832013-01-07 09:53:42 -08007153ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007154{
7155 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007156 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7157
7158 // Consider the first OutputTrack for timestamp and frame counting.
7159
7160 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7161 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7162 // we always claim success.
7163 if (i == 0) {
7164 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7165 ALOGD_IF(correction != 0 && writeFrames != 0,
7166 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7167 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7168 mFramesWritten -= correction;
7169 }
7170
7171 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007172 }
Andy Hungcf10d742020-04-28 15:38:24 -07007173 if (mStandby) {
7174 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007175 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007176 mStandby = false;
7177 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007178 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007179}
7180
7181void AudioFlinger::DuplicatingThread::threadLoop_standby()
7182{
7183 // DuplicatingThread implements standby by stopping all tracks
7184 for (size_t i = 0; i < outputTracks.size(); i++) {
7185 outputTracks[i]->stop();
7186 }
7187}
7188
Andy Hung71ba4b32022-10-06 12:09:49 -07007189void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007190{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007191 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007192
7193 std::stringstream ss;
7194 const size_t numTracks = mOutputTracks.size();
7195 ss << " " << numTracks << " OutputTracks";
7196 if (numTracks > 0) {
7197 ss << ":";
7198 for (const auto &track : mOutputTracks) {
7199 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007200 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007201 if (thread.get() != nullptr) {
7202 ss << thread.get() << ", " << thread->id();
7203 } else {
7204 ss << "null";
7205 }
7206 ss << ")";
7207 }
7208 }
7209 ss << "\n";
7210 std::string result = ss.str();
7211 write(fd, result.c_str(), result.size());
7212}
7213
Eric Laurent81784c32012-11-19 14:55:58 -08007214void AudioFlinger::DuplicatingThread::saveOutputTracks()
7215{
7216 outputTracks = mOutputTracks;
7217}
7218
7219void AudioFlinger::DuplicatingThread::clearOutputTracks()
7220{
7221 outputTracks.clear();
7222}
7223
7224void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7225{
7226 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007227 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7228 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7229 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7230 const size_t frameCount =
7231 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7232 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7233 // from different OutputTracks and their associated MixerThreads (e.g. one may
7234 // nearly empty and the other may be dropping data).
7235
Svet Ganov33761132021-05-13 22:51:08 +00007236 // TODO b/182392769: use attribution source util, move to server edge
7237 AttributionSourceState attributionSource = AttributionSourceState();
7238 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007239 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007240 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007241 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007242 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007243 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007244 this,
7245 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007246 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007247 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007248 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007249 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007250 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7251 if (status != NO_ERROR) {
7252 ALOGE("addOutputTrack() initCheck failed %d", status);
7253 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007254 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007255 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7256 mOutputTracks.add(outputTrack);
7257 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7258 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007259}
7260
7261void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7262{
7263 Mutex::Autolock _l(mLock);
7264 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7265 if (mOutputTracks[i]->thread() == thread) {
7266 mOutputTracks[i]->destroy();
7267 mOutputTracks.removeAt(i);
7268 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007269 if (thread->getOutput() == mOutput) {
7270 mOutput = NULL;
7271 }
Eric Laurent81784c32012-11-19 14:55:58 -08007272 return;
7273 }
7274 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007275 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007276}
7277
7278// caller must hold mLock
7279void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7280{
7281 mWaitTimeMs = UINT_MAX;
7282 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7283 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7284 if (strong != 0) {
7285 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7286 if (waitTimeMs < mWaitTimeMs) {
7287 mWaitTimeMs = waitTimeMs;
7288 }
7289 }
7290 }
7291}
7292
Andy Hung71ba4b32022-10-06 12:09:49 -07007293bool AudioFlinger::DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007294{
7295 for (size_t i = 0; i < outputTracks.size(); i++) {
7296 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7297 if (thread == 0) {
7298 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7299 outputTracks[i].get());
7300 return false;
7301 }
7302 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7303 // see note at standby() declaration
7304 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7305 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7306 thread.get());
7307 return false;
7308 }
7309 }
7310 return true;
7311}
7312
Kevin Rocard12381092018-04-11 09:19:59 -07007313void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7314 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007315{
Kevin Rocard12381092018-04-11 09:19:59 -07007316 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7317 outputTrack->setMetadatas(metadata.tracks);
7318 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007319}
7320
Eric Laurent81784c32012-11-19 14:55:58 -08007321uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7322{
7323 return (mWaitTimeMs * 1000) / 2;
7324}
7325
7326void AudioFlinger::DuplicatingThread::cacheParameters_l()
7327{
7328 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7329 updateWaitTime_l();
7330
7331 MixerThread::cacheParameters_l();
7332}
7333
Eric Laurentb3f315a2021-07-13 15:09:05 +02007334// ----------------------------------------------------------------------------
7335
Eric Laurentfa0f6742021-08-17 18:39:44 +02007336AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007337 AudioStreamOut* output,
7338 audio_io_handle_t id,
7339 bool systemReady,
7340 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007341 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007342{
7343}
7344
Eric Laurent6f9534f2022-05-03 18:15:04 +02007345void AudioFlinger::SpatializerThread::onFirstRef() {
7346 PlaybackThread::onFirstRef();
7347
7348 Mutex::Autolock _l(mLock);
7349 status_t status = mOutput->stream->setLatencyModeCallback(this);
7350 if (status != INVALID_OPERATION) {
7351 updateHalSupportedLatencyModes_l();
7352 }
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007353
Andy Hung41ccf7f2022-12-14 14:25:49 -08007354 const pid_t tid = getTid();
7355 if (tid == -1) {
7356 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7357 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7358 } else {
7359 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7360 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007361 stream()->setHalThreadPriority(priorityBoost);
7362 }
7363 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007364}
7365
7366status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7367 audio_patch_handle_t *handle)
7368{
7369 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7370 updateHalSupportedLatencyModes_l();
7371 return status;
7372}
7373
7374void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7375 std::vector<audio_latency_mode_t> latencyModes;
Andy Hung4bd53e72022-11-17 17:21:45 -08007376 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
7377 if (status != NO_ERROR) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007378 latencyModes.clear();
7379 }
7380 if (latencyModes != mSupportedLatencyModes) {
Andy Hung4bd53e72022-11-17 17:21:45 -08007381 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
7382 __func__, mId, status, toString(latencyModes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007383 mSupportedLatencyModes.swap(latencyModes);
7384 sendHalLatencyModesChangedEvent_l();
7385 }
7386}
7387
7388void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7389 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7390}
7391
7392void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7393 // if mSupportedLatencyModes is empty, the HAL stream does not support
7394 // latency mode control and we can exit.
7395 if (mSupportedLatencyModes.empty()) {
7396 return;
7397 }
7398 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7399 if (mSupportedLatencyModes.size() == 1) {
7400 // If the HAL only support one latency mode currently, confirm the choice
7401 latencyMode = mSupportedLatencyModes[0];
7402 } else if (mSupportedLatencyModes.size() > 1) {
7403 // Request low latency if:
7404 // - The low latency mode is requested by the spatializer controller
7405 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7406 // AND
7407 // - At least one active track is spatialized
7408 bool hasSpatializedActiveTrack = false;
7409 for (const auto& track : mActiveTracks) {
7410 if (track->isSpatialized()) {
7411 hasSpatializedActiveTrack = true;
7412 break;
7413 }
7414 }
7415 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7416 latencyMode = AUDIO_LATENCY_MODE_LOW;
7417 }
7418 }
7419
7420 if (latencyMode != mSetLatencyMode) {
7421 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007422 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7423 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007424 if (status == NO_ERROR) {
7425 mSetLatencyMode = latencyMode;
7426 }
7427 }
7428}
7429
7430status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7431 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7432 return BAD_VALUE;
7433 }
7434 Mutex::Autolock _l(mLock);
7435 mRequestedLatencyMode = mode;
7436 return NO_ERROR;
7437}
7438
7439status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7440 std::vector<audio_latency_mode_t>* modes) {
7441 if (modes == nullptr) {
7442 return BAD_VALUE;
7443 }
7444 Mutex::Autolock _l(mLock);
7445 *modes = mSupportedLatencyModes;
7446 return NO_ERROR;
7447}
7448
Eric Laurent49879b72022-12-20 20:20:23 +01007449status_t AudioFlinger::PlaybackThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007450 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
Eric Laurent49879b72022-12-20 20:20:23 +01007451 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007452 return INVALID_OPERATION;
7453 }
7454 mBluetoothLatencyModesEnabled.store(enabled);
7455 return NO_ERROR;
7456}
7457
Eric Laurentfa0f6742021-08-17 18:39:44 +02007458void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007459{
7460 bool hasVirtualizer = false;
7461 bool hasDownMixer = false;
7462 sp<EffectHandle> finalDownMixer;
7463 {
7464 Mutex::Autolock _l(mLock);
7465 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7466 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007467 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007468 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7469 }
7470
7471 finalDownMixer = mFinalDownMixer;
7472 mFinalDownMixer.clear();
7473 }
7474
7475 if (hasVirtualizer) {
7476 if (finalDownMixer != nullptr) {
7477 int32_t ret;
7478 finalDownMixer->disable(&ret);
7479 }
7480 finalDownMixer.clear();
7481 } else if (!hasDownMixer) {
7482 std::vector<effect_descriptor_t> descriptors;
7483 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7484 EFFECT_UIID_DOWNMIX, &descriptors);
7485 if (status != NO_ERROR) {
7486 return;
7487 }
7488 ALOG_ASSERT(!descriptors.empty(),
7489 "%s getDescriptors() returned no error but empty list", __func__);
7490
7491 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7492 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007493 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007494
7495 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7496 ALOGW("%s error creating downmixer %d", __func__, status);
7497 finalDownMixer.clear();
7498 } else {
7499 int32_t ret;
7500 finalDownMixer->enable(&ret);
7501 }
7502 }
7503
7504 {
7505 Mutex::Autolock _l(mLock);
7506 mFinalDownMixer = finalDownMixer;
7507 }
7508}
7509
Eric Laurent6f9534f2022-05-03 18:15:04 +02007510void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7511 std::vector<audio_latency_mode_t> modes) {
7512 Mutex::Autolock _l(mLock);
7513 if (modes != mSupportedLatencyModes) {
Andy Hungb5ecdb82022-11-18 19:40:00 -08007514 ALOGD("%s: thread(%d) supported latency modes: %s",
7515 __func__, mId, toString(modes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007516 mSupportedLatencyModes.swap(modes);
7517 sendHalLatencyModesChangedEvent_l();
7518 }
7519}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007520
Eric Laurent81784c32012-11-19 14:55:58 -08007521// ----------------------------------------------------------------------------
7522// Record
7523// ----------------------------------------------------------------------------
7524
7525AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7526 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007527 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007528 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007529 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007530 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007531 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007532 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007533 mActiveTracks(&this->mLocalLog),
7534 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007535 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007536 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007537 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7538 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007539 // mFastCapture below
7540 , mFastCaptureFutex(0)
7541 // mInputSource
7542 // mPipeSink
7543 // mPipeSource
7544 , mPipeFramesP2(0)
7545 // mPipeMemory
7546 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007547 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007548 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007549{
Glenn Kastend7dca052015-03-05 16:05:54 -08007550 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7551 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007552
George Burgess IVa8f90c12020-05-14 11:27:19 -07007553 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007554 mIsMsdDevice = strcmp(
7555 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7556 }
7557
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007558 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007559
Andy Hungc8fddf32018-08-08 18:32:37 -07007560 // TODO: We may also match on address as well as device type for
7561 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007562 // TODO: This property should be ensure that only contains one single device type.
7563 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7564 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007565 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7566 : AUDIO_DEVICE_NONE));
7567
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007568 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007569 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007570 size_t numCounterOffers = 0;
7571 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007572#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007573 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007574#else
7575 (void)
7576#endif
7577 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007578 ALOG_ASSERT(index == 0);
7579
7580 // initialize fast capture depending on configuration
7581 bool initFastCapture;
7582 switch (kUseFastCapture) {
7583 case FastCapture_Never:
7584 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007585 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007586 break;
7587 case FastCapture_Always:
7588 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007589 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007590 break;
7591 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007592 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7593 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7594 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7595 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7596 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007597 break;
7598 // case FastCapture_Dynamic:
7599 }
7600
7601 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007602 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007603 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007604 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7605 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007606 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007607 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007608 const sp<MemoryDealer> roHeap(readOnlyHeap());
7609 sp<IMemory> pipeMemory;
7610 if ((roHeap == 0) ||
7611 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007612 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007613 ALOGE("not enough memory for pipe buffer size=%zu; "
7614 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7615 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7616 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007617 goto failed;
7618 }
7619 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7620 memset(pipeBuffer, 0, pipeSize);
7621 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007622 const NBAIO_Format offersFast[1] = {format};
7623 size_t numCounterOffersFast = 0;
7624 [[maybe_unused]] ssize_t index = pipe->negotiate(offersFast, std::size(offersFast),
7625 nullptr /* counterOffers */, numCounterOffersFast);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007626 ALOG_ASSERT(index == 0);
7627 mPipeSink = pipe;
7628 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07007629 numCounterOffersFast = 0;
7630 index = pipeReader->negotiate(offersFast, std::size(offersFast),
7631 nullptr /* counterOffers */, numCounterOffersFast);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007632 ALOG_ASSERT(index == 0);
7633 mPipeSource = pipeReader;
7634 mPipeFramesP2 = pipeFramesP2;
7635 mPipeMemory = pipeMemory;
7636
7637 // create fast capture
7638 mFastCapture = new FastCapture();
7639 FastCaptureStateQueue *sq = mFastCapture->sq();
7640#ifdef STATE_QUEUE_DUMP
7641 // FIXME
7642#endif
7643 FastCaptureState *state = sq->begin();
7644 state->mCblk = NULL;
7645 state->mInputSource = mInputSource.get();
7646 state->mInputSourceGen++;
7647 state->mPipeSink = pipe;
7648 state->mPipeSinkGen++;
7649 state->mFrameCount = mFrameCount;
7650 state->mCommand = FastCaptureState::COLD_IDLE;
7651 // already done in constructor initialization list
7652 //mFastCaptureFutex = 0;
7653 state->mColdFutexAddr = &mFastCaptureFutex;
7654 state->mColdGen++;
7655 state->mDumpState = &mFastCaptureDumpState;
7656#ifdef TEE_SINK
7657 // FIXME
7658#endif
7659 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7660 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7661 sq->end();
7662 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7663
7664 // start the fast capture
7665 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7666 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007667 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007668 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007669#ifdef AUDIO_WATCHDOG
7670 // FIXME
7671#endif
7672
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007673 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007674 }
Andy Hung8946a282018-04-19 20:04:56 -07007675#ifdef TEE_SINK
7676 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7677 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7678#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007679failed: ;
7680
7681 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007682}
7683
Eric Laurent81784c32012-11-19 14:55:58 -08007684AudioFlinger::RecordThread::~RecordThread()
7685{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007686 if (mFastCapture != 0) {
7687 FastCaptureStateQueue *sq = mFastCapture->sq();
7688 FastCaptureState *state = sq->begin();
7689 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7690 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7691 if (old == -1) {
7692 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7693 }
7694 }
7695 state->mCommand = FastCaptureState::EXIT;
7696 sq->end();
7697 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7698 mFastCapture->join();
7699 mFastCapture.clear();
7700 }
7701 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007702 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007703 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007704}
7705
7706void AudioFlinger::RecordThread::onFirstRef()
7707{
Glenn Kastend7dca052015-03-05 16:05:54 -08007708 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007709}
7710
Eric Laurent555530a2017-02-07 18:17:24 -08007711void AudioFlinger::RecordThread::preExit()
7712{
7713 ALOGV(" preExit()");
7714 Mutex::Autolock _l(mLock);
7715 for (size_t i = 0; i < mTracks.size(); i++) {
7716 sp<RecordTrack> track = mTracks[i];
7717 track->invalidate();
7718 }
7719 mActiveTracks.clear();
7720 mStartStopCond.broadcast();
7721}
7722
Eric Laurent81784c32012-11-19 14:55:58 -08007723bool AudioFlinger::RecordThread::threadLoop()
7724{
Eric Laurent81784c32012-11-19 14:55:58 -08007725 nsecs_t lastWarning = 0;
7726
7727 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007728
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007729reacquire_wakelock:
7730 sp<RecordTrack> activeTrack;
7731 {
7732 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007733 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007734 }
7735
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007736 // used to request a deferred sleep, to be executed later while mutex is unlocked
7737 uint32_t sleepUs = 0;
7738
Andy Hung446f4df2019-02-21 12:26:41 -08007739 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7740
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007741 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007742 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007743 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007744
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007745 // activeTracks accumulates a copy of a subset of mActiveTracks
7746 Vector< sp<RecordTrack> > activeTracks;
7747
Glenn Kasten735f45f2014-08-18 15:51:59 -07007748 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007749 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007750
Glenn Kasten735f45f2014-08-18 15:51:59 -07007751 // reference to a fast track which is about to be removed
7752 sp<RecordTrack> fastTrackToRemove;
7753
Eric Laurent33403f02020-05-29 18:35:06 -07007754 bool silenceFastCapture = false;
7755
Eric Laurent81784c32012-11-19 14:55:58 -08007756 { // scope for mLock
7757 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007758
Eric Laurent021cf962014-05-13 10:18:14 -07007759 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007760
Eric Laurent000a4192014-01-29 15:17:32 -08007761 // check exitPending here because checkForNewParameters_l() and
7762 // checkForNewParameters_l() can temporarily release mLock
7763 if (exitPending()) {
7764 break;
7765 }
7766
Eric Laurent5c25d562016-07-13 17:17:45 -07007767 // sleep with mutex unlocked
7768 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007769 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007770 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7771 ATRACE_END();
7772 sleepUs = 0;
7773 continue;
7774 }
7775
Glenn Kasten2b806402013-11-20 16:37:38 -08007776 // if no active track(s), then standby and release wakelock
7777 size_t size = mActiveTracks.size();
7778 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007779 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007780 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007781 releaseWakeLock_l();
7782 ALOGV("RecordThread: loop stopping");
7783 // go to sleep
7784 mWaitWorkCV.wait(mLock);
7785 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007786 goto reacquire_wakelock;
7787 }
7788
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007789 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007790 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007791 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007792
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007793 activeTrack = mActiveTracks[i];
7794 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007795 if (activeTrack->isFastTrack()) {
7796 ALOG_ASSERT(fastTrackToRemove == 0);
7797 fastTrackToRemove = activeTrack;
7798 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007799 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007800 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007801 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007802 continue;
7803 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007804
7805 TrackBase::track_state activeTrackState = activeTrack->mState;
7806 switch (activeTrackState) {
7807
7808 case TrackBase::PAUSING:
7809 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007810 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007811 doBroadcast = true;
7812 size--;
7813 continue;
7814
7815 case TrackBase::STARTING_1:
7816 sleepUs = 10000;
7817 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007818 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007819 continue;
7820
7821 case TrackBase::STARTING_2:
7822 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007823 if (mStandby) {
7824 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007825 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007826 mStandby = false;
7827 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007828 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007829 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007830 break;
7831
7832 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007833 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007834 break;
7835
Andy Hungce685402018-10-05 17:23:27 -07007836 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7837 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7838 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007839 default:
Andy Hungce685402018-10-05 17:23:27 -07007840 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7841 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007842 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007843
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007844 if (activeTrack->isFastTrack()) {
7845 ALOG_ASSERT(!mFastTrackAvail);
7846 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007847 // if the active fast track is silenced either:
7848 // 1) silence the whole capture from fast capture buffer if this is
7849 // the only active track
7850 // 2) invalidate this track: this will cause the client to reconnect and possibly
7851 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007852 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007853 if (activeTrack->isSilenced()) {
7854 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007855 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007856 } else {
7857 silenceFastCapture = true;
7858 }
7859 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007860 // Invalidate fast tracks if access to audio history is required as this is not
7861 // possible with fast tracks. Once the fast track has been invalidated, no new
7862 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7863 if (mMaxSharedAudioHistoryMs != 0) {
7864 invalidate = true;
7865 }
7866 if (invalidate) {
7867 activeTrack->invalidate();
7868 ALOG_ASSERT(fastTrackToRemove == 0);
7869 fastTrackToRemove = activeTrack;
7870 removeTrack_l(activeTrack);
7871 mActiveTracks.remove(activeTrack);
7872 size--;
7873 continue;
7874 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007875 fastTrack = activeTrack;
7876 }
Eric Laurent33403f02020-05-29 18:35:06 -07007877
7878 activeTracks.add(activeTrack);
7879 i++;
7880
Glenn Kasten9e982352013-08-14 14:39:50 -07007881 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007882
Andy Hungdae27702016-10-31 14:01:16 -07007883 mActiveTracks.updatePowerState(this);
7884
Kevin Rocard069c2712018-03-29 19:09:14 -07007885 updateMetadata_l();
7886
Eric Laurent5c25d562016-07-13 17:17:45 -07007887 if (allStopped) {
7888 standbyIfNotAlreadyInStandby();
7889 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007890 if (doBroadcast) {
7891 mStartStopCond.broadcast();
7892 }
7893
7894 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007895 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007896 if (sleepUs == 0) {
7897 sleepUs = kRecordThreadSleepUs;
7898 }
7899 continue;
7900 }
7901 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007902
Eric Laurent81784c32012-11-19 14:55:58 -08007903 lockEffectChains_l(effectChains);
7904 }
7905
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007906 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007907
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007908 size_t size = effectChains.size();
7909 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007910 // thread mutex is not locked, but effect chain is locked
7911 effectChains[i]->process_l();
7912 }
7913
Glenn Kasten735f45f2014-08-18 15:51:59 -07007914 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007915 if (mFastCapture != 0) {
7916 FastCaptureStateQueue *sq = mFastCapture->sq();
7917 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007918 bool didModify = false;
7919 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007920 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7921 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7922 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7923 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7924 if (old == -1) {
7925 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7926 }
7927 }
7928 state->mCommand = FastCaptureState::READ_WRITE;
7929#if 0 // FIXME
7930 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007931 FastThreadDumpState::kSamplingNforLowRamDevice :
7932 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007933#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007934 didModify = true;
7935 }
7936 audio_track_cblk_t *cblkOld = state->mCblk;
7937 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7938 if (cblkNew != cblkOld) {
7939 state->mCblk = cblkNew;
7940 // block until acked if removing a fast track
7941 if (cblkOld != NULL) {
7942 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7943 }
7944 didModify = true;
7945 }
jiabin01c8f562018-07-19 17:47:28 -07007946 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7947 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7948 if (state->mFastPatchRecordBufferProvider != abp) {
7949 state->mFastPatchRecordBufferProvider = abp;
7950 state->mFastPatchRecordFormat = fastTrack == 0 ?
7951 AUDIO_FORMAT_INVALID : fastTrack->format();
7952 didModify = true;
7953 }
Eric Laurent33403f02020-05-29 18:35:06 -07007954 if (state->mSilenceCapture != silenceFastCapture) {
7955 state->mSilenceCapture = silenceFastCapture;
7956 didModify = true;
7957 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007958 sq->end(didModify);
7959 if (didModify) {
7960 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007961#if 0
7962 if (kUseFastCapture == FastCapture_Dynamic) {
7963 mNormalSource = mPipeSource;
7964 }
7965#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 }
7967 }
7968
Glenn Kasten735f45f2014-08-18 15:51:59 -07007969 // now run the fast track destructor with thread mutex unlocked
7970 fastTrackToRemove.clear();
7971
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007972 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7973 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7974 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7975 // If destination is non-contiguous, first read past the nominal end of buffer, then
7976 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007977
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007978 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07007979 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08007980 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007981
7982 // If an NBAIO source is present, use it to read the normal capture's data
7983 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007984 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007985
7986 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7987 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7988 // we immediately retry the read() to get data and prevent another overflow.
7989 for (int retries = 0; retries <= 2; ++retries) {
7990 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7991 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7992 framesToRead);
7993 if (framesRead != OVERRUN) break;
7994 }
7995
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007996 const ssize_t availableToRead = mPipeSource->availableToRead();
7997 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007998 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007999 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008000 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8001 "more frames to read than fifo size, %zd > %zu",
8002 availableToRead, mPipeFramesP2);
8003 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8004 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8005 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8006 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008007 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8008 }
8009 if (framesRead < 0) {
8010 status_t status = (status_t) framesRead;
8011 switch (status) {
8012 case OVERRUN:
8013 ALOGW("overrun on read from pipe");
8014 framesRead = 0;
8015 break;
8016 case NEGOTIATE:
8017 ALOGE("re-negotiation is needed");
8018 framesRead = -1; // Will cause an attempt to recover.
8019 break;
8020 default:
8021 ALOGE("unknown error %d on read from pipe", status);
8022 break;
8023 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008024 }
8025 // otherwise use the HAL / AudioStreamIn directly
8026 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008027 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008028 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008029 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008030 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008031 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008032 if (result < 0) {
8033 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008034 } else {
8035 framesRead = bytesRead / mFrameSize;
8036 }
8037 }
8038
Andy Hung446f4df2019-02-21 12:26:41 -08008039 const int64_t lastIoEndNs = systemTime(); // end IO timing
8040
Andy Hung3f0c9022016-01-15 17:49:46 -08008041 // Update server timestamp with server stats
8042 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008043 if (framesRead >= 0) {
8044 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8045 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8046 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008047
8048 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008049 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008050 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008051 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008052 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8053 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8054 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008055 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008056 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8057
8058 mTimestampVerifier.add(position, time, mSampleRate);
8059
8060 // Correct timestamps
8061 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008062 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008063 id(), (long long)time, (long long)position);
8064 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8065 position = correctedTimestamp.mFrames;
8066 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008067 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008068 id(), (long long)time, (long long)position);
8069 }
8070
Andy Hung3f0c9022016-01-15 17:49:46 -08008071 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8072 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8073 // Note: In general record buffers should tend to be empty in
8074 // a properly running pipeline.
8075 //
8076 // Also, it is not advantageous to call get_presentation_position during the read
8077 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008078 } else {
8079 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008080 }
8081 }
Andy Hunge6c37112019-02-26 17:38:10 -08008082
8083 // From the timestamp, input read latency is negative output write latency.
8084 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8085 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8086 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8087 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8088 mLatencyMs.add(latencyMs);
8089 }
8090
Andy Hung3f0c9022016-01-15 17:49:46 -08008091 // Use this to track timestamp information
8092 // ALOGD("%s", mTimestamp.toString().c_str());
8093
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008094 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008095 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008096 // Force input into standby so that it tries to recover at next read attempt
8097 inputStandBy();
8098 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008099 }
8100 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008101 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008102 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008103 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008104 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008105
Andy Hung8946a282018-04-19 20:04:56 -07008106#ifdef TEE_SINK
8107 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8108#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008109 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008110 {
8111 size_t part1 = mRsmpInFramesP2 - rear;
8112 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008113 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008114 (framesRead - part1) * mFrameSize);
8115 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008116 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008117 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008118
8119 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008120
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008121 // loop over each active track
8122 for (size_t i = 0; i < size; i++) {
8123 activeTrack = activeTracks[i];
8124
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008125 // skip fast tracks, as those are handled directly by FastCapture
8126 if (activeTrack->isFastTrack()) {
8127 continue;
8128 }
8129
Andy Hung73c02e42015-03-29 01:13:58 -07008130 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008131 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8132
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008133 enum {
8134 OVERRUN_UNKNOWN,
8135 OVERRUN_TRUE,
8136 OVERRUN_FALSE
8137 } overrun = OVERRUN_UNKNOWN;
8138
8139 // loop over getNextBuffer to handle circular sink
8140 for (;;) {
8141
8142 activeTrack->mSink.frameCount = ~0;
8143 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8144 size_t framesOut = activeTrack->mSink.frameCount;
8145 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8146
Andy Hung73c02e42015-03-29 01:13:58 -07008147 // check available frames and handle overrun conditions
8148 // if the record track isn't draining fast enough.
8149 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008150 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008151 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8152 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008153 overrun = OVERRUN_TRUE;
8154 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008155 if (framesOut == 0 || framesIn == 0) {
8156 break;
8157 }
8158
Andy Hung6770c6f2015-04-07 13:43:36 -07008159 // Don't allow framesOut to be larger than what is possible with resampling
8160 // from framesIn.
8161 // This isn't strictly necessary but helps limit buffer resizing in
8162 // RecordBufferConverter. TODO: remove when no longer needed.
8163 framesOut = min(framesOut,
8164 destinationFramesPossible(
8165 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008166
8167 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008168 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008169 // straight from RecordThread buffer to RecordTrack buffer.
8170 AudioBufferProvider::Buffer buffer;
8171 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008172 const status_t getNextBufferStatus =
8173 activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8174 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008175 ALOGV_IF(buffer.frameCount != framesOut,
8176 "%s() read less than expected (%zu vs %zu)",
8177 __func__, buffer.frameCount, framesOut);
8178 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008179 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008180 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8181 } else {
8182 framesOut = 0;
8183 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008184 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008185 }
8186 } else {
8187 // process frames from the RecordThread buffer provider to the RecordTrack
8188 // buffer
8189 framesOut = activeTrack->mRecordBufferConverter->convert(
8190 activeTrack->mSink.raw,
8191 activeTrack->mResamplerBufferProvider,
8192 framesOut);
8193 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008194
8195 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8196 overrun = OVERRUN_FALSE;
8197 }
8198
Andy Hung93bb5732023-05-04 21:16:34 -07008199 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8200 const ssize_t framesToDrop =
8201 activeTrack->mSynchronizedRecordState.updateRecordFrames(framesOut);
8202 if (framesToDrop == 0) {
8203 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008204 if (framesOut > 0) {
8205 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008206 // Sanitize before releasing if the track has no access to the source data
8207 // An idle UID receives silence from non virtual devices until active
8208 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008209 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008210 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008211 activeTrack->releaseBuffer(&activeTrack->mSink);
8212 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008213 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008214 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008215 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008216 }
8217 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008218
8219 switch (overrun) {
8220 case OVERRUN_TRUE:
8221 // client isn't retrieving buffers fast enough
8222 if (!activeTrack->setOverflow()) {
8223 nsecs_t now = systemTime();
8224 // FIXME should lastWarning per track?
8225 if ((now - lastWarning) > kWarningThrottleNs) {
8226 ALOGW("RecordThread: buffer overflow");
8227 lastWarning = now;
8228 }
8229 }
8230 break;
8231 case OVERRUN_FALSE:
8232 activeTrack->clearOverflow();
8233 break;
8234 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008235 break;
8236 }
8237
Andy Hung3f0c9022016-01-15 17:49:46 -08008238 // update frame information and push timestamp out
8239 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008240 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008241 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8242 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008243 }
8244
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008245unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008246 // enable changes in effect chain
8247 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008248 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008249 if (audio_has_proportional_frames(mFormat)
8250 && loopCount == lastLoopCountRead + 1) {
8251 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8252 const double jitterMs =
8253 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8254 {framesRead, readPeriodNs},
8255 {0, 0} /* lastTimestamp */, mSampleRate);
8256 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8257
8258 Mutex::Autolock _l(mLock);
8259 mIoJitterMs.add(jitterMs);
8260 mProcessTimeMs.add(processMs);
8261 }
8262 // update timing info.
8263 mLastIoBeginNs = lastIoBeginNs;
8264 mLastIoEndNs = lastIoEndNs;
8265 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008266 }
8267
Glenn Kasten93e471f2013-08-19 08:40:07 -07008268 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008269
8270 {
8271 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008272 for (size_t i = 0; i < mTracks.size(); i++) {
8273 sp<RecordTrack> track = mTracks[i];
8274 track->invalidate();
8275 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008276 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008277 mStartStopCond.broadcast();
8278 }
8279
8280 releaseWakeLock();
8281
8282 ALOGV("RecordThread %p exiting", this);
8283 return false;
8284}
8285
Glenn Kasten93e471f2013-08-19 08:40:07 -07008286void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008287{
8288 if (!mStandby) {
8289 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008290 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008291 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008292 mStandby = true;
8293 }
8294}
8295
8296void AudioFlinger::RecordThread::inputStandBy()
8297{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008298 // Idle the fast capture if it's currently running
8299 if (mFastCapture != 0) {
8300 FastCaptureStateQueue *sq = mFastCapture->sq();
8301 FastCaptureState *state = sq->begin();
8302 if (!(state->mCommand & FastCaptureState::IDLE)) {
8303 state->mCommand = FastCaptureState::COLD_IDLE;
8304 state->mColdFutexAddr = &mFastCaptureFutex;
8305 state->mColdGen++;
8306 mFastCaptureFutex = 0;
8307 sq->end();
8308 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8309 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8310#if 0
8311 if (kUseFastCapture == FastCapture_Dynamic) {
8312 // FIXME
8313 }
8314#endif
8315#ifdef AUDIO_WATCHDOG
8316 // FIXME
8317#endif
8318 } else {
8319 sq->end(false /*didModify*/);
8320 }
8321 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008322 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008323 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008324
8325 // If going into standby, flush the pipe source.
8326 if (mPipeSource.get() != nullptr) {
8327 const ssize_t flushed = mPipeSource->flush();
8328 if (flushed > 0) {
8329 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8330 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8331 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8332 }
8333 }
Eric Laurent81784c32012-11-19 14:55:58 -08008334}
8335
Glenn Kasten05997e22014-03-13 15:08:33 -07008336// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008337sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008338 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008339 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008340 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008341 audio_format_t format,
8342 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008343 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008344 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008345 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008346 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008347 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008348 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008349 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008350 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008351 audio_port_handle_t portId,
8352 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008353{
Glenn Kasten74935e42013-12-19 08:56:45 -08008354 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008355 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008356 sp<RecordTrack> track;
8357 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008358 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008359 audio_input_flags_t requestedFlags = *flags;
8360 uint32_t sampleRate;
8361
8362 lStatus = initCheck();
8363 if (lStatus != NO_ERROR) {
8364 ALOGE("createRecordTrack_l() audio driver not initialized");
8365 goto Exit;
8366 }
8367
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008368 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8369 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8370 lStatus = BAD_VALUE;
8371 goto Exit;
8372 }
8373
Eric Laurentec376dc2021-04-08 20:41:22 +02008374 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008375 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008376 lStatus = PERMISSION_DENIED;
8377 goto Exit;
8378 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008379 if (maxSharedAudioHistoryMs < 0
8380 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8381 lStatus = BAD_VALUE;
8382 goto Exit;
8383 }
8384 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008385 if (*pSampleRate == 0) {
8386 *pSampleRate = mSampleRate;
8387 }
8388 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008389
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008390 // special case for FAST flag considered OK if fast capture is present and access to
8391 // audio history is not required
8392 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008393 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8394 }
8395
Eric Laurentf14db3c2017-12-08 14:20:36 -08008396 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008397 if ((*flags & inputFlags) != *flags) {
8398 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8399 " input flags (%08x)",
8400 *flags, inputFlags);
8401 *flags = (audio_input_flags_t)(*flags & inputFlags);
8402 }
Eric Laurent81784c32012-11-19 14:55:58 -08008403
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008404 // client expresses a preference for FAST and no access to audio history,
8405 // but we get the final say
8406 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008407 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008408 // we formerly checked for a callback handler (non-0 tid),
8409 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008410 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008411 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008412 // Frame count is not specified (0), or is less than or equal the pipe depth.
8413 // It is OK to provide a higher capacity than requested.
8414 // We will force it to mPipeFramesP2 below.
8415 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008416 // PCM data
8417 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008418 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008419 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008420 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008421 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008422 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008423 hasFastCapture() &&
8424 // there are sufficient fast track slots available
8425 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008426 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008427 // check compatibility with audio effects.
8428 Mutex::Autolock _l(mLock);
8429 // Do not accept FAST flag if the session has software effects
8430 sp<EffectChain> chain = getEffectChain_l(sessionId);
8431 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008432 audio_input_flags_t old = *flags;
8433 chain->checkInputFlagCompatibility(flags);
8434 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008435 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8436 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008437 }
8438 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008439 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008440 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8441 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008442 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008443 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8444 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008445 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008446 this, frameCount, mFrameCount, mPipeFramesP2,
8447 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008448 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008449 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008450 }
8451 }
8452
Eric Laurentf14db3c2017-12-08 14:20:36 -08008453 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8454 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8455 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8456 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8457 lStatus = BAD_TYPE;
8458 goto Exit;
8459 }
8460
Glenn Kasten74105912014-07-03 12:28:53 -07008461 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008462 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008463 // fast track: frame count is exactly the pipe depth
8464 frameCount = mPipeFramesP2;
8465 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008466 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008467 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008468 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8469 // or 20 ms if there is a fast capture
8470 // TODO This could be a roundupRatio inline, and const
8471 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8472 * sampleRate + mSampleRate - 1) / mSampleRate;
8473 // minimum number of notification periods is at least kMinNotifications,
8474 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8475 static const size_t kMinNotifications = 3;
8476 static const uint32_t kMinMs = 30;
8477 // TODO This could be a roundupRatio inline
8478 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8479 // TODO This could be a roundupRatio inline
8480 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8481 maxNotificationFrames;
8482 const size_t minFrameCount = maxNotificationFrames *
8483 max(kMinNotifications, minNotificationsByMs);
8484 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008485 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8486 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008487 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008488 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008489 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008490 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008491
8492 { // scope for mLock
8493 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008494 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008495 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008496 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008497 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008498 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008499 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008500 }
Eric Laurent81784c32012-11-19 14:55:58 -08008501
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008502 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008503 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008504 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent9ff3e532022-11-10 16:04:44 +01008505 attributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008506 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008507
Glenn Kasten03003332013-08-06 15:40:54 -07008508 lStatus = track->initCheck();
8509 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008510 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008511 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008512 goto Exit;
8513 }
8514 mTracks.add(track);
8515
Eric Laurent05067782016-06-01 18:27:28 -07008516 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008517 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8518 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8519 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008520 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008521 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008522
8523 if (maxSharedAudioHistoryMs != 0) {
8524 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8525 }
Eric Laurent81784c32012-11-19 14:55:58 -08008526 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008527
Eric Laurent81784c32012-11-19 14:55:58 -08008528 lStatus = NO_ERROR;
8529
8530Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008531 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008532 return track;
8533}
8534
8535status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8536 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008537 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008538{
8539 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8540 sp<ThreadBase> strongMe = this;
8541 status_t status = NO_ERROR;
8542
8543 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008544 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008545 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung93bb5732023-05-04 21:16:34 -07008546 recordTrack->mSynchronizedRecordState.startRecording(
8547 mAudioFlinger->createSyncEvent(
8548 event, triggerSession,
8549 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008550 }
8551
8552 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008553 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008554 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008555 if (recordTrack->isInvalid()) {
8556 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008557 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8558 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008559 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008560 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8561 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008562 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8563 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008564 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008565 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008566 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008567 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008568 }
8569 return status;
8570 }
8571
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008572 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8573 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8574 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008575 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008576 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008577 if (recordTrack->isExternalTrack()) {
8578 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008579 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008580 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008581 if (recordTrack->isInvalid()) {
8582 recordTrack->clearSyncStartEvent();
8583 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8584 recordTrack->mState = TrackBase::STARTING_2;
8585 // STARTING_2 forces destroy to call stopInput.
8586 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008587 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8588 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008589 }
8590 if (recordTrack->mState != TrackBase::STARTING_1) {
8591 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008592 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008593 // Someone else has changed state, let them take over,
8594 // leave mState in the new state.
8595 recordTrack->clearSyncStartEvent();
8596 return INVALID_OPERATION;
8597 }
8598 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008599 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008600 ALOGW("%s(%d): startInput failed, status %d",
8601 __func__, recordTrack->id(), status);
8602 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8603 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008604 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008605 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008606 return status;
8607 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008608 sendIoConfigEvent_l(
8609 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008610 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008611
8612 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8613
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008614 // Catch up with current buffer indices if thread is already running.
8615 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8616 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8617 // see previously buffered data before it called start(), but with greater risk of overrun.
8618
Andy Hung73c02e42015-03-29 01:13:58 -07008619 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008620 if (!recordTrack->isDirect()) {
8621 // clear any converter state as new data will be discontinuous
8622 recordTrack->mRecordBufferConverter->reset();
8623 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008624 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008625 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008626 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008627 return status;
8628 }
Eric Laurent81784c32012-11-19 14:55:58 -08008629}
8630
Andy Hung068e08e2023-05-15 19:02:55 -07008631void AudioFlinger::RecordThread::syncStartEventCallback(const wp<audioflinger::SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008632{
Andy Hung068e08e2023-05-15 19:02:55 -07008633 sp<audioflinger::SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008634
8635 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008636 sp<RefBase> ptr = strongEvent->cookie().promote();
8637 if (ptr != 0) {
8638 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8639 recordTrack->handleSyncStartEvent(strongEvent);
8640 }
Eric Laurent81784c32012-11-19 14:55:58 -08008641 }
8642}
8643
Glenn Kastena8356f62013-07-25 14:37:52 -07008644bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008645 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008646 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008647 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008648 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008649 return false;
8650 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008651 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008652 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008653
Andy Hungabfab202019-03-07 19:45:54 -08008654 // NOTE: Waiting here is important to keep stop synchronous.
8655 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008656 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8657 mWaitWorkCV.broadcast(); // signal thread to stop
8658 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008659 }
Andy Hungce685402018-10-05 17:23:27 -07008660
8661 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008662 ALOGV("Record stopped OK");
8663 return true;
8664 }
Andy Hungce685402018-10-05 17:23:27 -07008665
8666 // don't handle anything - we've been invalidated or restarted and in a different state
8667 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8668 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008669 return false;
8670}
8671
Andy Hung068e08e2023-05-15 19:02:55 -07008672bool AudioFlinger::RecordThread::isValidSyncEvent(
8673 const sp<audioflinger::SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008674{
8675 return false;
8676}
8677
Andy Hung068e08e2023-05-15 19:02:55 -07008678status_t AudioFlinger::RecordThread::setSyncEvent(
8679 const sp<audioflinger::SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008680{
8681#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8682 if (!isValidSyncEvent(event)) {
8683 return BAD_VALUE;
8684 }
8685
Glenn Kastend848eb42016-03-08 13:42:11 -08008686 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008687 status_t ret = NAME_NOT_FOUND;
8688
8689 Mutex::Autolock _l(mLock);
8690
8691 for (size_t i = 0; i < mTracks.size(); i++) {
8692 sp<RecordTrack> track = mTracks[i];
8693 if (eventSession == track->sessionId()) {
8694 (void) track->setSyncEvent(event);
8695 ret = NO_ERROR;
8696 }
8697 }
8698 return ret;
8699#else
8700 return BAD_VALUE;
8701#endif
8702}
8703
jiabin653cc0a2018-01-17 17:54:10 -08008704status_t AudioFlinger::RecordThread::getActiveMicrophones(
Mikhail Naganov2a6a3012023-02-13 11:45:03 -08008705 std::vector<media::MicrophoneInfoFw>* activeMicrophones)
jiabin653cc0a2018-01-17 17:54:10 -08008706{
8707 ALOGV("RecordThread::getActiveMicrophones");
8708 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008709 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008710 return NO_INIT;
8711 }
jiabin9ff780e2018-03-19 18:19:52 -07008712 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8713 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008714}
8715
Paul McLean12340082019-03-19 09:35:05 -06008716status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8717 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008718{
Paul McLean12340082019-03-19 09:35:05 -06008719 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008720 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008721 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008722 return NO_INIT;
8723 }
Paul McLean12340082019-03-19 09:35:05 -06008724 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008725}
8726
Paul McLean12340082019-03-19 09:35:05 -06008727status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008728{
Paul McLean12340082019-03-19 09:35:05 -06008729 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008730 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008731 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008732 return NO_INIT;
8733 }
Paul McLean12340082019-03-19 09:35:05 -06008734 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008735}
8736
Eric Laurentec376dc2021-04-08 20:41:22 +02008737status_t AudioFlinger::RecordThread::shareAudioHistory(
8738 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8739 int64_t sharedAudioStartMs) {
8740 AutoMutex _l(mLock);
8741 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8742}
8743
8744status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8745 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8746 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008747
Eric Laurentec376dc2021-04-08 20:41:22 +02008748 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8749 return BAD_VALUE;
8750 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008751
8752 if (sharedAudioStartMs < 0
8753 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008754 return BAD_VALUE;
8755 }
8756
Eric Laurent2407ce32021-04-26 14:56:03 +02008757 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8758 // As we cannot detect more than one wraparound, only accept values up current write position
8759 // after one wraparound
8760 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8761 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008762 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008763 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8764 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008765 // Bring the start frame position within the input buffer to match the documented
8766 // "best effort" behavior of the API.
8767 if (sharedOffset < 0) {
8768 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07008769 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008770 sharedAudioStartFrames =
8771 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008772 }
8773
Eric Laurentec376dc2021-04-08 20:41:22 +02008774 mSharedAudioPackageName = sharedAudioPackageName;
8775 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008776 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008777 } else {
8778 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008779 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008780 }
8781 return NO_ERROR;
8782}
8783
Eric Laurent92d0a322021-07-16 15:32:33 +02008784void AudioFlinger::RecordThread::resetAudioHistory_l() {
8785 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8786 mSharedAudioStartFrames = -1;
8787 mSharedAudioPackageName = "";
8788}
8789
Kevin Rocard069c2712018-03-29 19:09:14 -07008790void AudioFlinger::RecordThread::updateMetadata_l()
8791{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008792 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8793 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008794 }
8795 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02008796 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07008797 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02008798 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07008799 }
8800 mInput->stream->updateSinkMetadata(metadata);
8801}
8802
Eric Laurent81784c32012-11-19 14:55:58 -08008803// destroyTrack_l() must be called with ThreadBase::mLock held
8804void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8805{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008806 track->terminate();
8807 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008808
Eric Laurent81784c32012-11-19 14:55:58 -08008809 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008810 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008811 removeTrack_l(track);
8812 }
8813}
8814
8815void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8816{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008817 String8 result;
8818 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008819 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008820
Eric Laurent81784c32012-11-19 14:55:58 -08008821 mTracks.remove(track);
8822 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008823 if (track->isFastTrack()) {
8824 ALOG_ASSERT(!mFastTrackAvail);
8825 mFastTrackAvail = true;
8826 }
Eric Laurent81784c32012-11-19 14:55:58 -08008827}
8828
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008829void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008830{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008831 AudioStreamIn *input = mInput;
8832 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8833 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008834 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008835 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008836 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008837 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008838 }
Andy Hungbfa64962017-06-12 14:43:19 -07008839
8840 if (input != nullptr) {
8841 dprintf(fd, " Hal stream dump:\n");
8842 (void)input->stream->dump(fd);
8843 }
8844
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008845 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008846 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008847
Glenn Kasten2f90c512015-12-02 11:40:09 -08008848 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8849 // while we are dumping it. It may be inconsistent, but it won't mutate!
8850 // This is a large object so we place it on the heap.
8851 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008852 const std::unique_ptr<FastCaptureDumpState> copy =
8853 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008854 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008855}
8856
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008857void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008858{
Eric Laurent81784c32012-11-19 14:55:58 -08008859 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008860 size_t numtracks = mTracks.size();
8861 size_t numactive = mActiveTracks.size();
8862 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008863 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008864 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008865 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008866 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008867 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008868 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008869 for (size_t i = 0; i < numtracks ; ++i) {
8870 sp<RecordTrack> track = mTracks[i];
8871 if (track != 0) {
8872 bool active = mActiveTracks.indexOf(track) >= 0;
8873 if (active) {
8874 numactiveseen++;
8875 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008876 result.append(prefix);
8877 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008878 }
Eric Laurent81784c32012-11-19 14:55:58 -08008879 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008880 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008881 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008882 }
8883
Marco Nelissenb2208842014-02-07 14:00:50 -08008884 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008885 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008886 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008887 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008888 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008889 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008890 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008891 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008892 result.append(prefix);
8893 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008894 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008895 }
Eric Laurent81784c32012-11-19 14:55:58 -08008896
8897 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008898 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08008899}
8900
Eric Laurent5ada82e2019-08-29 17:53:54 -07008901void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008902{
8903 Mutex::Autolock _l(mLock);
8904 for (size_t i = 0; i < mTracks.size() ; i++) {
8905 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008906 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008907 track->setSilenced(silenced);
8908 }
8909 }
8910}
Andy Hung73c02e42015-03-29 01:13:58 -07008911
8912void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8913{
8914 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8915 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008916 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008917 const int32_t rear = recordThread->mRsmpInRear;
8918 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008919 if (mRecordTrack->startFrames() >= 0) {
8920 int32_t startFrames = mRecordTrack->startFrames();
8921 // Accept a recent wraparound of mRsmpInRear
8922 if (startFrames <= rear) {
8923 deltaFrames = rear - startFrames;
8924 } else {
8925 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008926 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008927 // start frame cannot be further in the past than start of resampling buffer
8928 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8929 deltaFrames = recordThread->mRsmpInFrames;
8930 }
8931 }
8932 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008933}
8934
8935void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8936 size_t *framesAvailable, bool *hasOverrun)
8937{
8938 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8939 RecordThread *recordThread = (RecordThread *) threadBase.get();
8940 const int32_t rear = recordThread->mRsmpInRear;
8941 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008942 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008943
8944 size_t framesIn;
8945 bool overrun = false;
8946 if (filled < 0) {
8947 // should not happen, but treat like a massive overrun and re-sync
8948 framesIn = 0;
8949 mRsmpInFront = rear;
8950 overrun = true;
8951 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8952 framesIn = (size_t) filled;
8953 } else {
8954 // client is not keeping up with server, but give it latest data
8955 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008956 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8957 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008958 overrun = true;
8959 }
8960 if (framesAvailable != NULL) {
8961 *framesAvailable = framesIn;
8962 }
8963 if (hasOverrun != NULL) {
8964 *hasOverrun = overrun;
8965 }
8966}
8967
Eric Laurent81784c32012-11-19 14:55:58 -08008968// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008969status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008970 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008971{
Andy Hung73c02e42015-03-29 01:13:58 -07008972 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008973 if (threadBase == 0) {
8974 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008975 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008976 return NOT_ENOUGH_DATA;
8977 }
8978 RecordThread *recordThread = (RecordThread *) threadBase.get();
8979 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008980 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008981 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008982 // FIXME should not be P2 (don't want to increase latency)
8983 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008984 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008985 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008986
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008987 front &= recordThread->mRsmpInFramesP2 - 1;
8988 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008989 if (part1 > (size_t) filled) {
8990 part1 = filled;
8991 }
8992 size_t ask = buffer->frameCount;
8993 ALOG_ASSERT(ask > 0);
8994 if (part1 > ask) {
8995 part1 = ask;
8996 }
8997 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008998 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008999 buffer->raw = NULL;
9000 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009001 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009002 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009003 }
9004
Andy Hung57446612015-04-19 23:56:46 -07009005 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009006 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009007 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009008 return NO_ERROR;
9009}
9010
9011// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009012void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9013 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009014{
Hongwei Wang95e37682019-04-12 11:13:36 -07009015 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009016 if (stepCount == 0) {
9017 return;
9018 }
Andy Hung73c02e42015-03-29 01:13:58 -07009019 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9020 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009021 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009022 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009023 buffer->frameCount = 0;
9024}
9025
Eric Laurentd8365c52017-07-16 15:27:05 -07009026void AudioFlinger::RecordThread::checkBtNrec()
9027{
9028 Mutex::Autolock _l(mLock);
9029 checkBtNrec_l();
9030}
9031
9032void AudioFlinger::RecordThread::checkBtNrec_l()
9033{
9034 // disable AEC and NS if the device is a BT SCO headset supporting those
9035 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009036 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009037 mAudioFlinger->btNrecIsOff();
9038 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9039 for (size_t i = 0; i < mEffectChains.size(); i++) {
9040 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9041 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9042 }
9043 }
9044}
9045
Andy Hung97a893e2015-03-29 01:03:07 -07009046
Eric Laurent10351942014-05-08 18:49:52 -07009047bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9048 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009049{
9050 bool reconfig = false;
9051
Eric Laurent10351942014-05-08 18:49:52 -07009052 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009053
Eric Laurent10351942014-05-08 18:49:52 -07009054 audio_format_t reqFormat = mFormat;
9055 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009056 // 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 +08009057 [[maybe_unused]] audio_channel_mask_t channelMask =
9058 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009059
9060 AudioParameter param = AudioParameter(keyValuePair);
9061 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009062
9063 // scope for AutoPark extends to end of method
9064 AutoPark<FastCapture> park(mFastCapture);
9065
Eric Laurent10351942014-05-08 18:49:52 -07009066 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9067 // channel count change can be requested. Do we mandate the first client defines the
9068 // HAL sampling rate and channel count or do we allow changes on the fly?
9069 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9070 samplingRate = value;
9071 reconfig = true;
9072 }
9073 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009074 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009075 status = BAD_VALUE;
9076 } else {
9077 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009078 reconfig = true;
9079 }
Eric Laurent10351942014-05-08 18:49:52 -07009080 }
9081 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9082 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009083 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009084 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009085 status = BAD_VALUE;
9086 } else {
9087 channelMask = mask;
9088 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009089 }
Eric Laurent10351942014-05-08 18:49:52 -07009090 }
9091 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9092 // do not accept frame count changes if tracks are open as the track buffer
9093 // size depends on frame count and correct behavior would not be guaranteed
9094 // if frame count is changed after track creation
9095 if (mActiveTracks.size() > 0) {
9096 status = INVALID_OPERATION;
9097 } else {
9098 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009099 }
Eric Laurent10351942014-05-08 18:49:52 -07009100 }
9101 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009102 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009103 }
9104 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9105 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009106 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009107 }
Glenn Kastene198c362013-08-13 09:13:36 -07009108
Eric Laurent10351942014-05-08 18:49:52 -07009109 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009110 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009111 if (status == INVALID_OPERATION) {
9112 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009113 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009114 }
9115 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009116 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009117 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9118 if (mInput->stream->getAudioProperties(&config) == OK &&
9119 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9120 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009121 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009122 status = NO_ERROR;
9123 }
Eric Laurent81784c32012-11-19 14:55:58 -08009124 }
Eric Laurent10351942014-05-08 18:49:52 -07009125 if (status == NO_ERROR) {
9126 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009127 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009128 }
9129 }
Eric Laurent81784c32012-11-19 14:55:58 -08009130 }
Eric Laurent10351942014-05-08 18:49:52 -07009131
Eric Laurent81784c32012-11-19 14:55:58 -08009132 return reconfig;
9133}
9134
9135String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9136{
Eric Laurent81784c32012-11-19 14:55:58 -08009137 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009138 if (initCheck() == NO_ERROR) {
9139 String8 out_s8;
9140 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9141 return out_s8;
9142 }
Eric Laurent81784c32012-11-19 14:55:58 -08009143 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009144 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009145}
9146
Mikhail Naganov88536df2021-07-26 17:30:29 -07009147void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009148 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009149 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009150 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009151 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009152 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009153 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009154 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9155 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009156 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009157 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009158 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009159 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009160 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009161 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009162 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009163 break;
9164 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009165 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009166}
9167
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009168void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009169{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009170 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9171 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009172 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009173 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9174 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009175 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9176 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009177 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009178 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009179 ALOGI("HAL format %#x is not linear pcm", mFormat);
9180 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009181 result = mInput->stream->getFrameSize(&mFrameSize);
9182 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009183 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9184 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009185 result = mInput->stream->getBufferSize(&mBufferSize);
9186 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009187 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009188 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9189 "mBufferSize=%zu, mFrameCount=%zu",
9190 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009191
Eric Laurentec376dc2021-04-08 20:41:22 +02009192 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9193 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009194 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009195
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009196 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9197 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009198
9199 audio_input_flags_t flags = mInput->flags;
9200 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9201 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9202 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9203 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9204 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9205 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9206 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9207 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9208 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009209}
9210
Glenn Kasten5f972c02014-01-13 09:59:31 -08009211uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009212{
9213 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009214 uint32_t result;
9215 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9216 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009217 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009218 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009219}
9220
Glenn Kastend848eb42016-03-08 13:42:11 -08009221KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009222{
Glenn Kastend848eb42016-03-08 13:42:11 -08009223 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009224 Mutex::Autolock _l(mLock);
9225 for (size_t j = 0; j < mTracks.size(); ++j) {
9226 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009227 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009228 if (ids.indexOfKey(sessionId) < 0) {
9229 ids.add(sessionId, true);
9230 }
9231 }
9232 return ids;
9233}
9234
9235AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9236{
9237 Mutex::Autolock _l(mLock);
9238 AudioStreamIn *input = mInput;
9239 mInput = NULL;
9240 return input;
9241}
9242
9243// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009244sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009245{
9246 if (mInput == NULL) {
9247 return NULL;
9248 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009249 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009250}
9251
9252status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9253{
Eric Laurent81784c32012-11-19 14:55:58 -08009254 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009255 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009256 chain->setInBuffer(NULL);
9257 chain->setOutBuffer(NULL);
9258
9259 checkSuspendOnAddEffectChain_l(chain);
9260
Eric Laurent1b928682014-10-02 19:41:47 -07009261 // make sure enabled pre processing effects state is communicated to the HAL as we
9262 // just moved them to a new input stream.
9263 chain->syncHalEffectsState();
9264
Eric Laurent81784c32012-11-19 14:55:58 -08009265 mEffectChains.add(chain);
9266
9267 return NO_ERROR;
9268}
9269
9270size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9271{
9272 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009273
9274 for (size_t i = 0; i < mEffectChains.size(); i++) {
9275 if (chain == mEffectChains[i]) {
9276 mEffectChains.removeAt(i);
9277 break;
9278 }
Eric Laurent81784c32012-11-19 14:55:58 -08009279 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009280 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009281}
9282
Eric Laurent1c333e22014-05-20 10:48:17 -07009283status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9284 audio_patch_handle_t *handle)
9285{
9286 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009287
9288 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009289 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009290 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009291 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009292 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009293 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009294 }
9295
Eric Laurentd8365c52017-07-16 15:27:05 -07009296 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009297
9298 // store new source and send to effects
9299 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9300 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009301 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009302 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009303 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009304 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009305
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009306 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009307 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9308 status = hwDevice->createAudioPatch(patch->num_sources,
9309 patch->sources,
9310 patch->num_sinks,
9311 patch->sinks,
9312 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009313 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009314 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9315 patch->sinks[0].ext.mix.usecase.source,
9316 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009317 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009318 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009319
jiabinc52b1ff2019-10-31 17:20:42 -07009320 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009321 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009322 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009323 }
Eric Laurent296fb132015-05-01 11:38:42 -07009324
Andy Hungc2b11cb2020-04-22 09:04:01 -07009325 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009326 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009327 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009328 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009329 // also dispatch to active AudioRecords
9330 for (const auto &track : mActiveTracks) {
9331 track->logEndInterval();
9332 track->logBeginInterval(pathSourcesAsString);
9333 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009334 return status;
9335}
9336
9337status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9338{
9339 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009340
jiabinc52b1ff2019-10-31 17:20:42 -07009341 mPatch = audio_patch{};
9342 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009343
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009344 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009345 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9346 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009347 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009348 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009349 }
9350 return status;
9351}
9352
jiabinc52b1ff2019-10-31 17:20:42 -07009353void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9354{
wendy lin56aa82b2020-12-02 15:19:55 +08009355 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009356 mOutDevices = outDevices;
9357 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9358 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009359 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009360 }
9361}
9362
Eric Laurentec376dc2021-04-08 20:41:22 +02009363int32_t AudioFlinger::RecordThread::getOldestFront_l()
9364{
9365 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009366 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009367 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009368 int32_t oldestFront = mRsmpInRear;
9369 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009370 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009371 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9372 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009373 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009374 if (filled > maxFilled) {
9375 oldestFront = front;
9376 maxFilled = filled;
9377 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009378 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009379 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009380 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9381 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009382 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009383}
9384
9385void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9386{
9387 if (offset == 0) {
9388 return;
9389 }
9390 for (size_t i = 0; i < mTracks.size(); i++) {
9391 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9392 front = audio_utils::safe_sub_overflow(front, offset);
9393 mTracks[i]->mResamplerBufferProvider->setFront(front);
9394 }
9395}
9396
9397void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9398{
9399 // This is the formula for calculating the temporary buffer size.
9400 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9401 // 1 full output buffer, regardless of the alignment of the available input.
9402 // The value is somewhat arbitrary, and could probably be even larger.
9403 // A larger value should allow more old data to be read after a track calls start(),
9404 // without increasing latency.
9405 //
9406 // Note this is independent of the maximum downsampling ratio permitted for capture.
9407 size_t minRsmpInFrames = mFrameCount * 7;
9408
9409 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9410 // capture history available to another client using the same session ID:
9411 // dimension the resampler input buffer accordingly.
9412
9413 // Get oldest client read position: getOldestFront_l() must be called before altering
9414 // mRsmpInRear, or mRsmpInFrames
9415 int32_t previousFront = getOldestFront_l();
9416 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9417 int32_t previousRear = mRsmpInRear;
9418 mRsmpInRear = 0;
9419
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009420 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9421 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9422 "resizeInputBuffer_l() called with invalid max shared history %d",
9423 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009424 if (maxSharedAudioHistoryMs != 0) {
9425 // resizeInputBuffer_l should never be called with a non zero shared history if the
9426 // buffer was not already allocated
9427 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9428 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9429 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9430 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009431 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009432 return;
9433 }
9434 mRsmpInFrames = rsmpInFrames;
9435 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009436 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009437 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9438 // initialized
9439 if (mRsmpInFrames < minRsmpInFrames) {
9440 mRsmpInFrames = minRsmpInFrames;
9441 }
9442 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9443
9444 // TODO optimize audio capture buffer sizes ...
9445 // Here we calculate the size of the sliding buffer used as a source
9446 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9447 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9448 // be better to have it derived from the pipe depth in the long term.
9449 // The current value is higher than necessary. However it should not add to latency.
9450
9451 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9452 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9453
9454 void *rsmpInBuffer;
9455 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9456 // if posix_memalign fails, will segv here.
9457 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9458
9459 // Copy audio history if any from old buffer before freeing it
9460 if (previousRear != 0) {
9461 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9462 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9463
9464 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9465 previousFront &= previousRsmpInFramesP2 - 1;
9466 size_t part1 = previousRsmpInFramesP2 - previousFront;
9467 if (part1 > (size_t) unread) {
9468 part1 = unread;
9469 }
9470 if (part1 != 0) {
9471 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9472 part1 * mFrameSize);
9473 mRsmpInRear = part1;
9474 part1 = unread - part1;
9475 if (part1 != 0) {
9476 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9477 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9478 mRsmpInRear += part1;
9479 }
9480 }
9481 // Update front for all clients according to new rear
9482 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9483 } else {
9484 mRsmpInRear = 0;
9485 }
9486 free(mRsmpInBuffer);
9487 mRsmpInBuffer = rsmpInBuffer;
9488}
9489
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009490void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009491{
9492 Mutex::Autolock _l(mLock);
9493 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009494 if (record->getSource()) {
9495 mSource = record->getSource();
9496 }
Eric Laurent83b88082014-06-20 18:31:16 -07009497}
9498
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009499void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009500{
9501 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009502 if (mSource == record->getSource()) {
9503 mSource = mInput;
9504 }
Eric Laurent83b88082014-06-20 18:31:16 -07009505 destroyTrack_l(record);
9506}
9507
Mikhail Naganovdc769682018-05-04 15:34:08 -07009508void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009509{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009510 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009511 config->role = AUDIO_PORT_ROLE_SINK;
9512 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9513 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009514 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9515 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9516 config->flags.input = mInput->flags;
9517 }
Eric Laurent83b88082014-06-20 18:31:16 -07009518}
Eric Laurent1c333e22014-05-20 10:48:17 -07009519
Eric Laurent6acd1d42017-01-04 14:23:29 -08009520// ----------------------------------------------------------------------------
9521// Mmap
9522// ----------------------------------------------------------------------------
9523
9524AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9525 : mThread(thread)
9526{
Phil Burk9fabbf82017-08-03 12:02:00 -07009527 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009528}
9529
9530AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9531{
Phil Burk9fabbf82017-08-03 12:02:00 -07009532 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009533}
9534
9535status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9536 struct audio_mmap_buffer_info *info)
9537{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009538 return mThread->createMmapBuffer(minSizeFrames, info);
9539}
9540
9541status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9542{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009543 return mThread->getMmapPosition(position);
9544}
9545
jiabinb7d8c5a2020-08-26 17:24:52 -07009546status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9547 int64_t *timeNanos) {
9548 return mThread->getExternalPosition(position, timeNanos);
9549}
9550
Eric Laurenta54f1282017-07-01 19:39:32 -07009551status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009552 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009553
9554{
jiabind1f1cb62020-03-24 11:57:57 -07009555 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009556}
9557
9558status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9559{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009560 return mThread->stop(handle);
9561}
9562
Eric Laurent18b57012017-02-13 16:23:52 -08009563status_t AudioFlinger::MmapThreadHandle::standby()
9564{
Eric Laurent18b57012017-02-13 16:23:52 -08009565 return mThread->standby();
9566}
9567
Eric Laurent6acd1d42017-01-04 14:23:29 -08009568
9569AudioFlinger::MmapThread::MmapThread(
9570 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009571 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009572 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009573 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009574 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009575 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009576 mActiveTracks(&this->mLocalLog),
9577 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9578 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009579{
Eric Laurent18b57012017-02-13 16:23:52 -08009580 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009581 readHalParameters_l();
9582}
9583
9584AudioFlinger::MmapThread::~MmapThread()
9585{
9586}
9587
9588void AudioFlinger::MmapThread::onFirstRef()
9589{
9590 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9591}
9592
9593void AudioFlinger::MmapThread::disconnect()
9594{
Eric Laurent331679c2018-04-16 17:03:16 -07009595 ActiveTracks<MmapTrack> activeTracks;
9596 {
9597 Mutex::Autolock _l(mLock);
9598 for (const sp<MmapTrack> &t : mActiveTracks) {
9599 activeTracks.add(t);
9600 }
9601 }
9602 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009603 stop(t->portId());
9604 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009605 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009606 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009607 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009608 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009609 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009610 }
9611}
9612
9613
9614void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9615 audio_stream_type_t streamType __unused,
9616 audio_session_t sessionId,
9617 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009618 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009619 audio_port_handle_t portId)
9620{
9621 mAttr = *attr;
9622 mSessionId = sessionId;
9623 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009624 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009625 mPortId = portId;
9626}
9627
9628status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9629 struct audio_mmap_buffer_info *info)
9630{
9631 if (mHalStream == 0) {
9632 return NO_INIT;
9633 }
Eric Laurent18b57012017-02-13 16:23:52 -08009634 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009635 return mHalStream->createMmapBuffer(minSizeFrames, info);
9636}
9637
9638status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9639{
9640 if (mHalStream == 0) {
9641 return NO_INIT;
9642 }
9643 return mHalStream->getMmapPosition(position);
9644}
9645
Eric Laurent331679c2018-04-16 17:03:16 -07009646status_t AudioFlinger::MmapThread::exitStandby()
9647{
9648 status_t ret = mHalStream->start();
9649 if (ret != NO_ERROR) {
9650 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9651 return ret;
9652 }
Andy Hungcf10d742020-04-28 15:38:24 -07009653 if (mStandby) {
9654 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009655 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009656 mStandby = false;
9657 }
Eric Laurent331679c2018-04-16 17:03:16 -07009658 return NO_ERROR;
9659}
9660
Eric Laurenta54f1282017-07-01 19:39:32 -07009661status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009662 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009663 audio_port_handle_t *handle)
9664{
Eric Laurenta54f1282017-07-01 19:39:32 -07009665 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009666 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009667 if (mHalStream == 0) {
9668 return NO_INIT;
9669 }
9670
9671 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009672
Eric Laurenta54f1282017-07-01 19:39:32 -07009673 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009674 // For the first track, reuse portId and session allocated when the stream was opened.
9675 ret = exitStandby();
9676 if (ret == NO_ERROR) {
9677 acquireWakeLock();
9678 }
9679 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009680 }
9681
9682 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9683
9684 audio_io_handle_t io = mId;
9685 if (isOutput()) {
9686 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9687 config.sample_rate = mSampleRate;
9688 config.channel_mask = mChannelMask;
9689 config.format = mFormat;
9690 audio_stream_type_t stream = streamType();
9691 audio_output_flags_t flags =
9692 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009693 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009694 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009695 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009696 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9697 mSessionId,
9698 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009699 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009700 &config,
9701 flags,
9702 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009703 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009704 &secondaryOutputs,
9705 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009706 ALOGD_IF(!secondaryOutputs.empty(),
9707 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009708 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009709 audio_config_base_t config;
9710 config.sample_rate = mSampleRate;
9711 config.channel_mask = mChannelMask;
9712 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009713 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009714 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009715 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009716 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009717 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009718 &config,
9719 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9720 &deviceId,
9721 &portId);
9722 }
9723 // APM should not chose a different input or output stream for the same set of attributes
9724 // and audo configuration
9725 if (ret != NO_ERROR || io != mId) {
9726 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9727 __FUNCTION__, ret, io, mId);
9728 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009729 }
9730
9731 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009732 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009733 } else {
jiabincfc10a42022-06-15 19:26:01 +00009734 {
9735 // Add the track record before starting input so that the silent status for the
9736 // client can be cached.
9737 Mutex::Autolock _l(mLock);
9738 setClientSilencedState_l(portId, false /*silenced*/);
9739 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009740 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009741 }
9742
Eric Laurent331679c2018-04-16 17:03:16 -07009743 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009744 // abort if start is rejected by audio policy manager
9745 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009746 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009747 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009748 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009749 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009750 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009751 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009752 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009753 }
Eric Laurent331679c2018-04-16 17:03:16 -07009754 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009755 } else {
9756 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009757 }
jiabincfc10a42022-06-15 19:26:01 +00009758 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009759 return PERMISSION_DENIED;
9760 }
9761
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009762 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009763 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009764 mChannelMask, mSessionId, isOutput(),
9765 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009766 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +00009767 if (!isOutput()) {
9768 track->setSilenced_l(isClientSilenced_l(portId));
9769 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009770
Eric Laurent4eb58f12018-12-07 16:41:02 -08009771 if (isOutput()) {
9772 // force volume update when a new track is added
9773 mHalVolFloat = -1.0f;
9774 } else if (!track->isSilenced_l()) {
9775 for (const sp<MmapTrack> &t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -07009776 if (t->isSilenced_l()
9777 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009778 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -07009779 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009780 }
9781 }
9782
9783
Eric Laurent6acd1d42017-01-04 14:23:29 -08009784 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009785 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009786 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009787 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009788 chain->incTrackCnt();
9789 chain->incActiveTrackCnt();
9790 }
9791
Andy Hungc2b11cb2020-04-22 09:04:01 -07009792 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009793 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009794 broadcast_l();
9795
Eric Laurenta54f1282017-07-01 19:39:32 -07009796 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009797
9798 return NO_ERROR;
9799}
9800
9801status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9802{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009803 ALOGV("%s handle %d", __FUNCTION__, handle);
9804
9805 if (mHalStream == 0) {
9806 return NO_INIT;
9807 }
9808
Eric Laurenta54f1282017-07-01 19:39:32 -07009809 if (handle == mPortId) {
9810 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009811 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009812 return NO_ERROR;
9813 }
9814
Eric Laurent331679c2018-04-16 17:03:16 -07009815 Mutex::Autolock _l(mLock);
9816
Eric Laurent6acd1d42017-01-04 14:23:29 -08009817 sp<MmapTrack> track;
9818 for (const sp<MmapTrack> &t : mActiveTracks) {
9819 if (handle == t->portId()) {
9820 track = t;
9821 break;
9822 }
9823 }
9824 if (track == 0) {
9825 return BAD_VALUE;
9826 }
9827
9828 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +00009829 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009830
Eric Laurent331679c2018-04-16 17:03:16 -07009831 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009832 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009833 AudioSystem::stopOutput(track->portId());
9834 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009835 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009836 AudioSystem::stopInput(track->portId());
9837 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009838 }
Eric Laurent331679c2018-04-16 17:03:16 -07009839 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009840
9841 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9842 if (chain != 0) {
9843 chain->decActiveTrackCnt();
9844 chain->decTrackCnt();
9845 }
9846
9847 broadcast_l();
9848
Eric Laurent6acd1d42017-01-04 14:23:29 -08009849 return NO_ERROR;
9850}
9851
Eric Laurent18b57012017-02-13 16:23:52 -08009852status_t AudioFlinger::MmapThread::standby()
9853{
9854 ALOGV("%s", __FUNCTION__);
9855
9856 if (mHalStream == 0) {
9857 return NO_INIT;
9858 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009859 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009860 return INVALID_OPERATION;
9861 }
9862 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009863 if (!mStandby) {
9864 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009865 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009866 mStandby = true;
9867 }
Eric Laurent18b57012017-02-13 16:23:52 -08009868 releaseWakeLock();
9869 return NO_ERROR;
9870}
9871
Eric Laurent6acd1d42017-01-04 14:23:29 -08009872
9873void AudioFlinger::MmapThread::readHalParameters_l()
9874{
9875 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9876 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9877 mFormat = mHALFormat;
9878 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9879 result = mHalStream->getFrameSize(&mFrameSize);
9880 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009881 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9882 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009883 result = mHalStream->getBufferSize(&mBufferSize);
9884 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9885 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009886
Andy Hungcf10d742020-04-28 15:38:24 -07009887 // TODO: make a readHalParameters call?
9888 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009889 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9890 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9891 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9892 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9893 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9894 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9895 /*
9896 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9897 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9898 (int32_t)mHapticChannelMask)
9899 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9900 (int32_t)mHapticChannelCount)
9901 */
9902 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9903 formatToString(mHALFormat).c_str())
9904 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9905 (int32_t)mFrameCount) // sic - added HAL
9906 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009907}
9908
9909bool AudioFlinger::MmapThread::threadLoop()
9910{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009911 checkSilentMode_l();
9912
9913 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9914
9915 while (!exitPending())
9916 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009917 Vector< sp<EffectChain> > effectChains;
9918
Andy Hung13850be2019-03-14 11:33:09 -07009919 { // under Thread lock
9920 Mutex::Autolock _l(mLock);
9921
Eric Laurent6acd1d42017-01-04 14:23:29 -08009922 if (mSignalPending) {
9923 // A signal was raised while we were unlocked
9924 mSignalPending = false;
9925 } else {
9926 if (mConfigEvents.isEmpty()) {
9927 // we're about to wait, flush the binder command buffer
9928 IPCThreadState::self()->flushCommands();
9929
9930 if (exitPending()) {
9931 break;
9932 }
9933
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009935 ALOGV("%s going to sleep", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009936 mWaitWorkCV.wait(mLock);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009937 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009938
9939 checkSilentMode_l();
9940
9941 continue;
9942 }
9943 }
9944
9945 processConfigEvents_l();
9946
9947 processVolume_l();
9948
9949 checkInvalidTracks_l();
9950
9951 mActiveTracks.updatePowerState(this);
9952
Kevin Rocard069c2712018-03-29 19:09:14 -07009953 updateMetadata_l();
9954
Eric Laurent6acd1d42017-01-04 14:23:29 -08009955 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009956 } // release Thread lock
9957
Eric Laurent6acd1d42017-01-04 14:23:29 -08009958 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009959 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009960 }
Andy Hung13850be2019-03-14 11:33:09 -07009961
9962 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963 unlockEffectChains(effectChains);
9964 // Effect chains will be actually deleted here if they were removed from
9965 // mEffectChains list during mixing or effects processing
9966 }
9967
9968 threadLoop_exit();
9969
9970 if (!mStandby) {
9971 threadLoop_standby();
9972 mStandby = true;
9973 }
9974
Eric Laurent6acd1d42017-01-04 14:23:29 -08009975 ALOGV("Thread %p type %d exiting", this, mType);
9976 return false;
9977}
9978
9979// checkForNewParameter_l() must be called with ThreadBase::mLock held
9980bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9981 status_t& status)
9982{
9983 AudioParameter param = AudioParameter(keyValuePair);
9984 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009985 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009986 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009987 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009989 if (sendToHal) {
9990 status = mHalStream->setParameters(keyValuePair);
9991 } else {
9992 status = NO_ERROR;
9993 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009994
9995 return false;
9996}
9997
9998String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9999{
10000 Mutex::Autolock _l(mLock);
10001 String8 out_s8;
10002 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10003 return out_s8;
10004 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010005 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006}
10007
Mikhail Naganov88536df2021-07-26 17:30:29 -070010008void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010009 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010010 sp<AudioIoDescriptor> desc;
10011 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010012 switch (event) {
10013 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010014 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010015 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010016 isInput = true;
10017 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010018 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010019 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010020 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010021 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10022 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010023 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010024 case AUDIO_INPUT_CLOSED:
10025 case AUDIO_OUTPUT_CLOSED:
10026 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010027 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010028 break;
10029 }
10030 mAudioFlinger->ioConfigChanged(event, desc, pid);
10031}
10032
10033status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10034 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010035NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010036{
10037 status_t status = NO_ERROR;
10038
10039 // store new device and send to effects
10040 audio_devices_t type = AUDIO_DEVICE_NONE;
10041 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010042 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10043 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10044 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010045 if (isOutput()) {
10046 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010047 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10048 && !mAudioHwDev->supportsAudioPatches(),
10049 "Enumerated device type(%#x) must not be used "
10050 "as it does not support audio patches",
10051 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010052 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010053 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10054 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 }
10056 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010057 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058 } else {
10059 type = patch->sources[0].ext.device.type;
10060 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010061 numDevices = mPatch.num_sources;
10062 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010063 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010064 }
10065
10066 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010067 if (isOutput()) {
10068 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10069 } else {
10070 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10071 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010072 }
10073
jiabinc52b1ff2019-10-31 17:20:42 -070010074 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010075 // store new source and send to effects
10076 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10077 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10078 for (size_t i = 0; i < mEffectChains.size(); i++) {
10079 mEffectChains[i]->setAudioSource_l(mAudioSource);
10080 }
10081 }
10082 }
10083
10084 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010085 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10086 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010087 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010088 audio_port_config port;
10089 std::optional<audio_source_t> source;
10090 if (isOutput()) {
10091 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010092 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010093 port = patch->sources[0];
10094 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010095 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010096 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010097 *handle = AUDIO_PATCH_HANDLE_NONE;
10098 }
10099
jiabinc52b1ff2019-10-31 17:20:42 -070010100 if (numDevices == 0 || mDeviceId != deviceId) {
10101 if (isOutput()) {
10102 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10103 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010104 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010105 } else {
10106 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10107 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10108 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010109 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010110 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010111 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010112 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010113 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010114 }
jiabinc52b1ff2019-10-31 17:20:42 -070010115 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010116 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010117 }
10118 return status;
10119}
10120
10121status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10122{
10123 status_t status = NO_ERROR;
10124
jiabinc52b1ff2019-10-31 17:20:42 -070010125 mPatch = audio_patch{};
10126 mOutDeviceTypeAddrs.clear();
10127 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010128
10129 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10130 supportsAudioPatches : false;
10131
10132 if (supportsAudioPatches) {
10133 status = mHalDevice->releaseAudioPatch(handle);
10134 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010135 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010136 }
10137 return status;
10138}
10139
Mikhail Naganovdc769682018-05-04 15:34:08 -070010140void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010142 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143 if (isOutput()) {
10144 config->role = AUDIO_PORT_ROLE_SOURCE;
10145 config->ext.mix.hw_module = mAudioHwDev->handle();
10146 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10147 } else {
10148 config->role = AUDIO_PORT_ROLE_SINK;
10149 config->ext.mix.hw_module = mAudioHwDev->handle();
10150 config->ext.mix.usecase.source = mAudioSource;
10151 }
10152}
10153
10154status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10155{
10156 audio_session_t session = chain->sessionId();
10157
10158 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10159 // Attach all tracks with same session ID to this chain.
10160 // indicate all active tracks in the chain
10161 for (const sp<MmapTrack> &track : mActiveTracks) {
10162 if (session == track->sessionId()) {
10163 chain->incTrackCnt();
10164 chain->incActiveTrackCnt();
10165 }
10166 }
10167
10168 chain->setThread(this);
10169 chain->setInBuffer(nullptr);
10170 chain->setOutBuffer(nullptr);
10171 chain->syncHalEffectsState();
10172
10173 mEffectChains.add(chain);
10174 checkSuspendOnAddEffectChain_l(chain);
10175 return NO_ERROR;
10176}
10177
10178size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10179{
10180 audio_session_t session = chain->sessionId();
10181
10182 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10183
10184 for (size_t i = 0; i < mEffectChains.size(); i++) {
10185 if (chain == mEffectChains[i]) {
10186 mEffectChains.removeAt(i);
10187 // detach all active tracks from the chain
10188 // detach all tracks with same session ID from this chain
10189 for (const sp<MmapTrack> &track : mActiveTracks) {
10190 if (session == track->sessionId()) {
10191 chain->decActiveTrackCnt();
10192 chain->decTrackCnt();
10193 }
10194 }
10195 break;
10196 }
10197 }
10198 return mEffectChains.size();
10199}
10200
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201void AudioFlinger::MmapThread::threadLoop_standby()
10202{
10203 mHalStream->standby();
10204}
10205
10206void AudioFlinger::MmapThread::threadLoop_exit()
10207{
Phil Burk7dce7282017-09-27 13:51:41 -070010208 // Do not call callback->onTearDown() because it is redundant for thread exit
10209 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010210}
10211
Andy Hung068e08e2023-05-15 19:02:55 -070010212status_t AudioFlinger::MmapThread::setSyncEvent(const sp<audioflinger::SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213{
10214 return BAD_VALUE;
10215}
10216
Andy Hung068e08e2023-05-15 19:02:55 -070010217bool AudioFlinger::MmapThread::isValidSyncEvent(
10218 const sp<audioflinger::SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010219{
10220 return false;
10221}
10222
10223status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10224 const effect_descriptor_t *desc, audio_session_t sessionId)
10225{
10226 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010227 if (audio_is_global_session(sessionId)) {
10228 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 desc->name, mThreadName);
10230 return BAD_VALUE;
10231 }
10232
10233 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10234 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10235 desc->name);
10236 return BAD_VALUE;
10237 }
10238 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010239 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10240 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241 return BAD_VALUE;
10242 }
10243
10244 // Only allow effects without processing load or latency
10245 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10246 return BAD_VALUE;
10247 }
10248
jiabineb3bda02020-06-30 14:07:03 -070010249 if (EffectModule::isHapticGenerator(&desc->type)) {
10250 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10251 return BAD_VALUE;
10252 }
10253
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255}
10256
10257void AudioFlinger::MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010258NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010259{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010260 sp<MmapStreamCallback> callback;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261 for (const sp<MmapTrack> &track : mActiveTracks) {
10262 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010263 callback = mCallback.promote();
10264 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10265 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010266 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010267 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010268 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 }
10270 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010271 if (callback != 0) {
10272 mLock.unlock();
10273 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10274 mLock.lock();
10275 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276}
10277
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010278void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010280 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10281 mAttr.content_type, mAttr.usage, mAttr.source);
10282 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010283 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010284 dprintf(fd, " No active clients\n");
10285 }
10286}
10287
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010288void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010292 dprintf(fd, " %zu Tracks\n", numtracks);
10293 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010295 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010296 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010297 for (size_t i = 0; i < numtracks ; ++i) {
10298 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010299 result.append(prefix);
10300 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010301 }
10302 } else {
10303 dprintf(fd, "\n");
10304 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010305 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010306}
10307
10308AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10309 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010310 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010311 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010312 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010313 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314{
10315 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10316 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10317 mMasterVolume = audioFlinger->masterVolume_l();
10318 mMasterMute = audioFlinger->masterMute_l();
Eric Laurentbc02c6b2023-07-03 18:14:07 +020010319
10320 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10321 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10322 mStreamTypes[stream].volume = 0.0f;
10323 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
10324 }
10325 // Audio patch and call assistant volume are always max
10326 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10327 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10328 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10329 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10330
Eric Laurent6acd1d42017-01-04 14:23:29 -080010331 if (mAudioHwDev) {
10332 if (mAudioHwDev->canSetMasterVolume()) {
10333 mMasterVolume = 1.0;
10334 }
10335
10336 if (mAudioHwDev->canSetMasterMute()) {
10337 mMasterMute = false;
10338 }
10339 }
10340}
10341
10342void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10343 audio_stream_type_t streamType,
10344 audio_session_t sessionId,
10345 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010346 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010347 audio_port_handle_t portId)
10348{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010349 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 mStreamType = streamType;
10351}
10352
10353AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10354{
10355 Mutex::Autolock _l(mLock);
10356 AudioStreamOut *output = mOutput;
10357 mOutput = NULL;
10358 return output;
10359}
10360
10361void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10362{
10363 Mutex::Autolock _l(mLock);
10364 // Don't apply master volume in SW if our HAL can do it for us.
10365 if (mAudioHwDev &&
10366 mAudioHwDev->canSetMasterVolume()) {
10367 mMasterVolume = 1.0;
10368 } else {
10369 mMasterVolume = value;
10370 }
10371}
10372
10373void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10374{
10375 Mutex::Autolock _l(mLock);
10376 // Don't apply master mute in SW if our HAL can do it for us.
10377 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10378 mMasterMute = false;
10379 } else {
10380 mMasterMute = muted;
10381 }
10382}
10383
10384void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10385{
10386 Mutex::Autolock _l(mLock);
Eric Laurentbc02c6b2023-07-03 18:14:07 +020010387 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010389 broadcast_l();
10390 }
10391}
10392
10393float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10394{
10395 Mutex::Autolock _l(mLock);
Eric Laurentbc02c6b2023-07-03 18:14:07 +020010396 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397}
10398
10399void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10400{
10401 Mutex::Autolock _l(mLock);
Eric Laurentbc02c6b2023-07-03 18:14:07 +020010402 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010403 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010404 broadcast_l();
10405 }
10406}
10407
10408void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10409{
10410 Mutex::Autolock _l(mLock);
10411 if (streamType == mStreamType) {
10412 for (const sp<MmapTrack> &track : mActiveTracks) {
10413 track->invalidate();
10414 }
10415 broadcast_l();
10416 }
10417}
10418
10419void AudioFlinger::MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010420NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421{
10422 float volume;
10423
Eric Laurentbc02c6b2023-07-03 18:14:07 +020010424 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010425 volume = 0;
10426 } else {
Eric Laurentbc02c6b2023-07-03 18:14:07 +020010427 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428 }
10429
10430 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010431 // Convert volumes from float to 8.24
10432 uint32_t vol = (uint32_t)(volume * (1 << 24));
10433
10434 // Delegate volume control to effect in track effect chain if needed
10435 // only one effect chain can be present on DirectOutputThread, so if
10436 // there is one, the track is connected to it
10437 if (!mEffectChains.isEmpty()) {
10438 mEffectChains[0]->setVolume_l(&vol, &vol);
10439 volume = (float)vol / (1 << 24);
10440 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010441 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010442 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10443 mHalVolFloat = volume; // HW volume control worked, so update value.
10444 mNoCallbackWarningCount = 0;
10445 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010446 sp<MmapStreamCallback> callback = mCallback.promote();
10447 if (callback != 0) {
10448 int channelCount;
10449 if (isOutput()) {
10450 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10451 } else {
10452 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10453 }
10454 Vector<float> values;
10455 for (int i = 0; i < channelCount; i++) {
10456 values.add(volume);
10457 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010458 mHalVolFloat = volume; // SW volume control worked, so update value.
10459 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010460 mLock.unlock();
10461 callback->onVolumeChanged(mChannelMask, values);
10462 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010463 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010464 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10465 ALOGW("Could not set MMAP stream volume: no volume callback!");
10466 mNoCallbackWarningCount++;
10467 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010470 for (const sp<MmapTrack> &track : mActiveTracks) {
10471 track->setMetadataHasChanged();
10472 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010473 }
10474}
10475
Kevin Rocard069c2712018-03-29 19:09:14 -070010476void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10477{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010478 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10479 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010480 }
10481 StreamOutHalInterface::SourceMetadata metadata;
10482 for (const sp<MmapTrack> &track : mActiveTracks) {
10483 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010484 playback_track_metadata_v7_t trackMetadata;
10485 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010486 .usage = track->attributes().usage,
10487 .content_type = track->attributes().content_type,
10488 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010489 };
10490 trackMetadata.channel_mask = track->channelMask(),
10491 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10492 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010493 }
10494 mOutput->stream->updateSourceMetadata(metadata);
10495}
10496
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10498{
10499 if (!mMasterMute) {
10500 char value[PROPERTY_VALUE_MAX];
10501 if (property_get("ro.audio.silent", value, "0") > 0) {
10502 char *endptr;
10503 unsigned long ul = strtoul(value, &endptr, 0);
10504 if (*endptr == '\0' && ul != 0) {
10505 ALOGD("Silence is golden");
10506 // The setprop command will not allow a property to be changed after
10507 // the first time it is set, so we don't have to worry about un-muting.
10508 setMasterMute_l(true);
10509 }
10510 }
10511 }
10512}
10513
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010514void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10515{
10516 MmapThread::toAudioPortConfig(config);
10517 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10518 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10519 config->flags.output = mOutput->flags;
10520 }
10521}
10522
jiabinb7d8c5a2020-08-26 17:24:52 -070010523status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10524 int64_t *timeNanos)
10525{
10526 if (mOutput == nullptr) {
10527 return NO_INIT;
10528 }
10529 struct timespec timestamp;
10530 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10531 if (status == NO_ERROR) {
10532 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10533 }
10534 return status;
10535}
10536
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010537void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010538{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010539 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010540
Glenn Kastend3bb6452016-12-05 18:14:37 -080010541 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurentbc02c6b2023-07-03 18:14:07 +020010542 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010543 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10544}
10545
10546AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10547 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010548 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010549 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550 mInput(input)
10551{
10552 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10553 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10554}
10555
Eric Laurent331679c2018-04-16 17:03:16 -070010556status_t AudioFlinger::MmapCaptureThread::exitStandby()
10557{
Phil Burkf054fc32018-12-06 09:45:59 -080010558 {
10559 // mInput might have been cleared by clearInput()
10560 Mutex::Autolock _l(mLock);
10561 if (mInput != nullptr && mInput->stream != nullptr) {
10562 mInput->stream->setGain(1.0f);
10563 }
10564 }
Eric Laurent331679c2018-04-16 17:03:16 -070010565 return MmapThread::exitStandby();
10566}
10567
Eric Laurent6acd1d42017-01-04 14:23:29 -080010568AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10569{
10570 Mutex::Autolock _l(mLock);
10571 AudioStreamIn *input = mInput;
10572 mInput = NULL;
10573 return input;
10574}
Kevin Rocard069c2712018-03-29 19:09:14 -070010575
Eric Laurent331679c2018-04-16 17:03:16 -070010576
10577void AudioFlinger::MmapCaptureThread::processVolume_l()
10578{
10579 bool changed = false;
10580 bool silenced = false;
10581
10582 sp<MmapStreamCallback> callback = mCallback.promote();
10583 if (callback == 0) {
10584 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10585 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10586 mNoCallbackWarningCount++;
10587 }
10588 }
10589
10590 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10591 // track is silenced and unmute otherwise
10592 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10593 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10594 changed = true;
10595 silenced = mActiveTracks[i]->isSilenced_l();
10596 }
10597 }
10598
10599 if (changed) {
10600 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10601 }
10602}
10603
Kevin Rocard069c2712018-03-29 19:09:14 -070010604void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10605{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010606 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10607 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010608 }
10609 StreamInHalInterface::SinkMetadata metadata;
10610 for (const sp<MmapTrack> &track : mActiveTracks) {
10611 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010612 record_track_metadata_v7_t trackMetadata;
10613 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010614 .source = track->attributes().source,
10615 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010616 };
10617 trackMetadata.channel_mask = track->channelMask(),
10618 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10619 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010620 }
10621 mInput->stream->updateSinkMetadata(metadata);
10622}
10623
Eric Laurent5ada82e2019-08-29 17:53:54 -070010624void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010625{
10626 Mutex::Autolock _l(mLock);
10627 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010628 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010629 mActiveTracks[i]->setSilenced_l(silenced);
10630 broadcast_l();
10631 }
10632 }
jiabincfc10a42022-06-15 19:26:01 +000010633 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010634}
10635
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010636void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10637{
10638 MmapThread::toAudioPortConfig(config);
10639 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10640 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10641 config->flags.input = mInput->flags;
10642 }
10643}
10644
jiabinb7d8c5a2020-08-26 17:24:52 -070010645status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10646 uint64_t *position, int64_t *timeNanos)
10647{
10648 if (mInput == nullptr) {
10649 return NO_INIT;
10650 }
10651 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10652}
10653
Glenn Kasten63238ef2015-03-02 15:50:29 -080010654} // namespace android