blob: 7f7b8aecb8eb4f44972ecc34eae65d44ccc738b8 [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"
Eric Laurent81784c32012-11-19 14:55:58 -080077#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070078#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070079#include <mediautils/SchedulingPolicyService.h>
80#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080081
Eric Laurent81784c32012-11-19 14:55:58 -080082#ifdef ADD_BATTERY_DATA
83#include <media/IMediaPlayerService.h>
84#include <media/IMediaDeathNotifier.h>
85#endif
86
Eric Laurent81784c32012-11-19 14:55:58 -080087#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070088#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080089#include <cpustats/ThreadCpuUsage.h>
90#endif
91
Glenn Kastenc05b8d72016-03-24 09:48:17 -070092#include "AutoPark.h"
93
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080094#include <pthread.h>
Andy Hungb776e372023-05-24 11:53:47 -070095#include <afutils/TypedLogger.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096
Eric Laurent81784c32012-11-19 14:55:58 -080097// ----------------------------------------------------------------------------
98
99// Note: the following macro is used for extremely verbose logging message. In
100// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
101// 0; but one side effect of this is to turn all LOGV's as well. Some messages
102// are so verbose that we want to suppress them even when we have ALOG_ASSERT
103// turned on. Do not uncomment the #def below unless you really know what you
104// are doing and want to see all of the extremely verbose messages.
105//#define VERY_VERY_VERBOSE_LOGGING
106#ifdef VERY_VERY_VERBOSE_LOGGING
107#define ALOGVV ALOGV
108#else
109#define ALOGVV(a...) do { } while(0)
110#endif
111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115template <typename T>
116static inline T min(const T& a, const T& b)
117{
118 return a < b ? a : b;
119}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700120
Eric Laurent81784c32012-11-19 14:55:58 -0800121namespace android {
122
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700123using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000124using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700125
Eric Laurent81784c32012-11-19 14:55:58 -0800126// retry counts for buffer fill timeout
127// 50 * ~20msecs = 1 second
128static const int8_t kMaxTrackRetries = 50;
129static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700130
Eric Laurent81784c32012-11-19 14:55:58 -0800131// allow less retry attempts on direct output thread.
132// direct outputs can be a scarce resource in audio hardware and should
133// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700134// Notes:
135// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
136// in case the data write is bursty for the AudioTrack. The application
137// should endeavor to write at least once every kMaxTrackRetriesDirectMs
138// to prevent an underrun situation. If the data is bursty, then
139// the application can also throttle the data sent to be even.
140// 2) For compressed audio data, any data present in the AudioTrack buffer
141// will be sent and reset the retry count. This delivers data as
142// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
143// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
144// of data to be available, then any remaining data is delivered.
145// This is required to ensure the last bit of data is delivered before underrun.
146//
147// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
148// or the size of the HAL period for proportional / linear PCM tracks.
149static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800150
151// don't warn about blocked writes or record buffer overflows more often than this
152static const nsecs_t kWarningThrottleNs = seconds(5);
153
154// RecordThread loop sleep time upon application overrun or audio HAL read error
155static const int kRecordThreadSleepUs = 5000;
156
Eric Laurent10351942014-05-08 18:49:52 -0700157// maximum time to wait in sendConfigEvent_l() for a status to be received
158static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800159
160// minimum sleep time for the mixer thread loop when tracks are active but in underrun
161static const uint32_t kMinThreadSleepTimeUs = 5000;
162// maximum divider applied to the active sleep time in the mixer thread loop
163static const uint32_t kMaxThreadSleepTimeShift = 2;
164
Andy Hung09a50072014-02-27 14:30:47 -0800165// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700166// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800167static const uint32_t kMinNormalSinkBufferSizeMs = 20;
168// maximum normal sink buffer size
169static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800170
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700171// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
172// FIXME This should be based on experimentally observed scheduling jitter
173static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
174
Eric Laurent972a1732013-09-04 09:42:59 -0700175// Offloaded output thread standby delay: allows track transition without going to standby
176static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
177
Eric Laurent51716182016-02-29 18:00:56 -0800178// Direct output thread minimum sleep time in idle or active(underrun) state
179static const nsecs_t kDirectMinSleepTimeUs = 10000;
180
Brian Lindahl9e661ad2022-07-27 18:01:07 +0200181// Minimum amount of time between checking to see if the timestamp is advancing
182// for underrun detection. If we check too frequently, we may not detect a
183// timestamp update and will falsely detect underrun.
184static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
185
Glenn Kasten1b291842016-07-18 14:55:21 -0700186// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
187// balance between power consumption and latency, and allows threads to be scheduled reliably
188// by the CFS scheduler.
189// FIXME Express other hardcoded references to 20ms with references to this constant and move
190// it appropriately.
191#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800192
Eric Laurent81784c32012-11-19 14:55:58 -0800193// Whether to use fast mixer
194static const enum {
195 FastMixer_Never, // never initialize or use: for debugging only
196 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
197 // normal mixer multiplier is 1
198 FastMixer_Static, // initialize if needed, then use all the time if initialized,
199 // multiplier is calculated based on min & max normal mixer buffer size
200 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
201 // multiplier is calculated based on min & max normal mixer buffer size
202 // FIXME for FastMixer_Dynamic:
203 // Supporting this option will require fixing HALs that can't handle large writes.
204 // For example, one HAL implementation returns an error from a large write,
205 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
206 // We could either fix the HAL implementations, or provide a wrapper that breaks
207 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
208} kUseFastMixer = FastMixer_Static;
209
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700210// Whether to use fast capture
211static const enum {
212 FastCapture_Never, // never initialize or use: for debugging only
213 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
214 FastCapture_Static, // initialize if needed, then use all the time if initialized
215} kUseFastCapture = FastCapture_Static;
216
Eric Laurent81784c32012-11-19 14:55:58 -0800217// Priorities for requestPriority
218static const int kPriorityAudioApp = 2;
219static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700220static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800221
Glenn Kastenea38ee72016-04-18 11:08:01 -0700222// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
223// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
224// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700225
226// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800227static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800228
Glenn Kasten03490092014-05-27 12:30:54 -0700229// The minimum and maximum allowed values
230static const int kFastTrackMultiplierMin = 1;
231static const int kFastTrackMultiplierMax = 2;
232
233// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
234static int sFastTrackMultiplier = kFastTrackMultiplier;
235
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700236// See Thread::readOnlyHeap().
237// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
238// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
239// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700240static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700241
Eric Laurent81784c32012-11-19 14:55:58 -0800242// ----------------------------------------------------------------------------
243
Andy Hungb68f5eb2019-12-03 16:49:17 -0800244// TODO: move all toString helpers to audio.h
245// under #ifdef __cplusplus #endif
246static std::string patchSinksToString(const struct audio_patch *patch)
247{
248 std::stringstream ss;
249 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700250 if (i > 0) {
251 ss << "|";
252 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800253 ss << "(" << toString(patch->sinks[i].ext.device.type)
254 << ", " << patch->sinks[i].ext.device.address << ")";
255 }
256 return ss.str();
257}
258
259static std::string patchSourcesToString(const struct audio_patch *patch)
260{
261 std::stringstream ss;
262 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700263 if (i > 0) {
264 ss << "|";
265 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800266 ss << "(" << toString(patch->sources[i].ext.device.type)
267 << ", " << patch->sources[i].ext.device.address << ")";
268 }
269 return ss.str();
270}
271
Andy Hung4bd53e72022-11-17 17:21:45 -0800272static std::string toString(audio_latency_mode_t mode) {
273 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganova77d5552022-12-18 02:48:14 +0000274 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
275 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800276}
277
278// Could be made a template, but other toString overloads for std::vector are confused.
279static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
280 std::string s("{ ");
281 for (const auto& e : elements) {
282 s.append(toString(e));
283 s.append(" ");
284 }
285 s.append("}");
286 return s;
287}
288
Glenn Kasten03490092014-05-27 12:30:54 -0700289static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
290
291static void sFastTrackMultiplierInit()
292{
293 char value[PROPERTY_VALUE_MAX];
294 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
295 char *endptr;
296 unsigned long ul = strtoul(value, &endptr, 0);
297 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
298 sFastTrackMultiplier = (int) ul;
299 }
300 }
301}
302
303// ----------------------------------------------------------------------------
304
Eric Laurent81784c32012-11-19 14:55:58 -0800305#ifdef ADD_BATTERY_DATA
306// To collect the amplifier usage
307static void addBatteryData(uint32_t params) {
308 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
309 if (service == NULL) {
310 // it already logged
311 return;
312 }
313
314 service->addBatteryData(params);
315}
316#endif
317
Andy Hung3f0c9022016-01-15 17:49:46 -0800318// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
319struct {
320 // call when you acquire a partial wakelock
321 void acquire(const sp<IBinder> &wakeLockToken) {
322 pthread_mutex_lock(&mLock);
323 if (wakeLockToken.get() == nullptr) {
324 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
325 } else {
326 if (mCount == 0) {
327 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
328 }
329 ++mCount;
330 }
331 pthread_mutex_unlock(&mLock);
332 }
333
334 // call when you release a partial wakelock.
335 void release(const sp<IBinder> &wakeLockToken) {
336 if (wakeLockToken.get() == nullptr) {
337 return;
338 }
339 pthread_mutex_lock(&mLock);
340 if (--mCount < 0) {
341 ALOGE("negative wakelock count");
342 mCount = 0;
343 }
344 pthread_mutex_unlock(&mLock);
345 }
346
347 // retrieves the boottime timebase offset from monotonic.
348 int64_t getBoottimeOffset() {
349 pthread_mutex_lock(&mLock);
350 int64_t boottimeOffset = mBoottimeOffset;
351 pthread_mutex_unlock(&mLock);
352 return boottimeOffset;
353 }
354
355 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
356 // and the selected timebase.
357 // Currently only TIMEBASE_BOOTTIME is allowed.
358 //
359 // This only needs to be called upon acquiring the first partial wakelock
360 // after all other partial wakelocks are released.
361 //
362 // We do an empirical measurement of the offset rather than parsing
363 // /proc/timer_list since the latter is not a formal kernel ABI.
364 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
365 int clockbase;
366 switch (timebase) {
367 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
368 clockbase = SYSTEM_TIME_BOOTTIME;
369 break;
370 default:
371 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
372 break;
373 }
374 // try three times to get the clock offset, choose the one
375 // with the minimum gap in measurements.
376 const int tries = 3;
Andy Hung71ba4b32022-10-06 12:09:49 -0700377 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800378 for (int i = 0; i < tries; ++i) {
379 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
380 const nsecs_t tbase = systemTime(clockbase);
381 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
382 const nsecs_t gap = tmono2 - tmono;
383 if (i == 0 || gap < bestGap) {
384 bestGap = gap;
385 measured = tbase - ((tmono + tmono2) >> 1);
386 }
387 }
388
389 // to avoid micro-adjusting, we don't change the timebase
390 // unless it is significantly different.
391 //
392 // Assumption: It probably takes more than toleranceNs to
393 // suspend and resume the device.
394 static int64_t toleranceNs = 10000; // 10 us
395 if (llabs(*offset - measured) > toleranceNs) {
396 ALOGV("Adjusting timebase offset old: %lld new: %lld",
397 (long long)*offset, (long long)measured);
398 *offset = measured;
399 }
400 }
401
402 pthread_mutex_t mLock;
403 int32_t mCount;
404 int64_t mBoottimeOffset;
405} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800406
407// ----------------------------------------------------------------------------
408// CPU Stats
409// ----------------------------------------------------------------------------
410
411class CpuStats {
412public:
413 CpuStats();
414 void sample(const String8 &title);
415#ifdef DEBUG_CPU_USAGE
416private:
417 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700418 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800419
Andy Hung16698b82018-08-01 10:48:38 -0700420 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800421
422 int mCpuNum; // thread's current CPU number
423 int mCpukHz; // frequency of thread's current CPU in kHz
424#endif
425};
426
427CpuStats::CpuStats()
428#ifdef DEBUG_CPU_USAGE
429 : mCpuNum(-1), mCpukHz(-1)
430#endif
431{
432}
433
Glenn Kasten0f11b512014-01-31 16:18:54 -0800434void CpuStats::sample(const String8 &title
435#ifndef DEBUG_CPU_USAGE
436 __unused
437#endif
438 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800439#ifdef DEBUG_CPU_USAGE
440 // get current thread's delta CPU time in wall clock ns
441 double wcNs;
442 bool valid = mCpuUsage.sampleAndEnable(wcNs);
443
444 // record sample for wall clock statistics
445 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700446 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800447 }
448
449 // get the current CPU number
450 int cpuNum = sched_getcpu();
451
452 // get the current CPU frequency in kHz
453 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
454
455 // check if either CPU number or frequency changed
456 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
457 mCpuNum = cpuNum;
458 mCpukHz = cpukHz;
459 // ignore sample for purposes of cycles
460 valid = false;
461 }
462
463 // if no change in CPU number or frequency, then record sample for cycle statistics
464 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700465 const double cycles = wcNs * cpukHz * 0.000001;
466 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800467 }
468
Eric Tan5b13ff82018-07-27 11:20:17 -0700469 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800470 // mCpuUsage.elapsed() is expensive, so don't call it every loop
471 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700472 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800473 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700474 const double perLoop = elapsed / (double) n;
475 const double perLoop100 = perLoop * 0.01;
476 const double perLoop1k = perLoop * 0.001;
477 const double mean = mWcStats.getMean();
478 const double stddev = mWcStats.getStdDev();
479 const double minimum = mWcStats.getMin();
480 const double maximum = mWcStats.getMax();
481 const double meanCycles = mHzStats.getMean();
482 const double stddevCycles = mHzStats.getStdDev();
483 const double minCycles = mHzStats.getMin();
484 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800485 mCpuUsage.resetElapsed();
486 mWcStats.reset();
487 mHzStats.reset();
488 ALOGD("CPU usage for %s over past %.1f secs\n"
489 " (%u mixer loops at %.1f mean ms per loop):\n"
490 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
491 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
492 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
493 title.string(),
494 elapsed * .000000001, n, perLoop * .000001,
495 mean * .001,
496 stddev * .001,
497 minimum * .001,
498 maximum * .001,
499 mean / perLoop100,
500 stddev / perLoop100,
501 minimum / perLoop100,
502 maximum / perLoop100,
503 meanCycles / perLoop1k,
504 stddevCycles / perLoop1k,
505 minCycles / perLoop1k,
506 maxCycles / perLoop1k);
507
508 }
509 }
510#endif
511};
512
513// ----------------------------------------------------------------------------
514// ThreadBase
515// ----------------------------------------------------------------------------
516
Glenn Kasten97b7b752014-09-28 13:04:24 -0700517// static
518const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
519{
520 switch (type) {
521 case MIXER:
522 return "MIXER";
523 case DIRECT:
524 return "DIRECT";
525 case DUPLICATING:
526 return "DUPLICATING";
527 case RECORD:
528 return "RECORD";
529 case OFFLOAD:
530 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700531 case MMAP_PLAYBACK:
532 return "MMAP_PLAYBACK";
533 case MMAP_CAPTURE:
534 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200535 case SPATIALIZER:
536 return "SPATIALIZER";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700537 default:
538 return "unknown";
539 }
540}
541
Eric Laurent81784c32012-11-19 14:55:58 -0800542AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700543 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800544 : Thread(false /*canCallJava*/),
545 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700546 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700547 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
548 isOut),
549 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700550 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800551 // are set by PlaybackThread::readOutputParameters_l() or
552 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700553 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700554 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700555 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800556 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700557 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800558 mSystemReady(systemReady),
559 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800560{
Andy Hungcf10d742020-04-28 15:38:24 -0700561 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700562 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800563}
564
565AudioFlinger::ThreadBase::~ThreadBase()
566{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700567 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700568 mConfigEvents.clear();
569
Eric Laurent81784c32012-11-19 14:55:58 -0800570 // do not lock the mutex in destructor
571 releaseWakeLock_l();
572 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800573 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800574 binder->unlinkToDeath(mDeathRecipient);
575 }
Andy Hungd0979812019-02-21 15:51:44 -0800576
577 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800578}
579
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700580status_t AudioFlinger::ThreadBase::readyToRun()
581{
582 status_t status = initCheck();
583 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800584 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700585 } else {
586 ALOGE("No working audio driver found.");
587 }
588 return status;
589}
590
Eric Laurent81784c32012-11-19 14:55:58 -0800591void AudioFlinger::ThreadBase::exit()
592{
593 ALOGV("ThreadBase::exit");
594 // do any cleanup required for exit to succeed
595 preExit();
596 {
597 // This lock prevents the following race in thread (uniprocessor for illustration):
598 // if (!exitPending()) {
599 // // context switch from here to exit()
600 // // exit() calls requestExit(), what exitPending() observes
601 // // exit() calls signal(), which is dropped since no waiters
602 // // context switch back from exit() to here
603 // mWaitWorkCV.wait(...);
604 // // now thread is hung
605 // }
606 AutoMutex lock(mLock);
607 requestExit();
608 mWaitWorkCV.broadcast();
609 }
610 // When Thread::requestExitAndWait is made virtual and this method is renamed to
611 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
612 requestExitAndWait();
613}
614
615status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
616{
Eric Laurent81784c32012-11-19 14:55:58 -0800617 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
618 Mutex::Autolock _l(mLock);
619
Eric Laurent10351942014-05-08 18:49:52 -0700620 return sendSetParameterConfigEvent_l(keyValuePairs);
621}
622
623// sendConfigEvent_l() must be called with ThreadBase::mLock held
624// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
625status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-10-06 12:09:49 -0700626NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700627{
628 status_t status = NO_ERROR;
629
Eric Laurent72e3f392015-05-20 14:43:50 -0700630 if (event->mRequiresSystemReady && !mSystemReady) {
631 event->mWaitStatus = false;
632 mPendingConfigEvents.add(event);
633 return status;
634 }
Eric Laurent10351942014-05-08 18:49:52 -0700635 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700636 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800637 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700638 mLock.unlock();
639 {
640 Mutex::Autolock _l(event->mLock);
641 while (event->mWaitStatus) {
642 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
643 event->mStatus = TIMED_OUT;
644 event->mWaitStatus = false;
645 }
646 }
647 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800648 }
Eric Laurent10351942014-05-08 18:49:52 -0700649 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800650 return status;
651}
652
Mikhail Naganov88536df2021-07-26 17:30:29 -0700653void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700654 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
656 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700657 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800658}
659
660// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov88536df2021-07-26 17:30:29 -0700661void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700662 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800663{
Andy Hungd0979812019-02-21 15:51:44 -0800664 // The audio statistics history is exponentially weighted to forget events
665 // about five or more seconds in the past. In order to have
666 // crisper statistics for mediametrics, we reset the statistics on
667 // an IoConfigEvent, to reflect different properties for a new device.
668 mIoJitterMs.reset();
669 mLatencyMs.reset();
670 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000671 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100672 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800673
Eric Laurent09f1ed22019-04-24 17:45:17 -0700674 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700675 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800676}
677
Mikhail Naganov83f04272017-02-07 10:45:09 -0800678void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700679{
680 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800681 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700682}
683
Eric Laurent81784c32012-11-19 14:55:58 -0800684// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800685void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
686 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800687{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800688 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700689 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800690}
691
Eric Laurent10351942014-05-08 18:49:52 -0700692// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
693status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800694{
Andy Hung2ddee192015-12-18 17:34:44 -0800695 sp<ConfigEvent> configEvent;
696 AudioParameter param(keyValuePair);
697 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700698 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800699 setMasterMono_l(value != 0);
700 if (param.size() == 1) {
701 return NO_ERROR; // should be a solo parameter - we don't pass down
702 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700703 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800704 configEvent = new SetParameterConfigEvent(param.toString());
705 } else {
706 configEvent = new SetParameterConfigEvent(keyValuePair);
707 }
Eric Laurent10351942014-05-08 18:49:52 -0700708 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700709}
710
Eric Laurent1c333e22014-05-20 10:48:17 -0700711status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
712 const struct audio_patch *patch,
713 audio_patch_handle_t *handle)
714{
715 Mutex::Autolock _l(mLock);
716 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
717 status_t status = sendConfigEvent_l(configEvent);
718 if (status == NO_ERROR) {
719 CreateAudioPatchConfigEventData *data =
720 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
721 *handle = data->mHandle;
722 }
723 return status;
724}
725
726status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
727 const audio_patch_handle_t handle)
728{
729 Mutex::Autolock _l(mLock);
730 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
731 return sendConfigEvent_l(configEvent);
732}
733
jiabinc52b1ff2019-10-31 17:20:42 -0700734status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
735 const DeviceDescriptorBaseVector& outDevices)
736{
737 if (type() != RECORD) {
738 // The update out device operation is only for record thread.
739 return INVALID_OPERATION;
740 }
741 Mutex::Autolock _l(mLock);
742 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
743 return sendConfigEvent_l(configEvent);
744}
745
Eric Laurentec376dc2021-04-08 20:41:22 +0200746void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
747{
748 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
749 sp<ConfigEvent> configEvent =
750 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
751 sendConfigEvent_l(configEvent);
752}
Eric Laurent1c333e22014-05-20 10:48:17 -0700753
Eric Laurentb3f315a2021-07-13 15:09:05 +0200754void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
755{
756 Mutex::Autolock _l(mLock);
757 sendCheckOutputStageEffectsEvent_l();
758}
759
760void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
761{
762 sp<ConfigEvent> configEvent =
763 (ConfigEvent *)new CheckOutputStageEffectsEvent();
764 sendConfigEvent_l(configEvent);
765}
766
Eric Laurent6f9534f2022-05-03 18:15:04 +0200767void AudioFlinger::ThreadBase::sendHalLatencyModesChangedEvent_l()
768{
769 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
770 sendConfigEvent_l(configEvent);
771}
772
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700773// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700774void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700775{
Eric Laurent10351942014-05-08 18:49:52 -0700776 bool configChanged = false;
777
Eric Laurent81784c32012-11-19 14:55:58 -0800778 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700779 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700780 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800781 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700782 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700783 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700784 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
785 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800786 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700787 true /*asynchronous*/);
788 if (err != 0) {
789 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700790 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700791 }
792 } break;
793 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700794 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700795 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700796 } break;
797 case CFG_EVENT_SET_PARAMETER: {
798 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
799 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
800 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700801 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
802 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700803 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700804 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700805 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700806 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700807 CreateAudioPatchConfigEventData *data =
808 (CreateAudioPatchConfigEventData *)event->mData.get();
809 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700810 const DeviceTypeSet newDevices = getDeviceTypes();
811 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
812 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
813 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 } break;
815 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700816 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700817 ReleaseAudioPatchConfigEventData *data =
818 (ReleaseAudioPatchConfigEventData *)event->mData.get();
819 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700820 const DeviceTypeSet newDevices = getDeviceTypes();
821 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
822 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
823 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
824 } break;
825 case CFG_EVENT_UPDATE_OUT_DEVICE: {
826 UpdateOutDevicesConfigEventData *data =
827 (UpdateOutDevicesConfigEventData *)event->mData.get();
828 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700829 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200830 case CFG_EVENT_RESIZE_BUFFER: {
831 ResizeBufferConfigEventData *data =
832 (ResizeBufferConfigEventData *)event->mData.get();
833 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
834 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200835
836 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
837 setCheckOutputStageEffects();
838 } break;
839
Eric Laurent6f9534f2022-05-03 18:15:04 +0200840 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
841 onHalLatencyModesChanged_l();
842 } break;
843
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700844 default:
Eric Laurent10351942014-05-08 18:49:52 -0700845 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700846 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800847 }
Eric Laurent10351942014-05-08 18:49:52 -0700848 {
849 Mutex::Autolock _l(event->mLock);
850 if (event->mWaitStatus) {
851 event->mWaitStatus = false;
852 event->mCond.signal();
853 }
854 }
855 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
856 }
857
858 if (configChanged) {
859 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800860 }
Eric Laurent81784c32012-11-19 14:55:58 -0800861}
862
Marco Nelissenb2208842014-02-07 14:00:50 -0800863String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
864 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700865 const audio_channel_representation_t representation =
866 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700867
868 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800869 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700870 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
871 if (output) {
872 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
873 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
874 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700875 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700876 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
877 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
878 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
879 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
880 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
881 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
882 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
883 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
884 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
885 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
886 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
887 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700888 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
889 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
890 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
891 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
892 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
893 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
894 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700895 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700896 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
897 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700898 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
899 } else {
900 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
901 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
902 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
903 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
904 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
905 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
906 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
907 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
908 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
909 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
910 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
911 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700912 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
913 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
914 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700915 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700916 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
917 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700918 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
919 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
920 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
921 }
922 const int len = s.length();
923 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700924 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700925 s.unlockBuffer(len - 2); // remove trailing ", "
926 }
927 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800928 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700929 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
930 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
931 return s;
932 default:
933 s.appendFormat("unknown mask, representation:%d bits:%#x",
934 representation, audio_channel_mask_get_bits(mask));
935 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800936 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800937}
938
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700939void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-10-06 12:09:49 -0700940NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -0800941{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800942 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
943 this, mThreadName, getTid(), type(), threadTypeToString(type()));
944
Eric Laurent81784c32012-11-19 14:55:58 -0800945 bool locked = AudioFlinger::dumpTryLock(mLock);
946 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800947 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800948 }
949
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700950 dumpBase_l(fd, args);
951 dumpInternals_l(fd, args);
952 dumpTracks_l(fd, args);
953 dumpEffectChains_l(fd, args);
954
955 if (locked) {
956 mLock.unlock();
957 }
958
959 dprintf(fd, " Local log:\n");
960 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -0700961
962 // --all does the statistics
963 bool dumpAll = false;
964 for (const auto &arg : args) {
965 if (arg == String16("--all")) {
966 dumpAll = true;
967 }
968 }
969 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -0700970 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -0700971 if (!sched.empty()) {
972 (void)write(fd, sched.c_str(), sched.size());
973 }
974 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700975}
976
977void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
978{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700979 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700980 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700981 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700982 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700983 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700984 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700985 dprintf(fd, " Channel count: %u\n", mChannelCount);
986 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800987 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700988 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700989 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700990 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800991 size_t numConfig = mConfigEvents.size();
992 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700993 const size_t SIZE = 256;
994 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800995 for (size_t i = 0; i < numConfig; i++) {
996 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700997 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800998 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700999 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001000 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001001 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001002 }
Andy Hung293558a2017-03-21 12:19:20 -07001003 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001004 dprintf(fd, " Output devices: %s (%s)\n",
1005 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1006 dprintf(fd, " Input device: %#x (%s)\n",
1007 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001008 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001009
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001010 // Dump timestamp statistics for the Thread types that support it.
1011 if (mType == RECORD
1012 || mType == MIXER
1013 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001014 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001015 || mType == OFFLOAD
1016 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001017 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001018 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001019 }
1020
Andy Hung446f4df2019-02-21 12:26:41 -08001021 if (mLastIoBeginNs > 0) { // MMAP may not set this
1022 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1023 isOutput() ? "write" : "read",
1024 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1025 }
1026
1027 if (mProcessTimeMs.getN() > 0) {
1028 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1029 }
1030
1031 if (mIoJitterMs.getN() > 0) {
1032 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1033 isOutput() ? "write" : "read",
1034 mIoJitterMs.toString().c_str());
1035 }
1036
Andy Hunge6c37112019-02-26 17:38:10 -08001037 if (mLatencyMs.getN() > 0) {
1038 dprintf(fd, " Threadloop %s latency stats: %s\n",
1039 isOutput() ? "write" : "read",
1040 mLatencyMs.toString().c_str());
1041 }
Robert Wu06db0a32021-08-10 19:05:34 +00001042
1043 if (mMonopipePipeDepthStats.getN() > 0) {
1044 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1045 isOutput() ? "write" : "read",
1046 mMonopipePipeDepthStats.toString().c_str());
1047 }
Eric Laurent81784c32012-11-19 14:55:58 -08001048}
1049
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001050void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001051{
1052 const size_t SIZE = 256;
1053 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001054
Marco Nelissenb2208842014-02-07 14:00:50 -08001055 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001056 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001057 write(fd, buffer, strlen(buffer));
1058
Marco Nelissenb2208842014-02-07 14:00:50 -08001059 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001060 sp<EffectChain> chain = mEffectChains[i];
1061 if (chain != 0) {
1062 chain->dump(fd, args);
1063 }
1064 }
1065}
1066
Andy Hungdae27702016-10-31 14:01:16 -07001067void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001068{
1069 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001070 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001071}
1072
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001073String16 AudioFlinger::ThreadBase::getWakeLockTag()
1074{
1075 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001076 case MIXER:
1077 return String16("AudioMix");
1078 case DIRECT:
1079 return String16("AudioDirectOut");
1080 case DUPLICATING:
1081 return String16("AudioDup");
1082 case RECORD:
1083 return String16("AudioIn");
1084 case OFFLOAD:
1085 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001086 case MMAP_PLAYBACK:
1087 return String16("MmapPlayback");
1088 case MMAP_CAPTURE:
1089 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001090 case SPATIALIZER:
1091 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001092 default:
1093 ALOG_ASSERT(false);
1094 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001095 }
1096}
1097
Andy Hungdae27702016-10-31 14:01:16 -07001098void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001099{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001100 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001101 if (mPowerManager != 0) {
1102 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001103 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001104 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1105 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001106 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001107 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001108 {} /* workSource */,
1109 {} /* historyTag */);
1110 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001111 mWakeLockToken = binder;
1112 }
Chris Ye6597d732020-02-28 22:38:25 -08001113 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001114 }
Wei Jia3f273d12015-11-24 09:06:49 -08001115
Andy Hung3f0c9022016-01-15 17:49:46 -08001116 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001117 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1118 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001119}
1120
1121void AudioFlinger::ThreadBase::releaseWakeLock()
1122{
1123 Mutex::Autolock _l(mLock);
1124 releaseWakeLock_l();
1125}
1126
1127void AudioFlinger::ThreadBase::releaseWakeLock_l()
1128{
Andy Hung3f0c9022016-01-15 17:49:46 -08001129 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001130 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001131 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001132 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001133 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001134 }
1135 mWakeLockToken.clear();
1136 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001137}
1138
1139void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001140 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001141 // use checkService() to avoid blocking if power service is not up yet
1142 sp<IBinder> binder =
1143 defaultServiceManager()->checkService(String16("power"));
1144 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001145 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001146 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001147 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001148 binder->linkToDeath(mDeathRecipient);
1149 }
1150 }
1151}
1152
Andy Hungd01b0f12016-11-07 16:10:30 -08001153void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001154 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001155
1156#if !LOG_NDEBUG
1157 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001158 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001159 s << uid << " ";
1160 }
1161 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1162#endif
1163
Andy Hung438e7572015-12-14 15:51:17 -08001164 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1165 if (mSystemReady) {
1166 ALOGE("no wake lock to update, but system ready!");
1167 } else {
1168 ALOGW("no wake lock to update, system not ready yet");
1169 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001170 return;
1171 }
1172 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001173 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001174 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1175 mWakeLockToken, uidsAsInt);
1176 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001177 }
1178}
1179
Eric Laurent81784c32012-11-19 14:55:58 -08001180void AudioFlinger::ThreadBase::clearPowerManager()
1181{
1182 Mutex::Autolock _l(mLock);
1183 releaseWakeLock_l();
1184 mPowerManager.clear();
1185}
1186
jiabinc52b1ff2019-10-31 17:20:42 -07001187void AudioFlinger::ThreadBase::updateOutDevices(
1188 const DeviceDescriptorBaseVector& outDevices __unused)
1189{
1190 ALOGE("%s should only be called in RecordThread", __func__);
1191}
1192
Eric Laurentec376dc2021-04-08 20:41:22 +02001193void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1194{
1195 ALOGE("%s should only be called in RecordThread", __func__);
1196}
1197
Glenn Kasten0f11b512014-01-31 16:18:54 -08001198void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
1200 sp<ThreadBase> thread = mThread.promote();
1201 if (thread != 0) {
1202 thread->clearPowerManager();
1203 }
1204 ALOGW("power manager service died !!!");
1205}
1206
Eric Laurent81784c32012-11-19 14:55:58 -08001207void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001208 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001209{
1210 sp<EffectChain> chain = getEffectChain_l(sessionId);
1211 if (chain != 0) {
1212 if (type != NULL) {
1213 chain->setEffectSuspended_l(type, suspend);
1214 } else {
1215 chain->setEffectSuspendedAll_l(suspend);
1216 }
1217 }
1218
1219 updateSuspendedSessions_l(type, suspend, sessionId);
1220}
1221
1222void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1223{
1224 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1225 if (index < 0) {
1226 return;
1227 }
1228
1229 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1230 mSuspendedSessions.valueAt(index);
1231
1232 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001233 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001234 for (int j = 0; j < desc->mRefCount; j++) {
1235 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1236 chain->setEffectSuspendedAll_l(true);
1237 } else {
1238 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1239 desc->mType.timeLow);
1240 chain->setEffectSuspended_l(&desc->mType, true);
1241 }
1242 }
1243 }
1244}
1245
1246void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1247 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001248 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001249{
1250 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1251
1252 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1253
1254 if (suspend) {
1255 if (index >= 0) {
1256 sessionEffects = mSuspendedSessions.valueAt(index);
1257 } else {
1258 mSuspendedSessions.add(sessionId, sessionEffects);
1259 }
1260 } else {
1261 if (index < 0) {
1262 return;
1263 }
1264 sessionEffects = mSuspendedSessions.valueAt(index);
1265 }
1266
1267
1268 int key = EffectChain::kKeyForSuspendAll;
1269 if (type != NULL) {
1270 key = type->timeLow;
1271 }
1272 index = sessionEffects.indexOfKey(key);
1273
1274 sp<SuspendedSessionDesc> desc;
1275 if (suspend) {
1276 if (index >= 0) {
1277 desc = sessionEffects.valueAt(index);
1278 } else {
1279 desc = new SuspendedSessionDesc();
1280 if (type != NULL) {
1281 desc->mType = *type;
1282 }
1283 sessionEffects.add(key, desc);
1284 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1285 }
1286 desc->mRefCount++;
1287 } else {
1288 if (index < 0) {
1289 return;
1290 }
1291 desc = sessionEffects.valueAt(index);
1292 if (--desc->mRefCount == 0) {
1293 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1294 sessionEffects.removeItemsAt(index);
1295 if (sessionEffects.isEmpty()) {
1296 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1297 sessionId);
1298 mSuspendedSessions.removeItem(sessionId);
1299 }
1300 }
1301 }
1302 if (!sessionEffects.isEmpty()) {
1303 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1304 }
1305}
1306
Eric Laurent6b446ce2019-12-13 10:56:31 -08001307void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1308 audio_session_t sessionId,
Andy Hung71ba4b32022-10-06 12:09:49 -07001309 bool threadLocked)
1310NO_THREAD_SAFETY_ANALYSIS // manual locking
1311{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001312 if (!threadLocked) {
1313 mLock.lock();
1314 }
Eric Laurent81784c32012-11-19 14:55:58 -08001315
Eric Laurent81784c32012-11-19 14:55:58 -08001316 if (mType != RECORD) {
1317 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1318 // another session. This gives the priority to well behaved effect control panels
1319 // and applications not using global effects.
1320 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1321 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001322 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001323 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1324 }
1325 }
1326
Eric Laurent6b446ce2019-12-13 10:56:31 -08001327 if (!threadLocked) {
1328 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001329 }
1330}
1331
Eric Laurent4c415062016-06-17 16:14:16 -07001332// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1333status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1334 const effect_descriptor_t *desc, audio_session_t sessionId)
1335{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001336 // No global output effect sessions on record threads
1337 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1338 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001339 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1340 desc->name, mThreadName);
1341 return BAD_VALUE;
1342 }
1343 // only pre processing effects on record thread
1344 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1345 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1346 desc->name, mThreadName);
1347 return BAD_VALUE;
1348 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001349
1350 // always allow effects without processing load or latency
1351 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1352 return NO_ERROR;
1353 }
1354
Eric Laurent4c415062016-06-17 16:14:16 -07001355 audio_input_flags_t flags = mInput->flags;
1356 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1357 if (flags & AUDIO_INPUT_FLAG_RAW) {
1358 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1359 desc->name, mThreadName);
1360 return BAD_VALUE;
1361 }
1362 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1363 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1364 desc->name, mThreadName);
1365 return BAD_VALUE;
1366 }
1367 }
jiabineb3bda02020-06-30 14:07:03 -07001368
1369 if (EffectModule::isHapticGenerator(&desc->type)) {
1370 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1371 return BAD_VALUE;
1372 }
Eric Laurent4c415062016-06-17 16:14:16 -07001373 return NO_ERROR;
1374}
1375
1376// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1377status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1378 const effect_descriptor_t *desc, audio_session_t sessionId)
1379{
1380 // no preprocessing on playback threads
1381 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001382 ALOGW("%s: pre processing effect %s created on playback"
1383 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001384 return BAD_VALUE;
1385 }
1386
Eric Laurent3e4de772017-07-16 16:55:08 -07001387 // always allow effects without processing load or latency
1388 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1389 return NO_ERROR;
1390 }
1391
jiabineb3bda02020-06-30 14:07:03 -07001392 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1393 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1394 __func__);
1395 return BAD_VALUE;
1396 }
1397
Eric Laurentf690c462021-09-17 14:47:03 +02001398 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1399 && mType != SPATIALIZER) {
1400 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1401 __func__, mType);
1402 return BAD_VALUE;
1403 }
1404
Eric Laurent4c415062016-06-17 16:14:16 -07001405 switch (mType) {
1406 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001407 audio_output_flags_t flags = mOutput->flags;
1408 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1409 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1410 // global effects are applied only to non fast tracks if they are SW
1411 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1412 break;
1413 }
1414 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1415 // only post processing on output stage session
1416 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001417 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1418 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001419 return BAD_VALUE;
1420 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001421 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1422 // only post processing on output stage session
1423 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001424 ALOGW("%s: non post processing effect %s not allowed on device session",
1425 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001426 return BAD_VALUE;
1427 }
Eric Laurent4c415062016-06-17 16:14:16 -07001428 } else {
1429 // no restriction on effects applied on non fast tracks
1430 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1431 break;
1432 }
1433 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001434
Eric Laurent4c415062016-06-17 16:14:16 -07001435 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001436 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001437 return BAD_VALUE;
1438 }
1439 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001440 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1441 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001442 return BAD_VALUE;
1443 }
1444 }
1445 } break;
1446 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001447 // nothing actionable on offload threads, if the effect:
1448 // - is offloadable: the effect can be created
1449 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1450 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001451 break;
1452 case DIRECT:
1453 // Reject any effect on Direct output threads for now, since the format of
1454 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001455 ALOGW("%s: effect %s on DIRECT output thread %s",
1456 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001457 return BAD_VALUE;
1458 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001459 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001460 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1461 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001462 return BAD_VALUE;
1463 }
1464 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001465 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1466 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001467 return BAD_VALUE;
1468 }
1469 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001470 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1471 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001472 return BAD_VALUE;
1473 }
1474 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001475 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001476 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1477 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1478 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1479 // are supported and added after the spatializer.
1480 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1481 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1482 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001483 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001484 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1485 // only post processing , downmixer or spatializer effects on output stage session
1486 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1487 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1488 break;
1489 }
1490 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1491 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1492 __func__, desc->name);
1493 return BAD_VALUE;
1494 }
1495 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1496 // only post processing on output stage session
1497 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1498 ALOGW("%s: non post processing effect %s not allowed on device session",
1499 __func__, desc->name);
1500 return BAD_VALUE;
1501 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001502 }
1503 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001504 default:
1505 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1506 }
1507
1508 return NO_ERROR;
1509}
1510
Eric Laurent81784c32012-11-19 14:55:58 -08001511// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1512sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1513 const sp<AudioFlinger::Client>& client,
1514 const sp<IEffectClient>& effectClient,
1515 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001516 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001517 effect_descriptor_t *desc,
1518 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001519 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001520 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001521 bool probe,
1522 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 sp<EffectModule> effect;
1525 sp<EffectHandle> handle;
1526 status_t lStatus;
1527 sp<EffectChain> chain;
1528 bool chainCreated = false;
1529 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001530 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001531
1532 lStatus = initCheck();
1533 if (lStatus != NO_ERROR) {
1534 ALOGW("createEffect_l() Audio driver not initialized.");
1535 goto Exit;
1536 }
1537
Eric Laurent81784c32012-11-19 14:55:58 -08001538 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1539
1540 { // scope for mLock
1541 Mutex::Autolock _l(mLock);
1542
Eric Laurent4c415062016-06-17 16:14:16 -07001543 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001544 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001545 goto Exit;
1546 }
1547
Eric Laurent81784c32012-11-19 14:55:58 -08001548 // check for existing effect chain with the requested audio session
1549 chain = getEffectChain_l(sessionId);
1550 if (chain == 0) {
1551 // create a new chain for this session
1552 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1553 chain = new EffectChain(this, sessionId);
1554 addEffectChain_l(chain);
1555 chain->setStrategy(getStrategyForSession_l(sessionId));
1556 chainCreated = true;
1557 } else {
1558 effect = chain->getEffectFromDesc_l(desc);
1559 }
1560
1561 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1562
1563 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001564 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001565 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001566 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001567 if (lStatus != NO_ERROR) {
1568 goto Exit;
1569 }
1570 effectCreated = true;
1571
jiabinc52b1ff2019-10-31 17:20:42 -07001572 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001573 effect->setDevices(outDeviceTypeAddrs());
1574 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001575 effect->setMode(mAudioFlinger->getMode());
1576 effect->setAudioSource(mAudioSource);
1577 }
jiabin1319f5a2021-03-30 22:21:24 +00001578 if (effect->isHapticGenerator()) {
1579 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1580 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001581 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1582 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1583 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001584 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001585 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001586 }
1587 }
Eric Laurent81784c32012-11-19 14:55:58 -08001588 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001589 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001590 lStatus = handle->initCheck();
1591 if (lStatus == OK) {
1592 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001593 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001594 }
Eric Laurent81784c32012-11-19 14:55:58 -08001595 if (enabled != NULL) {
1596 *enabled = (int)effect->isEnabled();
1597 }
1598 }
1599
1600Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001601 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001602 Mutex::Autolock _l(mLock);
1603 if (effectCreated) {
1604 chain->removeEffect_l(effect);
1605 }
Eric Laurent81784c32012-11-19 14:55:58 -08001606 if (chainCreated) {
1607 removeEffectChain_l(chain);
1608 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001609 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001610 }
1611
Glenn Kasten9156ef32013-08-06 15:39:08 -07001612 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001613 return handle;
1614}
1615
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001616void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1617 bool unpinIfLast)
1618{
1619 bool remove = false;
1620 sp<EffectModule> effect;
1621 {
1622 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001623 sp<EffectBase> effectBase = handle->effect().promote();
1624 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001625 return;
1626 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001627 effect = effectBase->asEffectModule();
1628 if (effect == nullptr) {
1629 return;
1630 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001631 // restore suspended effects if the disconnected handle was enabled and the last one.
1632 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1633 if (remove) {
1634 removeEffect_l(effect, true);
1635 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001636 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001637 }
1638 if (remove) {
1639 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001640 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001641 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001642 }
1643 }
1644}
1645
Eric Laurent6b446ce2019-12-13 10:56:31 -08001646void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001647 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001648 Mutex::Autolock _l(mLock);
1649 broadcast_l();
1650 }
1651 if (!effect->isOffloadable()) {
1652 if (mType == ThreadBase::OFFLOAD) {
1653 PlaybackThread *t = (PlaybackThread *)this;
1654 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1655 }
1656 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1657 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1658 }
1659 }
1660}
1661
1662void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001663 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001664 Mutex::Autolock _l(mLock);
1665 broadcast_l();
1666 }
1667}
1668
Glenn Kastend848eb42016-03-08 13:42:11 -08001669sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1670 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001671{
1672 Mutex::Autolock _l(mLock);
1673 return getEffect_l(sessionId, effectId);
1674}
1675
Glenn Kastend848eb42016-03-08 13:42:11 -08001676sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1677 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001678{
1679 sp<EffectChain> chain = getEffectChain_l(sessionId);
1680 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1681}
1682
Eric Laurent6c796322019-04-09 14:13:17 -07001683std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1684{
1685 sp<EffectChain> chain = getEffectChain_l(sessionId);
1686 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1687}
1688
Eric Laurent81784c32012-11-19 14:55:58 -08001689// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1690// PlaybackThread::mLock held
1691status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1692{
1693 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001694 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001695 sp<EffectChain> chain = getEffectChain_l(sessionId);
1696 bool chainCreated = false;
1697
Eric Laurent5baf2af2013-09-12 17:37:00 -07001698 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001699 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001700 this, effect->desc().name, effect->desc().flags);
1701
Eric Laurent81784c32012-11-19 14:55:58 -08001702 if (chain == 0) {
1703 // create a new chain for this session
1704 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1705 chain = new EffectChain(this, sessionId);
1706 addEffectChain_l(chain);
1707 chain->setStrategy(getStrategyForSession_l(sessionId));
1708 chainCreated = true;
1709 }
1710 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1711
1712 if (chain->getEffectFromId_l(effect->id()) != 0) {
1713 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1714 this, effect->desc().name, chain.get());
1715 return BAD_VALUE;
1716 }
1717
Eric Laurent5baf2af2013-09-12 17:37:00 -07001718 effect->setOffloaded(mType == OFFLOAD, mId);
1719
Eric Laurent81784c32012-11-19 14:55:58 -08001720 status_t status = chain->addEffect_l(effect);
1721 if (status != NO_ERROR) {
1722 if (chainCreated) {
1723 removeEffectChain_l(chain);
1724 }
1725 return status;
1726 }
1727
jiabin8f278ee2019-11-11 12:16:27 -08001728 effect->setDevices(outDeviceTypeAddrs());
1729 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001730 effect->setMode(mAudioFlinger->getMode());
1731 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001732
Eric Laurent81784c32012-11-19 14:55:58 -08001733 return NO_ERROR;
1734}
1735
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001736void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001737
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001738 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001739 effect_descriptor_t desc = effect->desc();
1740 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1741 detachAuxEffect_l(effect->id());
1742 }
1743
Andy Hungfda44002021-06-03 17:23:16 -07001744 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001745 if (chain != 0) {
1746 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001748 removeEffectChain_l(chain);
1749 }
1750 } else {
1751 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1752 }
1753}
1754
1755void AudioFlinger::ThreadBase::lockEffectChains_l(
1756 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001757NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001758{
1759 effectChains = mEffectChains;
1760 for (size_t i = 0; i < mEffectChains.size(); i++) {
1761 mEffectChains[i]->lock();
1762 }
1763}
1764
1765void AudioFlinger::ThreadBase::unlockEffectChains(
1766 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Andy Hung71ba4b32022-10-06 12:09:49 -07001767NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001768{
1769 for (size_t i = 0; i < effectChains.size(); i++) {
1770 effectChains[i]->unlock();
1771 }
1772}
1773
Glenn Kastend848eb42016-03-08 13:42:11 -08001774sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001775{
1776 Mutex::Autolock _l(mLock);
1777 return getEffectChain_l(sessionId);
1778}
1779
Glenn Kastend848eb42016-03-08 13:42:11 -08001780sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1781 const
Eric Laurent81784c32012-11-19 14:55:58 -08001782{
1783 size_t size = mEffectChains.size();
1784 for (size_t i = 0; i < size; i++) {
1785 if (mEffectChains[i]->sessionId() == sessionId) {
1786 return mEffectChains[i];
1787 }
1788 }
1789 return 0;
1790}
1791
1792void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1793{
1794 Mutex::Autolock _l(mLock);
1795 size_t size = mEffectChains.size();
1796 for (size_t i = 0; i < size; i++) {
1797 mEffectChains[i]->setMode_l(mode);
1798 }
1799}
1800
Mikhail Naganovdc769682018-05-04 15:34:08 -07001801void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001802{
1803 config->type = AUDIO_PORT_TYPE_MIX;
1804 config->ext.mix.handle = mId;
1805 config->sample_rate = mSampleRate;
1806 config->format = mFormat;
1807 config->channel_mask = mChannelMask;
1808 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1809 AUDIO_PORT_CONFIG_FORMAT;
1810}
1811
Eric Laurent72e3f392015-05-20 14:43:50 -07001812void AudioFlinger::ThreadBase::systemReady()
1813{
1814 Mutex::Autolock _l(mLock);
1815 if (mSystemReady) {
1816 return;
1817 }
1818 mSystemReady = true;
1819
1820 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1821 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1822 }
1823 mPendingConfigEvents.clear();
1824}
1825
Andy Hungdae27702016-10-31 14:01:16 -07001826template <typename T>
1827ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1828 ssize_t index = mActiveTracks.indexOf(track);
1829 if (index >= 0) {
1830 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1831 return index;
1832 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001833 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001834 mActiveTracksGeneration++;
1835 mLatestActiveTrack = track;
1836 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001837 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001838 return mActiveTracks.add(track);
1839}
1840
1841template <typename T>
1842ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1843 ssize_t index = mActiveTracks.remove(track);
1844 if (index < 0) {
1845 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1846 return index;
1847 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001848 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001849 mActiveTracksGeneration++;
1850 --mBatteryCounter[track->uid()].second;
1851 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001852 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001853#ifdef TEE_SINK
1854 track->dumpTee(-1 /* fd */, "_REMOVE");
1855#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001856 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001857 return index;
1858}
1859
1860template <typename T>
1861void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1862 for (const sp<T> &track : mActiveTracks) {
1863 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001864 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001865 }
1866 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001867 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001868 mActiveTracks.clear();
1869 mLatestActiveTrack.clear();
1870 mBatteryCounter.clear();
1871}
1872
1873template <typename T>
1874void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001875 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001876 // Updates ActiveTracks client uids to the thread wakelock.
1877 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1878 thread->updateWakeLockUids_l(getWakeLockUids());
1879 mLastActiveTracksGeneration = mActiveTracksGeneration;
1880 }
1881
1882 // Updates BatteryNotifier uids
1883 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1884 const uid_t uid = it->first;
1885 ssize_t &previous = it->second.first;
1886 ssize_t &current = it->second.second;
1887 if (current > 0) {
1888 if (previous == 0) {
1889 BatteryNotifier::getInstance().noteStartAudio(uid);
1890 }
1891 previous = current;
1892 ++it;
1893 } else if (current == 0) {
1894 if (previous > 0) {
1895 BatteryNotifier::getInstance().noteStopAudio(uid);
1896 }
1897 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1898 } else /* (current < 0) */ {
1899 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1900 }
1901 }
1902}
Eric Laurent83b88082014-06-20 18:31:16 -07001903
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001904template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001905bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001906 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001907 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001908
1909 for (const sp<T> &track : mActiveTracks) {
1910 // Do not short-circuit as all hasChanged states must be reset
1911 // as all the metadata are going to be sent
1912 hasChanged |= track->readAndClearHasChanged();
1913 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001914 return hasChanged;
1915}
1916
1917template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001918void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1919 const char *funcName, const sp<T> &track) const {
1920 if (mLocalLog != nullptr) {
1921 String8 result;
1922 track->appendDump(result, false /* active */);
1923 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1924 }
1925}
1926
Eric Laurent6acd1d42017-01-04 14:23:29 -08001927void AudioFlinger::ThreadBase::broadcast_l()
1928{
1929 // Thread could be blocked waiting for async
1930 // so signal it to handle state changes immediately
1931 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1932 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1933 mSignalPending = true;
1934 mWaitWorkCV.broadcast();
1935}
1936
Andy Hungd0979812019-02-21 15:51:44 -08001937// Call only from threadLoop() or when it is idle.
1938// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1939void AudioFlinger::ThreadBase::sendStatistics(bool force)
1940{
1941 // Do not log if we have no stats.
1942 // We choose the timestamp verifier because it is the most likely item to be present.
1943 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1944 if (nstats == 0) {
1945 return;
1946 }
1947
1948 // Don't log more frequently than once per 12 hours.
1949 // We use BOOTTIME to include suspend time.
1950 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1951 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1952 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1953 return;
1954 }
1955
1956 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1957 mLastRecordedTimeNs = timeNs;
1958
Ray Essickf27e9872019-12-07 06:28:46 -08001959 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001960
1961#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1962
1963 // thread configuration
1964 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1965 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1966 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1967 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1968 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1969 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1970 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001971 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1972 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001973
1974 // thread statistics
1975 if (mIoJitterMs.getN() > 0) {
1976 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1977 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1978 }
1979 if (mProcessTimeMs.getN() > 0) {
1980 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1981 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1982 }
1983 const auto tsjitter = mTimestampVerifier.getJitterMs();
1984 if (tsjitter.getN() > 0) {
1985 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1986 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1987 }
1988 if (mLatencyMs.getN() > 0) {
1989 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1990 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1991 }
Robert Wu06db0a32021-08-10 19:05:34 +00001992 if (mMonopipePipeDepthStats.getN() > 0) {
1993 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1994 mMonopipePipeDepthStats.getMean());
1995 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1996 mMonopipePipeDepthStats.getStdDev());
1997 }
Andy Hungd0979812019-02-21 15:51:44 -08001998
1999 item->selfrecord();
2000}
2001
Eric Laurentd66d7a12021-07-13 13:35:32 +02002002product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
2003{
2004 if (!mAudioFlinger->isAudioPolicyReady()) {
2005 return PRODUCT_STRATEGY_NONE;
2006 }
2007 return AudioSystem::getStrategyForStream(stream);
2008}
2009
Eric Laurent81784c32012-11-19 14:55:58 -08002010// ----------------------------------------------------------------------------
2011// Playback
2012// ----------------------------------------------------------------------------
2013
2014AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
2015 AudioStreamOut* output,
2016 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002017 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002018 bool systemReady,
2019 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07002020 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002021 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002022 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002023 mMixerBuffer(NULL),
2024 mMixerBufferSize(0),
2025 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2026 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002027 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002028 mEffectBuffer(NULL),
2029 mEffectBufferSize(0),
2030 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2031 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002032 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002033 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002034 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002035 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002036 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002037 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002038 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002039 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002040 mMixerStatus(MIXER_IDLE),
2041 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002042 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002043 mBytesRemaining(0),
2044 mCurrentWriteLength(0),
2045 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002046 mWriteAckSequence(0),
2047 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08002048 mScreenState(AudioFlinger::mScreenState),
2049 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002050 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002051 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002052 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002053 mDownStreamPatch{},
Eric Laurent01eb1642022-12-16 11:45:07 +01002054 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs),
2055 mBluetoothLatencyModesEnabled(true)
Eric Laurent81784c32012-11-19 14:55:58 -08002056{
Glenn Kastend7dca052015-03-05 16:05:54 -08002057 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
2058 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002059
2060 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2061 // it would be safer to explicitly pass initial masterVolume/masterMute as
2062 // parameter.
2063 //
2064 // If the HAL we are using has support for master volume or master mute,
2065 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2066 // and the mute set to false).
2067 mMasterVolume = audioFlinger->masterVolume_l();
2068 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002069 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002070 if (mOutput->audioHwDev->canSetMasterVolume()) {
2071 mMasterVolume = 1.0;
2072 }
2073
2074 if (mOutput->audioHwDev->canSetMasterMute()) {
2075 mMasterMute = false;
2076 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002077 mIsMsdDevice = strcmp(
2078 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002079 }
2080
Eric Laurentf1f22e72021-07-13 14:04:14 +02002081 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2082 mMixerChannelMask = mixerConfig->channel_mask;
2083 }
2084
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002085 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002086
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002087 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002088 && mMixerChannelMask != mChannelMask) {
2089 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2090 mChannelMask, mMixerChannelMask);
2091 }
2092
Andy Hungc8fddf32018-08-08 18:32:37 -07002093 // TODO: We may also match on address as well as device type for
2094 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002095 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002096 // TODO: This property should be ensure that only contains one single device type.
2097 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2098 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002099 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2100 : AUDIO_DEVICE_NONE));
2101 }
2102
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002103 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2104 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002105 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002106 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2107 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002108 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002109 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2110 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002111 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2112 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002113}
2114
2115AudioFlinger::PlaybackThread::~PlaybackThread()
2116{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002117 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002118 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002119 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002120 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002121 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002122}
2123
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002124// Thread virtuals
2125
2126void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002127{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002128 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002129 ALOGE("The stream is not open yet"); // This should not happen.
2130 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002131 // Callbacks take strong or weak pointers as a parameter.
2132 // Since PlaybackThread passes itself as a callback handler, it can only
2133 // be done outside of the constructor. Creating weak and especially strong
2134 // pointers to a refcounted object in its own constructor is strongly
2135 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2136 // Even if a function takes a weak pointer, it is possible that it will
2137 // need to convert it to a strong pointer down the line.
2138 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2139 mOutput->stream->setCallback(this) == OK) {
2140 mUseAsyncWrite = true;
2141 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
2142 }
2143
jiabinf6eb4c32020-02-25 14:06:25 -08002144 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002145 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002146 }
2147 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002148 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002149 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002150}
2151
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002152// ThreadBase virtuals
2153void AudioFlinger::PlaybackThread::preExit()
2154{
2155 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002156 status_t result = mOutput->stream->exit();
2157 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002158}
2159
2160void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002161{
Eric Laurent81784c32012-11-19 14:55:58 -08002162 String8 result;
2163
Marco Nelissenb2208842014-02-07 14:00:50 -08002164 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002165 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2166 const stream_type_t *st = &mStreamTypes[i];
2167 if (i > 0) {
2168 result.appendFormat(", ");
2169 }
2170 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2171 if (st->mute) {
2172 result.append("M");
2173 }
2174 }
2175 result.append("\n");
2176 write(fd, result.string(), result.length());
2177 result.clear();
2178
Eric Laurent81784c32012-11-19 14:55:58 -08002179 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2180 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002181 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002182 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002183
2184 size_t numtracks = mTracks.size();
2185 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002186 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002187 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002188 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002189 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002190 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002191 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002192 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002193 for (size_t i = 0; i < numtracks; ++i) {
2194 sp<Track> track = mTracks[i];
2195 if (track != 0) {
2196 bool active = mActiveTracks.indexOf(track) >= 0;
2197 if (active) {
2198 numactiveseen++;
2199 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002200 result.append(prefix);
2201 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002202 }
2203 }
2204 } else {
2205 result.append("\n");
2206 }
2207 if (numactiveseen != numactive) {
2208 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002209 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002210 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002211 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002212 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002213 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002214 sp<Track> track = mActiveTracks[i];
2215 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002216 result.append(prefix);
2217 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002218 }
2219 }
2220 }
2221
2222 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002223}
2224
Andy Hung61589a42021-06-16 09:37:53 -07002225void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002226{
Andy Hung04cb8f72020-03-20 13:44:33 -07002227 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002228 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002229 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2230 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002231 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2232 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2233 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2234 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002235 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002236 dprintf(fd, " Total writes: %d\n", mNumWrites);
2237 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2238 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2239 dprintf(fd, " Suspend count: %d\n", mSuspended);
2240 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2241 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2242 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2243 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002244 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002245 AudioStreamOut *output = mOutput;
2246 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002247 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002248 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002249 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2250 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2251 if (mPipeSink.get() != nullptr) {
2252 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2253 }
2254 if (output != nullptr) {
2255 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002256 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002257 }
Eric Laurent81784c32012-11-19 14:55:58 -08002258}
2259
Eric Laurent81784c32012-11-19 14:55:58 -08002260// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2261sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2262 const sp<AudioFlinger::Client>& client,
2263 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002264 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002265 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002266 audio_format_t format,
2267 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002268 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002269 size_t *pNotificationFrameCount,
2270 uint32_t notificationsPerBuffer,
2271 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002272 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002273 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002274 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002275 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002276 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002277 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002278 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002279 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002280 const sp<media::IAudioTrackCallback>& callback,
2281 bool isSpatialized)
Eric Laurent81784c32012-11-19 14:55:58 -08002282{
Glenn Kasten74935e42013-12-19 08:56:45 -08002283 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002284 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002285 sp<Track> track;
2286 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002287 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002288 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002289 uint32_t sampleRate;
2290
2291 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2292 lStatus = BAD_VALUE;
2293 goto Exit;
2294 }
Eric Laurent21da6472017-11-09 16:29:26 -08002295
2296 if (*pSampleRate == 0) {
2297 *pSampleRate = mSampleRate;
2298 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002299 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002300
2301 // special case for FAST flag considered OK if fast mixer is present
2302 if (hasFastMixer()) {
2303 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2304 }
2305
2306 // Check if requested flags are compatible with output stream flags
2307 if ((*flags & outputFlags) != *flags) {
2308 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2309 *flags, outputFlags);
2310 *flags = (audio_output_flags_t)(*flags & outputFlags);
2311 }
Eric Laurent81784c32012-11-19 14:55:58 -08002312
Eric Laurent81784c32012-11-19 14:55:58 -08002313 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002314 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002315 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002316 // PCM data
2317 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002318 // TODO: extract as a data library function that checks that a computationally
2319 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002320 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002321 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2322 (channelMask == AUDIO_CHANNEL_OUT_MONO
2323 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002324 // hardware sample rate
2325 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002326 // normal mixer has an associated fast mixer
2327 hasFastMixer() &&
2328 // there are sufficient fast track slots available
2329 (mFastTrackAvailMask != 0)
2330 // FIXME test that MixerThread for this fast track has a capable output HAL
2331 // FIXME add a permission test also?
2332 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002333 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2334 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002335 // read the fast track multiplier property the first time it is needed
2336 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2337 if (ok != 0) {
2338 ALOGE("%s pthread_once failed: %d", __func__, ok);
2339 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002340 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002341 }
Eric Laurent4c415062016-06-17 16:14:16 -07002342
2343 // check compatibility with audio effects.
2344 { // scope for mLock
2345 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002346 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002347 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002348 AUDIO_SESSION_OUTPUT_STAGE,
2349 AUDIO_SESSION_OUTPUT_MIX,
2350 sessionId,
2351 }) {
2352 sp<EffectChain> chain = getEffectChain_l(session);
2353 if (chain.get() != nullptr) {
2354 audio_output_flags_t old = *flags;
2355 chain->checkOutputFlagCompatibility(flags);
2356 if (old != *flags) {
2357 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2358 (int)session, (int)old, (int)*flags);
2359 }
Eric Laurent4c415062016-06-17 16:14:16 -07002360 }
2361 }
2362 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002363 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002364 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2365 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002366 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002367 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002368 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002369 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002370 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002371 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002372 audio_is_linear_pcm(format), channelMask, sampleRate,
2373 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002374 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002375 }
2376 }
Eric Laurent21da6472017-11-09 16:29:26 -08002377
2378 if (!audio_has_proportional_frames(format)) {
2379 if (sharedBuffer != 0) {
2380 // Same comment as below about ignoring frameCount parameter for set()
2381 frameCount = sharedBuffer->size();
2382 } else if (frameCount == 0) {
2383 frameCount = mNormalFrameCount;
2384 }
2385 if (notificationFrameCount != frameCount) {
2386 notificationFrameCount = frameCount;
2387 }
2388 } else if (sharedBuffer != 0) {
2389 // FIXME: Ensure client side memory buffers need
2390 // not have additional alignment beyond sample
2391 // (e.g. 16 bit stereo accessed as 32 bit frame).
2392 size_t alignment = audio_bytes_per_sample(format);
2393 if (alignment & 1) {
2394 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2395 alignment = 1;
2396 }
2397 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2398 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2399 if (channelCount > 1) {
2400 // More than 2 channels does not require stronger alignment than stereo
2401 alignment <<= 1;
2402 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002403 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002404 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002405 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002406 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002407 goto Exit;
2408 }
Eric Laurent21da6472017-11-09 16:29:26 -08002409
2410 // When initializing a shared buffer AudioTrack via constructors,
2411 // there's no frameCount parameter.
2412 // But when initializing a shared buffer AudioTrack via set(),
2413 // there _is_ a frameCount parameter. We silently ignore it.
2414 frameCount = sharedBuffer->size() / frameSize;
2415 } else {
2416 size_t minFrameCount = 0;
2417 // For fast tracks we try to respect the application's request for notifications per buffer.
2418 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2419 if (notificationsPerBuffer > 0) {
2420 // Avoid possible arithmetic overflow during multiplication.
2421 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2422 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2423 notificationsPerBuffer, mFrameCount);
2424 } else {
2425 minFrameCount = mFrameCount * notificationsPerBuffer;
2426 }
2427 }
2428 } else {
2429 // For normal PCM streaming tracks, update minimum frame count.
2430 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2431 // cover audio hardware latency.
2432 // This is probably too conservative, but legacy application code may depend on it.
2433 // If you change this calculation, also review the start threshold which is related.
2434 uint32_t latencyMs = latency_l();
2435 if (latencyMs == 0) {
2436 ALOGE("Error when retrieving output stream latency");
2437 lStatus = UNKNOWN_ERROR;
2438 goto Exit;
2439 }
2440
2441 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2442 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2443
Eric Laurent81784c32012-11-19 14:55:58 -08002444 }
Eric Laurent21da6472017-11-09 16:29:26 -08002445 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002446 frameCount = minFrameCount;
2447 }
Eric Laurent81784c32012-11-19 14:55:58 -08002448 }
Eric Laurent21da6472017-11-09 16:29:26 -08002449
2450 // Make sure that application is notified with sufficient margin before underrun.
2451 // The client can divide the AudioTrack buffer into sub-buffers,
2452 // and expresses its desire to server as the notification frame count.
2453 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2454 size_t maxNotificationFrames;
2455 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2456 // notify every HAL buffer, regardless of the size of the track buffer
2457 maxNotificationFrames = mFrameCount;
2458 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002459 // Triple buffer the notification period for a triple buffered mixer period;
2460 // otherwise, double buffering for the notification period is fine.
2461 //
2462 // TODO: This should be moved to AudioTrack to modify the notification period
2463 // on AudioTrack::setBufferSizeInFrames() changes.
2464 const int nBuffering =
2465 (uint64_t{frameCount} * mSampleRate)
2466 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2467
Eric Laurent21da6472017-11-09 16:29:26 -08002468 maxNotificationFrames = frameCount / nBuffering;
2469 // If client requested a fast track but this was denied, then use the smaller maximum.
2470 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2471 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2472 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2473 maxNotificationFrames = maxNotificationFramesFastDenied;
2474 }
2475 }
2476 }
2477 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2478 if (notificationFrameCount == 0) {
2479 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2480 maxNotificationFrames, frameCount);
2481 } else {
2482 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2483 notificationFrameCount, maxNotificationFrames, frameCount);
2484 }
2485 notificationFrameCount = maxNotificationFrames;
2486 }
2487 }
2488
Glenn Kasten74935e42013-12-19 08:56:45 -08002489 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002490 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002491
Glenn Kastenc3df8382014-03-13 15:05:25 -07002492 switch (mType) {
2493
2494 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002495 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002496 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002497 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2498 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002499 sampleRate, format, channelMask, mOutput, mFormat);
2500 lStatus = BAD_VALUE;
2501 goto Exit;
2502 }
2503 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002504 break;
2505
2506 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002507 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002508 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2509 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002510 sampleRate, format, channelMask, mOutput, mFormat);
2511 lStatus = BAD_VALUE;
2512 goto Exit;
2513 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002514 break;
2515
2516 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002517 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002518 ALOGE("createTrack_l() Bad parameter: format %#x \""
2519 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002520 format, mOutput, mFormat);
2521 lStatus = BAD_VALUE;
2522 goto Exit;
2523 }
Andy Hungcd044842014-08-07 11:04:34 -07002524 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002525 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2526 lStatus = BAD_VALUE;
2527 goto Exit;
2528 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002529 break;
2530
Eric Laurent81784c32012-11-19 14:55:58 -08002531 }
2532
2533 lStatus = initCheck();
2534 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002535 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002536 goto Exit;
2537 }
2538
2539 { // scope for mLock
2540 Mutex::Autolock _l(mLock);
2541
2542 // all tracks in same audio session must share the same routing strategy otherwise
2543 // conflicts will happen when tracks are moved from one output to another by audio policy
2544 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002545 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002546 for (size_t i = 0; i < mTracks.size(); ++i) {
2547 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002548 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002549 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002550 if (sessionId == t->sessionId() && strategy != actual) {
2551 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2552 strategy, actual);
2553 lStatus = BAD_VALUE;
2554 goto Exit;
2555 }
2556 }
2557 }
2558
yucliuc9c49cd2020-07-13 16:25:21 -07002559 // Set DIRECT flag if current thread is DirectOutputThread. This can
2560 // happen when the playback is rerouted to direct output thread by
2561 // dynamic audio policy.
2562 // Do NOT report the flag changes back to client, since the client
2563 // doesn't explicitly request a direct flag.
2564 audio_output_flags_t trackFlags = *flags;
2565 if (mType == DIRECT) {
2566 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2567 }
2568
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002569 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002570 channelMask, frameCount,
2571 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002572 sessionId, creatorPid, attributionSource, trackFlags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002573 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
2574 speed, isSpatialized);
Glenn Kasten03003332013-08-06 15:40:54 -07002575
Glenn Kasten03003332013-08-06 15:40:54 -07002576 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2577 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002578 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002579 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002580 goto Exit;
2581 }
2582 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002583 {
2584 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2585 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002586 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002587 }
2588 }
Eric Laurent81784c32012-11-19 14:55:58 -08002589
2590 sp<EffectChain> chain = getEffectChain_l(sessionId);
2591 if (chain != 0) {
2592 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2593 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002594 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002595 chain->incTrackCnt();
2596 }
2597
Eric Laurent05067782016-06-01 18:27:28 -07002598 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002599 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2600 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2601 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002602 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002603 }
2604 }
2605
2606 lStatus = NO_ERROR;
2607
2608Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002609 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002610 return track;
2611}
2612
Andy Hung1bc088a2018-02-09 15:57:31 -08002613template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002614ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2615{
Andy Hungc0691382018-09-12 18:01:57 -07002616 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002617 const ssize_t index = mTracks.remove(track);
2618 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002619 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002620 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002621 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002622 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002623 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002624 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002625 }
2626 return index;
2627}
2628
Eric Laurent81784c32012-11-19 14:55:58 -08002629uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2630{
2631 return latency;
2632}
2633
2634uint32_t AudioFlinger::PlaybackThread::latency() const
2635{
2636 Mutex::Autolock _l(mLock);
2637 return latency_l();
2638}
2639uint32_t AudioFlinger::PlaybackThread::latency_l() const
2640{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002641 uint32_t latency;
2642 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2643 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002644 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002645 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002646}
2647
2648void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2649{
2650 Mutex::Autolock _l(mLock);
2651 // Don't apply master volume in SW if our HAL can do it for us.
2652 if (mOutput && mOutput->audioHwDev &&
2653 mOutput->audioHwDev->canSetMasterVolume()) {
2654 mMasterVolume = 1.0;
2655 } else {
2656 mMasterVolume = value;
2657 }
2658}
2659
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002660void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2661{
2662 mMasterBalance.store(balance);
2663}
2664
Eric Laurent81784c32012-11-19 14:55:58 -08002665void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2666{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002667 if (isDuplicating()) {
2668 return;
2669 }
Eric Laurent81784c32012-11-19 14:55:58 -08002670 Mutex::Autolock _l(mLock);
2671 // Don't apply master mute in SW if our HAL can do it for us.
2672 if (mOutput && mOutput->audioHwDev &&
2673 mOutput->audioHwDev->canSetMasterMute()) {
2674 mMasterMute = false;
2675 } else {
2676 mMasterMute = muted;
2677 }
2678}
2679
2680void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2681{
2682 Mutex::Autolock _l(mLock);
2683 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002684 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002685}
2686
2687void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2688{
2689 Mutex::Autolock _l(mLock);
2690 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002691 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002692}
2693
2694float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2695{
2696 Mutex::Autolock _l(mLock);
2697 return mStreamTypes[stream].volume;
2698}
2699
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002700void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2701{
2702 mOutput->stream->setVolume(left, right);
2703}
2704
Eric Laurent81784c32012-11-19 14:55:58 -08002705// addTrack_l() must be called with ThreadBase::mLock held
2706status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
Andy Hung71ba4b32022-10-06 12:09:49 -07002707NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent81784c32012-11-19 14:55:58 -08002708{
2709 status_t status = ALREADY_EXISTS;
2710
Eric Laurent81784c32012-11-19 14:55:58 -08002711 if (mActiveTracks.indexOf(track) < 0) {
2712 // the track is newly added, make sure it fills up all its
2713 // buffers before playing. This is to ensure the client will
2714 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002715 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002716 TrackBase::track_state state = track->mState;
2717 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002718 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002719 mLock.lock();
2720 // abort track was stopped/paused while we released the lock
2721 if (state != track->mState) {
2722 if (status == NO_ERROR) {
2723 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002724 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002725 mLock.lock();
2726 }
2727 return INVALID_OPERATION;
2728 }
2729 // abort if start is rejected by audio policy manager
2730 if (status != NO_ERROR) {
2731 return PERMISSION_DENIED;
2732 }
2733#ifdef ADD_BATTERY_DATA
2734 // to track the speaker usage
2735 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2736#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002737 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002738 }
2739
Eric Laurent51716182016-02-29 18:00:56 -08002740 // set retry count for buffer fill
2741 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002742 if (track->isStopping_1()) {
2743 track->mRetryCount = kMaxTrackStopRetriesOffload;
2744 } else {
2745 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2746 }
2747 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002748 } else {
2749 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002750 track->mFillingUpStatus =
2751 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002752 }
2753
jiabineb3bda02020-06-30 14:07:03 -07002754 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2755 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2756 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2757 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002758 // Unlock due to VibratorService will lock for this call and will
2759 // call Tracks.mute/unmute which also require thread's lock.
2760 mLock.unlock();
2761 const int intensity = AudioFlinger::onExternalVibrationStart(
2762 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002763 std::optional<media::AudioVibratorInfo> vibratorInfo;
2764 {
2765 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2766 // used to play this track.
2767 Mutex::Autolock _l(mAudioFlinger->mLock);
2768 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2769 }
jiabin57303cc2018-12-18 15:45:57 -08002770 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002771 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002772 if (vibratorInfo) {
2773 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2774 }
2775
jiabin57303cc2018-12-18 15:45:57 -08002776 // Haptic playback should be enabled by vibrator service.
2777 if (track->getHapticPlaybackEnabled()) {
2778 // Disable haptic playback of all active track to ensure only
2779 // one track playing haptic if current track should play haptic.
2780 for (const auto &t : mActiveTracks) {
2781 t->setHapticPlaybackEnabled(false);
2782 }
jiabin245cdd92018-12-07 17:55:15 -08002783 }
jiabine70bc7f2020-06-30 22:07:55 -07002784
2785 // Set haptic intensity for effect
2786 if (chain != nullptr) {
2787 chain->setHapticIntensity_l(track->id(), intensity);
2788 }
jiabin245cdd92018-12-07 17:55:15 -08002789 }
2790
Eric Laurent81784c32012-11-19 14:55:58 -08002791 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002792 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002793 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002794 if (chain != 0) {
2795 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2796 track->sessionId());
2797 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002798 }
2799
Andy Hungc2b11cb2020-04-22 09:04:01 -07002800 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002801 status = NO_ERROR;
2802 }
2803
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002804 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002805 return status;
2806}
2807
Eric Laurentbfb1b832013-01-07 09:53:42 -08002808bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002809{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002810 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002812 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2813 track->mState = TrackBase::STOPPED;
2814 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002815 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002816 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002817 if (track->isPausePending()) {
2818 track->pauseAck();
2819 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002821 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002822
2823 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002824}
2825
2826void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2827{
2828 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002829
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002830 String8 result;
2831 track->appendDump(result, false /* active */);
2832 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002833
Eric Laurent81784c32012-11-19 14:55:58 -08002834 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002835 {
2836 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2837 mAudioTrackCallbacks.erase(track);
2838 }
Eric Laurent81784c32012-11-19 14:55:58 -08002839 if (track->isFastTrack()) {
2840 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002841 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002842 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2843 mFastTrackAvailMask |= 1 << index;
2844 // redundant as track is about to be destroyed, for dumpsys only
2845 track->mFastIndex = -1;
2846 }
2847 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2848 if (chain != 0) {
2849 chain->decTrackCnt();
2850 }
2851}
2852
2853String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2854{
Eric Laurent81784c32012-11-19 14:55:58 -08002855 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002856 String8 out_s8;
2857 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2858 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002859 }
Andy Hung71ba4b32022-10-06 12:09:49 -07002860 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002861}
2862
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002863status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2864 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002865 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002866 return NO_INIT;
2867 }
2868 return mOutput->stream->selectPresentation(presentationId, programId);
2869}
2870
Mikhail Naganov88536df2021-07-26 17:30:29 -07002871void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002872 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002873 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002874 sp<AudioIoDescriptor> desc;
2875 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002876 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002877 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002878 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002879 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002880 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2881 mSampleRate, mFormat, mChannelMask,
2882 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2883 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002884 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002885 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002886 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002887 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002888 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002889 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002890 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002891 break;
2892 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002893 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002894}
2895
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002896void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002898 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899}
2900
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002901void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002903 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904}
2905
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002906void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002907{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002908 mCallbackThread->setAsyncError();
2909}
2910
jiabinf6eb4c32020-02-25 14:06:25 -08002911void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2912 const std::basic_string<uint8_t>& metadataBs)
2913{
Kuowei Li9e2f6162022-11-23 16:25:26 +08002914 wp<AudioFlinger::PlaybackThread> weakPointerThis = this;
2915 std::thread([this, metadataBs, weakPointerThis]() {
2916 sp<AudioFlinger::PlaybackThread> playbackThread = weakPointerThis.promote();
2917 if (playbackThread == nullptr) {
2918 ALOGW("PlaybackThread was destroyed, skip codec format change event");
2919 return;
2920 }
2921
jiabinf6eb4c32020-02-25 14:06:25 -08002922 audio_utils::metadata::Data metadata =
2923 audio_utils::metadata::dataFromByteString(metadataBs);
2924 if (metadata.empty()) {
2925 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2926 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2927 (int)metadataBs.size());
2928 return;
2929 }
2930
2931 audio_utils::metadata::ByteString metaDataStr =
2932 audio_utils::metadata::byteStringFromData(metadata);
2933 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2934 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002935 for (const auto& callbackPair : mAudioTrackCallbacks) {
2936 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002937 }
2938 }).detach();
2939}
2940
Eric Laurent3b4529e2013-09-05 18:09:19 -07002941void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002942{
2943 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002944 // reject out of sequence requests
2945 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2946 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002947 mWaitWorkCV.signal();
2948 }
2949}
2950
Eric Laurent3b4529e2013-09-05 18:09:19 -07002951void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002952{
2953 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002954 // reject out of sequence requests
2955 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002956 // Register discontinuity when HW drain is completed because that can cause
2957 // the timestamp frame position to reset to 0 for direct and offload threads.
2958 // (Out of sequence requests are ignored, since the discontinuity would be handled
2959 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002960 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002961 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002962 mWaitWorkCV.signal();
2963 }
2964}
2965
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002966void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002967{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002968 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002969 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2970 mSampleRate = audioConfig.sample_rate;
2971 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002972 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002973 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002974 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002975 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002976 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2977 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002978 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002979
2980 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2981 mMixerChannelMask = mChannelMask;
2982 }
2983
Andy Hunge5412692014-05-16 11:25:07 -07002984 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002985 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002986
Eric Laurentf1f22e72021-07-13 14:04:14 +02002987 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2988
Phil Burkca5e6142015-07-14 09:42:29 -07002989 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002990 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002991 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002992 // Get format from the shim, which will be different than the HAL format
2993 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002994 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002995 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002996 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002997 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002998 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002999 LOG_FATAL("HAL format %#x not supported for mixed output",
3000 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003001 }
Phil Burk062e67a2015-02-11 13:40:50 -08003002 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003003 result = mOutput->stream->getBufferSize(&mBufferSize);
3004 LOG_ALWAYS_FATAL_IF(result != OK,
3005 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003006 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003007 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003008 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003009 mFrameCount);
3010 }
3011
Eric Laurentd1f69b02014-12-15 14:33:13 -08003012 mHwSupportsPause = false;
3013 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003014 bool supportsPause = false, supportsResume = false;
3015 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3016 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003017 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003018 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003019 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003020 } else if (supportsResume) {
3021 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003022 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003023 }
3024 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003025 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3026 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3027 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003028
Andy Hungfbfc3952015-01-15 13:33:51 -08003029 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3030 // For best precision, we use float instead of the associated output
3031 // device format (typically PCM 16 bit).
3032
3033 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3034 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3035 mBufferSize = mFrameSize * mFrameCount;
3036
3037 // TODO: We currently use the associated output device channel mask and sample rate.
3038 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3039 // (if a valid mask) to avoid premature downmix.
3040 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3041 // instead of the output device sample rate to avoid loss of high frequency information.
3042 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3043 }
3044
Andy Hung09a50072014-02-27 14:30:47 -08003045 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003046 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003047 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003048 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3049 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003050 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3051 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003052
Eric Laurent81784c32012-11-19 14:55:58 -08003053 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3054 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3055 maxNormalFrameCount = maxNormalFrameCount & ~15;
3056 if (maxNormalFrameCount < minNormalFrameCount) {
3057 maxNormalFrameCount = minNormalFrameCount;
3058 }
3059 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3060 if (multiplier <= 1.0) {
3061 multiplier = 1.0;
3062 } else if (multiplier <= 2.0) {
3063 if (2 * mFrameCount <= maxNormalFrameCount) {
3064 multiplier = 2.0;
3065 } else {
3066 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3067 }
3068 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003069 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003070 }
3071 }
3072 mNormalFrameCount = multiplier * mFrameCount;
3073 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003074 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003075 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3076 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003077 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003078 mNormalFrameCount);
3079
Andy Hung08fb1742015-05-31 23:22:10 -07003080 // Check if we want to throttle the processing to no more than 2x normal rate
3081 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003082 mThreadThrottleTimeMs = 0;
3083 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003084 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3085
Andy Hung010a1a12014-03-13 13:57:33 -07003086 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3087 // Originally this was int16_t[] array, need to remove legacy implications.
3088 free(mSinkBuffer);
3089 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003090
Andy Hung5b10a202014-03-13 13:59:29 -07003091 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3092 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3093 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003094 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003095
Andy Hung69aed5f2014-02-25 17:24:40 -08003096 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3097 // drives the output.
3098 free(mMixerBuffer);
3099 mMixerBuffer = NULL;
3100 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003101 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003102 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003103 * audio_bytes_per_sample(mMixerBufferFormat);
3104 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3105 }
Andy Hung98ef9782014-03-04 14:46:50 -08003106 free(mEffectBuffer);
3107 mEffectBuffer = NULL;
3108 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003109 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003110 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003111 * audio_bytes_per_sample(mEffectBufferFormat);
3112 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3113 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003114
Eric Laurentb62d0362021-10-26 17:40:18 +02003115 if (mType == SPATIALIZER) {
3116 free(mPostSpatializerBuffer);
3117 mPostSpatializerBuffer = nullptr;
3118 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3119 * audio_bytes_per_sample(mEffectBufferFormat);
3120 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3121 }
3122
Mikhail Naganov55773032020-10-01 15:08:13 -07003123 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3124 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003125 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3126 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003127 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003128
Eric Laurent81784c32012-11-19 14:55:58 -08003129 // force reconfiguration of effect chains and engines to take new buffer size and audio
3130 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003131 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003132 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3133 // matter.
3134 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3135 Vector< sp<EffectChain> > effectChains = mEffectChains;
3136 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003137 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3138 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003139 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003140
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003141 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003142 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003143 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3144 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3145 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3146 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3147 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3148 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3149 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3150 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3151 (int32_t)mHapticChannelMask)
3152 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3153 (int32_t)mHapticChannelCount)
3154 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3155 formatToString(mHALFormat).c_str())
3156 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3157 (int32_t)mFrameCount) // sic - added HAL
3158 ;
3159 uint32_t latencyMs;
3160 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3161 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3162 }
3163 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003164}
3165
Kevin Rocard069c2712018-03-29 19:09:14 -07003166void AudioFlinger::PlaybackThread::updateMetadata_l()
3167{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003168 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003169 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003170 }
3171 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003172 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003173 for (const sp<Track> &track : mActiveTracks) {
3174 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003175 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003176 }
Kevin Rocard12381092018-04-11 09:19:59 -07003177 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003178}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003179
Kevin Rocard12381092018-04-11 09:19:59 -07003180void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3181 const StreamOutHalInterface::SourceMetadata& metadata)
3182{
3183 mOutput->stream->updateSourceMetadata(metadata);
3184};
3185
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003186status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003187{
3188 if (halFrames == NULL || dspFrames == NULL) {
3189 return BAD_VALUE;
3190 }
3191 Mutex::Autolock _l(mLock);
3192 if (initCheck() != NO_ERROR) {
3193 return INVALID_OPERATION;
3194 }
Andy Hung818e7a32016-02-16 18:08:07 -08003195 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003196 *halFrames = framesWritten;
3197
3198 if (isSuspended()) {
3199 // return an estimation of rendered frames when the output is suspended
3200 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003201 *dspFrames = (uint32_t)
3202 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003203 return NO_ERROR;
3204 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003205 status_t status;
3206 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003207 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003208 *dspFrames = (size_t)frames;
3209 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003210 }
3211}
3212
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003213product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003214{
3215 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3216 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3217 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003218 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003219 }
3220 for (size_t i = 0; i < mTracks.size(); i++) {
3221 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003222 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003223 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003224 }
3225 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003226 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003227}
3228
3229
Phil Burk062e67a2015-02-11 13:40:50 -08003230AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003231{
3232 Mutex::Autolock _l(mLock);
3233 return mOutput;
3234}
3235
Phil Burk062e67a2015-02-11 13:40:50 -08003236AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003237{
3238 Mutex::Autolock _l(mLock);
3239 AudioStreamOut *output = mOutput;
3240 mOutput = NULL;
3241 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3242 // must push a NULL and wait for ack
3243 mOutputSink.clear();
3244 mPipeSink.clear();
3245 mNormalSink.clear();
3246 return output;
3247}
3248
3249// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003250sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003251{
3252 if (mOutput == NULL) {
3253 return NULL;
3254 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003255 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003256}
3257
3258uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3259{
3260 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3261}
3262
Andy Hung068e08e2023-05-15 19:02:55 -07003263status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<audioflinger::SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003264{
3265 if (!isValidSyncEvent(event)) {
3266 return BAD_VALUE;
3267 }
3268
3269 Mutex::Autolock _l(mLock);
3270
3271 for (size_t i = 0; i < mTracks.size(); ++i) {
3272 sp<Track> track = mTracks[i];
3273 if (event->triggerSession() == track->sessionId()) {
3274 (void) track->setSyncEvent(event);
3275 return NO_ERROR;
3276 }
3277 }
3278
3279 return NAME_NOT_FOUND;
3280}
3281
Andy Hung068e08e2023-05-15 19:02:55 -07003282bool AudioFlinger::PlaybackThread::isValidSyncEvent(
3283 const sp<audioflinger::SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003284{
3285 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3286}
3287
3288void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
Jing Mike537412f2023-03-12 11:01:47 +08003289 [[maybe_unused]] const Vector< sp<Track> >& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003290{
Andy Hungfe726a62018-09-27 15:17:25 -07003291 // Miscellaneous track cleanup when removed from the active list,
3292 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003294 for (const auto& track : tracksToRemove) {
3295 if (track->isExternalTrack()) {
3296 // to track the speaker usage
3297 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003298 }
3299 }
Andy Hungfe726a62018-09-27 15:17:25 -07003300#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003301}
3302
3303void AudioFlinger::PlaybackThread::checkSilentMode_l()
3304{
3305 if (!mMasterMute) {
3306 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003307 if (mOutDeviceTypeAddrs.empty()) {
3308 ALOGD("ro.audio.silent is ignored since no output device is set");
3309 return;
3310 }
jiabinc52b1ff2019-10-31 17:20:42 -07003311 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003312 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3313 return;
3314 }
Eric Laurent81784c32012-11-19 14:55:58 -08003315 if (property_get("ro.audio.silent", value, "0") > 0) {
3316 char *endptr;
3317 unsigned long ul = strtoul(value, &endptr, 0);
3318 if (*endptr == '\0' && ul != 0) {
3319 ALOGD("Silence is golden");
3320 // The setprop command will not allow a property to be changed after
3321 // the first time it is set, so we don't have to worry about un-muting.
3322 setMasterMute_l(true);
3323 }
3324 }
3325 }
3326}
3327
3328// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003329ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003330{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003331 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003332 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003333 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003334 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003335
3336 // If an NBAIO sink is present, use it to write the normal mixer's submix
3337 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003338
Andy Hung010a1a12014-03-13 13:57:33 -07003339 const size_t count = mBytesRemaining / mFrameSize;
3340
Simon Wilson2d590962012-11-29 15:18:50 -08003341 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003342 // update the setpoint when AudioFlinger::mScreenState changes
3343 uint32_t screenState = AudioFlinger::mScreenState;
3344 if (screenState != mScreenState) {
3345 mScreenState = screenState;
3346 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3347 if (pipe != NULL) {
3348 pipe->setAvgFrames((mScreenState & 1) ?
3349 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3350 }
3351 }
Andy Hung010a1a12014-03-13 13:57:33 -07003352 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003353 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003354 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003355 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003356#ifdef TEE_SINK
3357 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3358#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003359 } else {
3360 bytesWritten = framesWritten;
3361 }
3362 // otherwise use the HAL / AudioStreamOut directly
3363 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003364 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003365
Eric Laurentbfb1b832013-01-07 09:53:42 -08003366 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003367 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3368 mWriteAckSequence += 2;
3369 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003370 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003371 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003372 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003373 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003374 // FIXME We should have an implementation of timestamps for direct output threads.
3375 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003376 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003377 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003378
Eric Laurentbfb1b832013-01-07 09:53:42 -08003379 if (mUseAsyncWrite &&
3380 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3381 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003382 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003383 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003384 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003385 }
Eric Laurent81784c32012-11-19 14:55:58 -08003386 }
3387
Eric Laurent81784c32012-11-19 14:55:58 -08003388 mNumWrites++;
3389 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003390 if (mStandby) {
3391 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003392 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003393 mStandby = false;
3394 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003395 return bytesWritten;
3396}
3397
3398void AudioFlinger::PlaybackThread::threadLoop_drain()
3399{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003400 bool supportsDrain = false;
3401 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003402 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3403 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003404 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3405 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003406 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003407 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003408 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003409 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003410 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003411 }
3412}
3413
3414void AudioFlinger::PlaybackThread::threadLoop_exit()
3415{
Eric Laurent275e8e92014-11-30 15:14:47 -08003416 {
3417 Mutex::Autolock _l(mLock);
3418 for (size_t i = 0; i < mTracks.size(); i++) {
3419 sp<Track> track = mTracks[i];
3420 track->invalidate();
3421 }
Andy Hungdae27702016-10-31 14:01:16 -07003422 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3423 // After we exit there are no more track changes sent to BatteryNotifier
3424 // because that requires an active threadLoop.
3425 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3426 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003427 }
Eric Laurent81784c32012-11-19 14:55:58 -08003428}
3429
3430/*
3431The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003432 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003433 - mActiveSleepTimeUs from activeSleepTimeUs()
3434 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003435 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3436 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003437 - maxPeriod from frame count and sample rate (MIXER only)
3438
3439The parameters that affect these derived values are:
3440 - frame count
3441 - frame size
3442 - sample rate
3443 - device type: A2DP or not
3444 - device latency
3445 - format: PCM or not
3446 - active sleep time
3447 - idle sleep time
3448*/
3449
3450void AudioFlinger::PlaybackThread::cacheParameters_l()
3451{
Andy Hung25c2dac2014-02-27 14:56:00 -08003452 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003453 mActiveSleepTimeUs = activeSleepTimeUs();
3454 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003455
3456 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3457 // truncating audio when going to standby.
3458 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003459 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003460 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3461 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3462 }
3463 }
Eric Laurent81784c32012-11-19 14:55:58 -08003464}
3465
Eric Laurent13084622016-05-17 10:51:49 -07003466bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003467{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003468 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003469 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003470 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003471 size_t size = mTracks.size();
3472 for (size_t i = 0; i < size; i++) {
3473 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003474 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003475 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003476 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003477 }
3478 }
Eric Laurent13084622016-05-17 10:51:49 -07003479 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003480}
3481
Haynes Mathew George05317d22016-05-03 16:34:26 -07003482void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3483{
3484 Mutex::Autolock _l(mLock);
3485 invalidateTracks_l(streamType);
3486}
3487
jiabinf042b9b2021-05-07 23:46:28 +00003488// getTrackById_l must be called with holding thread lock
3489AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3490 audio_port_handle_t trackPortId) {
3491 for (size_t i = 0; i < mTracks.size(); i++) {
3492 if (mTracks[i]->portId() == trackPortId) {
3493 return mTracks[i].get();
3494 }
3495 }
3496 return nullptr;
3497}
3498
Eric Laurent81784c32012-11-19 14:55:58 -08003499status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3500{
Glenn Kastend848eb42016-03-08 13:42:11 -08003501 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003502 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003503 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003504
Andy Hungd3639922022-04-28 18:00:49 -07003505 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003506 if (!audio_is_global_session(session)) {
3507 // player sessions on a spatializer output will use a dedicated input buffer and
3508 // will either output multi channel to mEffectBuffer if the track is spatilaized
3509 // or stereo to mPostSpatializerBuffer if not spatialized.
3510 uint32_t channelMask;
3511 bool isSessionSpatialized =
3512 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3513 if (isSessionSpatialized) {
3514 channelMask = mMixerChannelMask;
3515 } else {
3516 channelMask = mChannelMask;
3517 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003518 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003519 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003520 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003521 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003522 &halInBuffer);
3523 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003524
3525 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3526 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3527 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3528 &halOutBuffer);
3529 if (result != OK) return result;
3530
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003531 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003532
Mikhail Naganov022b9952017-01-04 16:36:51 -08003533 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3534 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003535 } else {
3536 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3537 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3538 // mPostSpatializerBuffer as output buffer
3539 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
3540 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3541 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3542 if (result != OK) return result;
3543 result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3544 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3545 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003546
Eric Laurentb62d0362021-10-26 17:40:18 +02003547 if (session == AUDIO_SESSION_DEVICE) {
3548 halInBuffer = halOutBuffer;
3549 }
3550 }
3551 } else {
3552 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
3553 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3554 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3555 &halInBuffer);
3556 if (result != OK) return result;
3557 halOutBuffer = halInBuffer;
3558 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3559 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003560 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003561 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003562 // Only one effect chain can be present in direct output thread and it uses
3563 // the sink buffer as input
3564 if (mType != DIRECT) {
3565 size_t numSamples = mNormalFrameCount
3566 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3567 + mHapticChannelCount);
Andy Hung71ba4b32022-10-06 12:09:49 -07003568 const status_t allocateStatus = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003569 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003570 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003571 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003572
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003573 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003574 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3575 buffer, session);
3576 }
3577 }
3578 }
3579
3580 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // Attach all tracks with same session ID to this chain.
3582 for (size_t i = 0; i < mTracks.size(); ++i) {
3583 sp<Track> track = mTracks[i];
3584 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003585 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3586 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003587 track->setMainBuffer(buffer);
3588 chain->incTrackCnt();
3589 }
3590 }
3591
3592 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003593 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003594 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003595 ALOGV("addEffectChain_l() activating track %p on session %d",
3596 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003597 chain->incActiveTrackCnt();
3598 }
3599 }
3600 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003601
Eric Laurentaaa44472014-09-12 17:41:50 -07003602 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003603 chain->setInBuffer(halInBuffer);
3604 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003605 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3606 // chains list in order to be processed last as it contains output device effects.
3607 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3608 // processing effects specific to an output stream before effects applied to all streams
3609 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003610 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3611 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003612 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003613 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003614 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003615 // Effect chain for other sessions are inserted at beginning of effect
3616 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003617 // sessions is not important.
3618 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003619 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3620 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003621 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003622 size_t size = mEffectChains.size();
3623 size_t i = 0;
3624 for (i = 0; i < size; i++) {
3625 if (mEffectChains[i]->sessionId() < session) {
3626 break;
3627 }
3628 }
3629 mEffectChains.insertAt(chain, i);
3630 checkSuspendOnAddEffectChain_l(chain);
3631
3632 return NO_ERROR;
3633}
3634
3635size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3636{
Glenn Kastend848eb42016-03-08 13:42:11 -08003637 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003638
3639 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3640
3641 for (size_t i = 0; i < mEffectChains.size(); i++) {
3642 if (chain == mEffectChains[i]) {
3643 mEffectChains.removeAt(i);
3644 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003645 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003646 if (session == track->sessionId()) {
3647 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3648 chain.get(), session);
3649 chain->decActiveTrackCnt();
3650 }
3651 }
3652
3653 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003654 for (size_t j = 0; j < mTracks.size(); ++j) {
3655 sp<Track> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003656 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003657 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003658 chain->decTrackCnt();
3659 }
3660 }
3661 break;
3662 }
3663 }
3664 return mEffectChains.size();
3665}
3666
3667status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003668 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003669{
3670 Mutex::Autolock _l(mLock);
3671 return attachAuxEffect_l(track, EffectId);
3672}
3673
3674status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003675 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003676{
3677 status_t status = NO_ERROR;
3678
3679 if (EffectId == 0) {
3680 track->setAuxBuffer(0, NULL);
3681 } else {
3682 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3683 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3684 if (effect != 0) {
3685 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3686 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3687 } else {
3688 status = INVALID_OPERATION;
3689 }
3690 } else {
3691 status = BAD_VALUE;
3692 }
3693 }
3694 return status;
3695}
3696
3697void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3698{
3699 for (size_t i = 0; i < mTracks.size(); ++i) {
3700 sp<Track> track = mTracks[i];
3701 if (track->auxEffectId() == effectId) {
3702 attachAuxEffect_l(track, 0);
3703 }
3704 }
3705}
3706
3707bool AudioFlinger::PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003708NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003709{
Glenn Kasten388d5712017-04-07 14:38:41 -07003710 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003711
Eric Laurent81784c32012-11-19 14:55:58 -08003712 Vector< sp<Track> > tracksToRemove;
3713
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003714 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003715 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003716
3717 // MIXER
3718 nsecs_t lastWarning = 0;
3719
3720 // DUPLICATING
3721 // FIXME could this be made local to while loop?
3722 writeFrames = 0;
3723
3724 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003725 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003726
Andy Hungd3639922022-04-28 18:00:49 -07003727 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003728 sleepTimeShift = 0;
3729 }
3730
3731 CpuStats cpuStats;
3732 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3733
3734 acquireWakeLock();
3735
Glenn Kasteneef598c2017-04-03 14:41:13 -07003736 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3737 // thread associated with this PlaybackThread.
3738 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3739 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003740 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3741 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003742 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003743 const char *logString = NULL;
3744
rago1bb90822017-05-02 18:31:48 -07003745 // Estimated time for next buffer to be written to hal. This is used only on
3746 // suspended mode (for now) to help schedule the wait time until next iteration.
3747 nsecs_t timeLoopNextNs = 0;
3748
Eric Laurent664539d2013-09-23 18:24:31 -07003749 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003750
Andy Hung2dbffc22018-08-08 18:50:41 -07003751 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003752
Eric Laurentb3f315a2021-07-13 15:09:05 +02003753 sendCheckOutputStageEffectsEvent();
3754
Andy Hung446f4df2019-02-21 12:26:41 -08003755 // loopCount is used for statistics and diagnostics.
3756 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003757 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003758 // Log merge requests are performed during AudioFlinger binder transactions, but
3759 // that does not cover audio playback. It's requested here for that reason.
3760 mAudioFlinger->requestLogMerge();
3761
Eric Laurent81784c32012-11-19 14:55:58 -08003762 cpuStats.sample(myName);
3763
3764 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003765 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003766 bool isHapticSessionSpatialized = false;
Andy Hungc1646382019-04-30 16:12:10 -07003767 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003768
Andy Hung2dbffc22018-08-08 18:50:41 -07003769 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3770 //
jiabinc52b1ff2019-10-31 17:20:42 -07003771 // Note: we access outDeviceTypes() outside of mLock.
3772 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003773 // Here, we try for the AF lock, but do not block on it as the latency
3774 // is more informational.
3775 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3776 std::vector<PatchPanel::SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003777 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003778 status_t status = INVALID_OPERATION;
3779 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3780 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3781 && swPatches.size() > 0) {
3782 status = swPatches[0].getLatencyMs_l(&latencyMs);
3783 downstreamPatchHandle = swPatches[0].getPatchHandle();
3784 }
3785 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003786 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003787 lastDownstreamPatchHandle = downstreamPatchHandle;
3788 }
3789 if (status == OK) {
3790 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003791 // latency of 5 seconds).
3792 const double minLatency = 0., maxLatency = 5000.;
3793 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003794 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003795 } else {
3796 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07003797 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003798 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003799 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003800 }
3801 mAudioFlinger->mLock.unlock();
3802 }
3803 } else {
3804 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3805 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003806 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003807 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3808 }
3809 }
3810
Eric Laurentb3f315a2021-07-13 15:09:05 +02003811 if (mCheckOutputStageEffects.exchange(false)) {
3812 checkOutputStageEffects();
3813 }
3814
Eric Laurent81784c32012-11-19 14:55:58 -08003815 { // scope for mLock
3816
3817 Mutex::Autolock _l(mLock);
3818
Eric Laurent021cf962014-05-13 10:18:14 -07003819 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003820 if (mCheckOutputStageEffects.load()) {
3821 continue;
3822 }
Eric Laurent10351942014-05-08 18:49:52 -07003823
Glenn Kasteneef598c2017-04-03 14:41:13 -07003824 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003825 if (logString != NULL) {
3826 mNBLogWriter->logTimestamp();
3827 mNBLogWriter->log(logString);
3828 logString = NULL;
3829 }
3830
Dean Wheatley12473e92021-03-18 23:00:55 +11003831 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003832
Eric Laurent81784c32012-11-19 14:55:58 -08003833 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003834 if (mSignalPending) {
3835 // A signal was raised while we were unlocked
3836 mSignalPending = false;
3837 } else if (waitingAsyncCallback_l()) {
3838 if (exitPending()) {
3839 break;
3840 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003841 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003842 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003843 releaseWakeLock_l();
3844 released = true;
3845 }
Andy Hung10cbff12017-02-21 17:30:14 -08003846
3847 const int64_t waitNs = computeWaitTimeNs_l();
3848 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3849 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3850 if (status == TIMED_OUT) {
3851 mSignalPending = true; // if timeout recheck everything
3852 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003853 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003854 if (released) {
3855 acquireWakeLock_l();
3856 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003857 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3858 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003859
3860 continue;
3861 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003862 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003863 isSuspended()) {
3864 // put audio hardware into standby after short delay
3865 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003866
3867 threadLoop_standby();
3868
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003869 // This is where we go into standby
3870 if (!mStandby) {
3871 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003872 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003873 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07003874 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003875 }
Andy Hungd0979812019-02-21 15:51:44 -08003876 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003877 }
3878
Eric Tan39ec8d62018-07-24 09:49:29 -07003879 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003880 // we're about to wait, flush the binder command buffer
3881 IPCThreadState::self()->flushCommands();
3882
3883 clearOutputTracks();
3884
3885 if (exitPending()) {
3886 break;
3887 }
3888
3889 releaseWakeLock_l();
3890 // wait until we have something to do...
3891 ALOGV("%s going to sleep", myName.string());
3892 mWaitWorkCV.wait(mLock);
3893 ALOGV("%s waking up", myName.string());
3894 acquireWakeLock_l();
3895
3896 mMixerStatus = MIXER_IDLE;
3897 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3898 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003899 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003900 checkSilentMode_l();
3901
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003902 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3903 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07003904 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003905 sleepTimeShift = 0;
3906 }
3907
3908 continue;
3909 }
3910 }
Eric Laurent81784c32012-11-19 14:55:58 -08003911 // mMixerStatusIgnoringFastTracks is also updated internally
3912 mMixerStatus = prepareTracks_l(&tracksToRemove);
3913
Andy Hungdae27702016-10-31 14:01:16 -07003914 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003915
Kevin Rocard069c2712018-03-29 19:09:14 -07003916 updateMetadata_l();
3917
Eric Laurent81784c32012-11-19 14:55:58 -08003918 // prevent any changes in effect chain list and in each effect chain
3919 // during mixing and effect process as the audio buffers could be deleted
3920 // or modified if an effect is created or deleted
3921 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003922
3923 // Determine which session to pick up haptic data.
3924 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003925 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003926 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02003927 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003928 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003929 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02003930 if (effectChain != nullptr
3931 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07003932 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003933 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003934 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07003935 break;
3936 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003937 if (activeHapticSessionId == AUDIO_SESSION_NONE
3938 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07003939 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02003940 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02003941 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07003942 }
3943 }
3944 }
3945
Andy Hungc1646382019-04-30 16:12:10 -07003946 // Acquire a local copy of active tracks with lock (release w/o lock).
3947 //
3948 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3949 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3950 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3951 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02003952
3953 setHalLatencyMode_l();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003954 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003955
Eric Laurentbfb1b832013-01-07 09:53:42 -08003956 if (mBytesRemaining == 0) {
3957 mCurrentWriteLength = 0;
3958 if (mMixerStatus == MIXER_TRACKS_READY) {
3959 // threadLoop_mix() sets mCurrentWriteLength
3960 threadLoop_mix();
3961 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3962 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003963 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003964 // must be written to HAL
3965 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003966 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003967 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003968
3969 // Tally underrun frames as we are inserting 0s here.
3970 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003971 if (track->mFillingUpStatus == Track::FS_ACTIVE
3972 && !track->isStopped()
3973 && !track->isPaused()
3974 && !track->isTerminated()) {
3975 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3976 __func__, track->id(), track->getTrackStateAsString(),
3977 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003978 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3979 }
3980 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003981 }
3982 }
Andy Hung98ef9782014-03-04 14:46:50 -08003983 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003984 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003985 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3986 // or mSinkBuffer (if there are no effects).
3987 //
3988 // This is done pre-effects computation; if effects change to
3989 // support higher precision, this needs to move.
3990 //
3991 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003992 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003993 uint32_t mixerChannelCount = mEffectBufferValid ?
3994 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003995 if (mMixerBufferValid) {
3996 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3997 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3998
David Li88ee0902022-06-22 10:01:21 +08003999 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4000 // do these processes after effects are applied.
4001 if (!mEffectBufferValid) {
4002 // mono blend occurs for mixer threads only (not direct or offloaded)
4003 // and is handled here if we're going directly to the sink.
4004 if (requireMonoBlend()) {
4005 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4006 mNormalFrameCount, true /*limit*/);
4007 }
Andy Hung2ddee192015-12-18 17:34:44 -08004008
David Li88ee0902022-06-22 10:01:21 +08004009 if (!hasFastMixer()) {
4010 // Balance must take effect after mono conversion.
4011 // We do it here if there is no FastMixer.
4012 // mBalance detects zero balance within the class for speed
4013 // (not needed here).
4014 mBalance.setBalance(mMasterBalance.load());
4015 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4016 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004017 }
4018
Andy Hung98ef9782014-03-04 14:46:50 -08004019 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004020 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004021
4022 // If we're going directly to the sink and there are haptic channels,
4023 // we should adjust channels as the sample data is partially interleaved
4024 // in this case.
4025 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4026 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4027 mChannelCount + mHapticChannelCount,
4028 audio_bytes_per_sample(format),
4029 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4030 }
Andy Hung98ef9782014-03-04 14:46:50 -08004031 }
4032
Eric Laurentbfb1b832013-01-07 09:53:42 -08004033 mBytesRemaining = mCurrentWriteLength;
4034 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004035 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4036 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4037 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4038 mBytesWritten += mBytesRemaining;
4039 mFramesWritten += framesRemaining;
4040 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004041 mBytesRemaining = 0;
4042 }
Eric Laurent81784c32012-11-19 14:55:58 -08004043
Eric Laurentbfb1b832013-01-07 09:53:42 -08004044 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004045 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004046 for (size_t i = 0; i < effectChains.size(); i ++) {
4047 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004048 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004049 if (activeHapticSessionId != AUDIO_SESSION_NONE
4050 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004051 // Haptic data is active in this case, copy it directly from
4052 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004053 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4054 audio_channel_count_from_out_mask(mMixerChannelMask) :
4055 mChannelCount;
4056 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4057 hapticSessionChannelCount = mChannelCount;
4058 }
4059
jiabin47affe52019-04-04 18:02:07 -07004060 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004061 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004062 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004063 memcpy_by_audio_format(
4064 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004065 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004066 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004067 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004068 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004069 }
Eric Laurent81784c32012-11-19 14:55:58 -08004070 }
4071 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004072 // Process effect chains for offloaded thread even if no audio
4073 // was read from audio track: process only updates effect state
4074 // and thus does have to be synchronized with audio writes but may have
4075 // to be called while waiting for async write callback
4076 if (mType == OFFLOAD) {
4077 for (size_t i = 0; i < effectChains.size(); i ++) {
4078 effectChains[i]->process_l();
4079 }
4080 }
Eric Laurent81784c32012-11-19 14:55:58 -08004081
Andy Hung98ef9782014-03-04 14:46:50 -08004082 // Only if the Effects buffer is enabled and there is data in the
4083 // Effects buffer (buffer valid), we need to
4084 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004085 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08004086 if (mEffectBufferValid) {
4087 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004088 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004089 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004090 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004091 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004092 }
4093
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004094 if (!hasFastMixer()) {
4095 // Balance must take effect after mono conversion.
4096 // We do it here if there is no FastMixer.
4097 // mBalance detects zero balance within the class for speed (not needed here).
4098 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004099 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004100 }
4101
Eric Laurentb62d0362021-10-26 17:40:18 +02004102 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4103 // mPostSpatializerBuffer if the haptics track is spatialized.
4104 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4105 // For other thread types, the haptics channels are already in mEffectBuffer.
4106 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4107 const size_t srcBufferSize = mNormalFrameCount *
4108 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4109 mEffectBufferFormat);
4110 const size_t dstBufferSize = mNormalFrameCount
4111 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4112
4113 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4114 mEffectBufferFormat,
4115 (uint8_t*)mEffectBuffer + srcBufferSize,
4116 mEffectBufferFormat,
4117 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004118 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004119 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4120 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4121 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4122 // Clamp PCM float values more than this distance from 0 to insulate
4123 // a HAL which doesn't handle NaN correctly.
4124 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4125 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4126 static_cast<const float*>(effectBuffer),
4127 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4128 } else {
4129 memcpy_by_audio_format(mSinkBuffer, mFormat,
4130 effectBuffer, mEffectBufferFormat, framesToCopy);
4131 }
jiabin245cdd92018-12-07 17:55:15 -08004132 // The sample data is partially interleaved when haptic channels exist,
4133 // we need to adjust channels here.
4134 if (mHapticChannelCount > 0) {
4135 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4136 mChannelCount + mHapticChannelCount,
4137 audio_bytes_per_sample(mFormat),
4138 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4139 }
Andy Hung98ef9782014-03-04 14:46:50 -08004140 }
4141
Eric Laurent81784c32012-11-19 14:55:58 -08004142 // enable changes in effect chain
4143 unlockEffectChains(effectChains);
4144
Eric Laurentbfb1b832013-01-07 09:53:42 -08004145 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004146 // mSleepTimeUs == 0 means we must write to audio hardware
4147 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004148 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004149 // writePeriodNs is updated >= 0 when ret > 0.
4150 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004151 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004152 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004153 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004154 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004155 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004156 if (ret < 0) {
4157 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004158 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004159 mBytesWritten += ret;
4160 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004161 const int64_t frames = ret / mFrameSize;
4162 mFramesWritten += frames;
4163
4164 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4165 // process information relating to write time.
4166 if (audio_has_proportional_frames(mFormat)) {
4167 // we are in a continuous mixing cycle
4168 if (mMixerStatus == MIXER_TRACKS_READY &&
4169 loopCount == lastLoopCountWritten + 1) {
4170
4171 const double jitterMs =
4172 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4173 {frames, writePeriodNs},
4174 {0, 0} /* lastTimestamp */, mSampleRate);
4175 const double processMs =
4176 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4177
4178 Mutex::Autolock _l(mLock);
4179 mIoJitterMs.add(jitterMs);
4180 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004181
4182 if (mPipeSink.get() != nullptr) {
4183 // Using the Monopipe availableToWrite, we estimate the current
4184 // buffer size.
4185 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4186 const ssize_t
4187 availableToWrite = mPipeSink->availableToWrite();
4188 const size_t pipeFrames = monoPipe->maxFrames();
4189 const size_t
4190 remainingFrames = pipeFrames - max(availableToWrite, 0);
4191 mMonopipePipeDepthStats.add(remainingFrames);
4192 }
Andy Hung446f4df2019-02-21 12:26:41 -08004193 }
4194
4195 // write blocked detection
4196 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004197 if ((mType == MIXER || mType == SPATIALIZER)
4198 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004199 mNumDelayedWrites++;
4200 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4201 ATRACE_NAME("underrun");
4202 ALOGW("write blocked for %lld msecs, "
4203 "%d delayed writes, thread %d",
4204 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4205 mNumDelayedWrites, mId);
4206 lastWarning = lastIoEndNs;
4207 }
4208 }
4209 }
4210 // update timing info.
4211 mLastIoBeginNs = lastIoBeginNs;
4212 mLastIoEndNs = lastIoEndNs;
4213 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004214 }
4215 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4216 (mMixerStatus == MIXER_DRAIN_ALL)) {
4217 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004218 }
Andy Hungd3639922022-04-28 18:00:49 -07004219 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004220
4221 if (mThreadThrottle
4222 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004223 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004224 // Limit MixerThread data processing to no more than twice the
4225 // expected processing rate.
4226 //
4227 // This helps prevent underruns with NuPlayer and other applications
4228 // which may set up buffers that are close to the minimum size, or use
4229 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4230 //
4231 // The throttle smooths out sudden large data drains from the device,
4232 // e.g. when it comes out of standby, which often causes problems with
4233 // (1) mixer threads without a fast mixer (which has its own warm-up)
4234 // (2) minimum buffer sized tracks (even if the track is full,
4235 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004236 //
4237 // Total time spent in last processing cycle equals time spent in
4238 // 1. threadLoop_write, as well as time spent in
4239 // 2. threadLoop_mix (significant for heavy mixing, especially
4240 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004241
Andy Hung446f4df2019-02-21 12:26:41 -08004242 // it's OK if deltaMs is an overestimate.
4243
4244 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004245
Ivan Lozanoea04d392017-11-07 14:37:07 -08004246 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004247 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004248 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004249
Andy Hung08fb1742015-05-31 23:22:10 -07004250 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004251 // notify of throttle start on verbose log
4252 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4253 "mixer(%p) throttle begin:"
4254 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004255 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004256 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004257 // Throttle must be attributed to the previous mixer loop's write time
4258 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004259 // This also ensures proper timing statistics.
4260 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004261 } else {
4262 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4263 if (diff > 0) {
4264 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004265 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004266 ALOGD_IF(!isSingleDeviceType(
4267 outDeviceTypes(), audio_is_a2dp_out_device) &&
4268 !isSingleDeviceType(
4269 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004270 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004271 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4272 }
Andy Hung08fb1742015-05-31 23:22:10 -07004273 }
4274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004275 }
Eric Laurent81784c32012-11-19 14:55:58 -08004276
Eric Laurentbfb1b832013-01-07 09:53:42 -08004277 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004278 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004279 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004280 // suspended requires accurate metering of sleep time.
4281 if (isSuspended()) {
4282 // advance by expected sleepTime
4283 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4284 const nsecs_t nowNs = systemTime();
4285
4286 // compute expected next time vs current time.
4287 // (negative deltas are treated as delays).
4288 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4289 if (deltaNs < -kMaxNextBufferDelayNs) {
4290 // Delays longer than the max allowed trigger a reset.
4291 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4292 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4293 timeLoopNextNs = nowNs + deltaNs;
4294 } else if (deltaNs < 0) {
4295 // Delays within the max delay allowed: zero the delta/sleepTime
4296 // to help the system catch up in the next iteration(s)
4297 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4298 deltaNs = 0;
4299 }
4300 // update sleep time (which is >= 0)
4301 mSleepTimeUs = deltaNs / 1000;
4302 }
Eric Laurente93cc032016-05-05 10:15:10 -07004303 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4304 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004305 }
Glenn Kastene7754022014-10-31 12:11:26 -07004306 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307 }
Eric Laurent81784c32012-11-19 14:55:58 -08004308 }
4309
4310 // Finally let go of removed track(s), without the lock held
4311 // since we can't guarantee the destructors won't acquire that
4312 // same lock. This will also mutate and push a new fast mixer state.
4313 threadLoop_removeTracks(tracksToRemove);
4314 tracksToRemove.clear();
4315
4316 // FIXME I don't understand the need for this here;
4317 // it was in the original code but maybe the
4318 // assignment in saveOutputTracks() makes this unnecessary?
4319 clearOutputTracks();
4320
4321 // Effect chains will be actually deleted here if they were removed from
4322 // mEffectChains list during mixing or effects processing
4323 effectChains.clear();
4324
4325 // FIXME Note that the above .clear() is no longer necessary since effectChains
4326 // is now local to this block, but will keep it for now (at least until merge done).
4327 }
4328
Eric Laurentbfb1b832013-01-07 09:53:42 -08004329 threadLoop_exit();
4330
Eric Laurentcf817a22014-08-04 20:36:31 -07004331 if (!mStandby) {
4332 threadLoop_standby();
4333 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004334 }
4335
4336 releaseWakeLock();
4337
4338 ALOGV("Thread %p type %d exiting", this, mType);
4339 return false;
4340}
4341
Dean Wheatley12473e92021-03-18 23:00:55 +11004342void AudioFlinger::PlaybackThread::collectTimestamps_l()
4343{
Dean Wheatley12473e92021-03-18 23:00:55 +11004344 if (mStandby) {
4345 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4346 return;
4347 } else if (mHwPaused) {
4348 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4349 return;
4350 }
4351
4352 // Gather the framesReleased counters for all active tracks,
4353 // and associate with the sink frames written out. We need
4354 // this to convert the sink timestamp to the track timestamp.
4355 bool kernelLocationUpdate = false;
4356 ExtendedTimestamp timestamp; // use private copy to fetch
4357
4358 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4359 // HAL may be draining some small duration buffered data for fade out.
4360 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4361 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4362 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4363 mSampleRate);
4364
4365 if (isTimestampCorrectionEnabled()) {
4366 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4367 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4368 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4369 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4370 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4371 = correctedTimestamp.mFrames;
4372 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4373 = correctedTimestamp.mTimeNs;
4374 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4375 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4376 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4377
4378 // Note: Downstream latency only added if timestamp correction enabled.
4379 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4380 const int64_t newPosition =
4381 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4382 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4383 // prevent retrograde
4384 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4385 newPosition,
4386 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4387 - mSuspendedFrames));
4388 }
4389 }
4390
4391 // We always fetch the timestamp here because often the downstream
4392 // sink will block while writing.
4393
4394 // We keep track of the last valid kernel position in case we are in underrun
4395 // and the normal mixer period is the same as the fast mixer period, or there
4396 // is some error from the HAL.
4397 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4398 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4399 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4400 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4401 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4402
4403 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4404 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4405 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4406 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4407 }
4408
4409 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4410 kernelLocationUpdate = true;
4411 } else {
4412 ALOGVV("getTimestamp error - no valid kernel position");
4413 }
4414
4415 // copy over kernel info
4416 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4417 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4418 + mSuspendedFrames; // add frames discarded when suspended
4419 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4420 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4421 } else {
4422 mTimestampVerifier.error();
4423 }
4424
4425 // mFramesWritten for non-offloaded tracks are contiguous
4426 // even after standby() is called. This is useful for the track frame
4427 // to sink frame mapping.
4428 bool serverLocationUpdate = false;
4429 if (mFramesWritten != mLastFramesWritten) {
4430 serverLocationUpdate = true;
4431 mLastFramesWritten = mFramesWritten;
4432 }
4433 // Only update timestamps if there is a meaningful change.
4434 // Either the kernel timestamp must be valid or we have written something.
4435 if (kernelLocationUpdate || serverLocationUpdate) {
4436 if (serverLocationUpdate) {
4437 // use the time before we called the HAL write - it is a bit more accurate
4438 // to when the server last read data than the current time here.
4439 //
4440 // If we haven't written anything, mLastIoBeginNs will be -1
4441 // and we use systemTime().
4442 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4443 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4444 ? systemTime() : mLastIoBeginNs;
4445 }
4446
4447 for (const sp<Track> &t : mActiveTracks) {
4448 if (!t->isFastTrack()) {
4449 t->updateTrackFrameInfo(
4450 t->mAudioTrackServerProxy->framesReleased(),
4451 mFramesWritten,
4452 mSampleRate,
4453 mTimestamp);
4454 }
4455 }
4456 }
4457
4458 if (audio_has_proportional_frames(mFormat)) {
4459 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4460 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4461 mLatencyMs.add(latencyMs);
4462 }
4463 }
4464#if 0
4465 // logFormat example
4466 if (z % 100 == 0) {
4467 timespec ts;
4468 clock_gettime(CLOCK_MONOTONIC, &ts);
4469 LOGT("This is an integer %d, this is a float %f, this is my "
4470 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4471 LOGT("A deceptive null-terminated string %\0");
4472 }
4473 ++z;
4474#endif
4475}
4476
Eric Laurentbfb1b832013-01-07 09:53:42 -08004477// removeTracks_l() must be called with ThreadBase::mLock held
4478void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
Andy Hung71ba4b32022-10-06 12:09:49 -07004479NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480{
Andy Hungfe726a62018-09-27 15:17:25 -07004481 for (const auto& track : tracksToRemove) {
4482 mActiveTracks.remove(track);
4483 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4484 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4485 if (chain != 0) {
4486 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4487 __func__, track->id(), chain.get(), track->sessionId());
4488 chain->decActiveTrackCnt();
4489 }
4490 // If an external client track, inform APM we're no longer active, and remove if needed.
4491 // We do this under lock so that the state is consistent if the Track is destroyed.
4492 if (track->isExternalTrack()) {
4493 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004494 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004495 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004496 }
4497 }
Andy Hungfe726a62018-09-27 15:17:25 -07004498 if (track->isTerminated()) {
4499 // remove from our tracks vector
4500 removeTrack_l(track);
4501 }
jiabineb3bda02020-06-30 14:07:03 -07004502 if (mHapticChannelCount > 0 &&
4503 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4504 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004505 mLock.unlock();
4506 // Unlock due to VibratorService will lock for this call and will
4507 // call Tracks.mute/unmute which also require thread's lock.
4508 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4509 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004510
4511 // When the track is stop, set the haptic intensity as MUTE
4512 // for the HapticGenerator effect.
4513 if (chain != nullptr) {
4514 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4515 }
jiabin245cdd92018-12-07 17:55:15 -08004516 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004517 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004518}
Eric Laurent81784c32012-11-19 14:55:58 -08004519
Eric Laurentaccc1472013-09-20 09:36:34 -07004520status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4521{
4522 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004523 ExtendedTimestamp ets;
4524 status_t status = mNormalSink->getTimestamp(ets);
4525 if (status == NO_ERROR) {
4526 status = ets.getBestTimestamp(&timestamp);
4527 }
4528 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004529 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004530 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004531 collectTimestamps_l();
4532 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4533 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004534 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004535 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4536 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4537 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4538 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4539 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004540 }
4541 return INVALID_OPERATION;
4542}
Eric Laurent1c333e22014-05-20 10:48:17 -07004543
Eric Laurenteab90452019-06-24 15:17:46 -07004544// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4545// still applied by the mixer.
4546// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4547// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4548// if more than one track are active
4549status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4550{
4551 status_t result = NO_ERROR;
4552 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4553 if (*volume != mLeftVolFloat) {
4554 result = mOutput->stream->setVolume(*volume, *volume);
4555 ALOGE_IF(result != OK,
4556 "Error when setting output stream volume: %d", result);
4557 if (result == NO_ERROR) {
4558 mLeftVolFloat = *volume;
4559 }
4560 }
4561 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4562 // remove stream volume contribution from software volume.
4563 if (mLeftVolFloat == *volume) {
4564 *volume = 1.0f;
4565 }
4566 }
4567 return result;
4568}
4569
Eric Laurent054d9d32015-04-24 08:48:48 -07004570status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4571 audio_patch_handle_t *handle)
4572{
Andy Hungf60abce2016-08-26 11:37:54 -07004573 status_t status;
4574 if (property_get_bool("af.patch_park", false /* default_value */)) {
4575 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4576 // or if HAL does not properly lock against access.
4577 AutoPark<FastMixer> park(mFastMixer);
4578 status = PlaybackThread::createAudioPatch_l(patch, handle);
4579 } else {
4580 status = PlaybackThread::createAudioPatch_l(patch, handle);
4581 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004582 return status;
4583}
4584
Eric Laurent1c333e22014-05-20 10:48:17 -07004585status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4586 audio_patch_handle_t *handle)
4587{
4588 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004589
4590 // store new device and send to effects
4591 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004592 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004593 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004594 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4595 && !mOutput->audioHwDev->supportsAudioPatches(),
4596 "Enumerated device type(%#x) must not be used "
4597 "as it does not support audio patches",
4598 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004599 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004600 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4601 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004602 }
4603
François Gaffie0c280aa2018-07-25 10:02:15 +02004604 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004605#ifdef ADD_BATTERY_DATA
4606 // when changing the audio output device, call addBatteryData to notify
4607 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004608 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004609 uint32_t params = 0;
4610 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004611 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004612 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004613 }
4614
Eric Laurent054d9d32015-04-24 08:48:48 -07004615 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004616 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004617 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4618 }
4619
4620 if (params != 0) {
4621 addBatteryData(params);
4622 }
4623 }
4624#endif
4625
4626 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004627 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004628 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004629
jiabinc52b1ff2019-10-31 17:20:42 -07004630 // mPatch.num_sinks is not set when the thread is created so that
4631 // the first patch creation triggers an ioConfigChanged callback
4632 bool configChanged = (mPatch.num_sinks == 0) ||
4633 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004634 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004635 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004636 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004637
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004638 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004639 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4640 status = hwDevice->createAudioPatch(patch->num_sources,
4641 patch->sources,
4642 patch->num_sinks,
4643 patch->sinks,
4644 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004645 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004646 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004647 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004648 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004649 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004650
4651 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004652 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004653 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004654 // also dispatch to active AudioTracks for MediaMetrics
4655 for (const auto &track : mActiveTracks) {
4656 track->logEndInterval();
4657 track->logBeginInterval(patchSinksAsString);
4658 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004659
Eric Laurente8726fe2015-06-26 09:39:24 -07004660 if (configChanged) {
4661 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4662 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004663 return status;
4664}
4665
Eric Laurent054d9d32015-04-24 08:48:48 -07004666status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4667{
Andy Hungf60abce2016-08-26 11:37:54 -07004668 status_t status;
4669 if (property_get_bool("af.patch_park", false /* default_value */)) {
4670 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4671 // or if HAL does not properly lock against access.
4672 AutoPark<FastMixer> park(mFastMixer);
4673 status = PlaybackThread::releaseAudioPatch_l(handle);
4674 } else {
4675 status = PlaybackThread::releaseAudioPatch_l(handle);
4676 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004677 return status;
4678}
4679
Eric Laurent1c333e22014-05-20 10:48:17 -07004680status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4681{
4682 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004683
jiabinc52b1ff2019-10-31 17:20:42 -07004684 mPatch = audio_patch{};
4685 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004686
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004687 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004688 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4689 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004690 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004691 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004692 }
4693 return status;
4694}
4695
Eric Laurent83b88082014-06-20 18:31:16 -07004696void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4697{
4698 Mutex::Autolock _l(mLock);
4699 mTracks.add(track);
4700}
4701
4702void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4703{
4704 Mutex::Autolock _l(mLock);
4705 destroyTrack_l(track);
4706}
4707
Mikhail Naganovdc769682018-05-04 15:34:08 -07004708void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004709{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004710 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004711 config->role = AUDIO_PORT_ROLE_SOURCE;
4712 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4713 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004714 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4715 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4716 config->flags.output = mOutput->flags;
4717 }
Eric Laurent83b88082014-06-20 18:31:16 -07004718}
4719
Eric Laurent81784c32012-11-19 14:55:58 -08004720// ----------------------------------------------------------------------------
4721
4722AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004723 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4724 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004725 // mAudioMixer below
4726 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004727 mFastMixerFutex(0),
4728 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004729 // mOutputSink below
4730 // mPipeSink below
4731 // mNormalSink below
4732{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004733 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004734 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004735 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004736 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004737 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4738 mNormalFrameCount);
4739 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4740
Andy Hungfbfc3952015-01-15 13:33:51 -08004741 if (type == DUPLICATING) {
4742 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4743 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4744 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4745 return;
4746 }
Eric Laurent81784c32012-11-19 14:55:58 -08004747 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004748 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004749 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004750 const NBAIO_Format offers[1] = {Format_from_SR_C(
4751 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004752#if !LOG_NDEBUG
4753 ssize_t index =
4754#else
4755 (void)
4756#endif
4757 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004758 ALOG_ASSERT(index == 0);
4759
4760 // initialize fast mixer depending on configuration
4761 bool initFastMixer;
Eric Laurentb62d0362021-10-26 17:40:18 +02004762 if (mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004763 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004764 } else {
4765 switch (kUseFastMixer) {
4766 case FastMixer_Never:
4767 initFastMixer = false;
4768 break;
4769 case FastMixer_Always:
4770 initFastMixer = true;
4771 break;
4772 case FastMixer_Static:
4773 case FastMixer_Dynamic:
4774 initFastMixer = mFrameCount < mNormalFrameCount;
4775 break;
4776 }
4777 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4778 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4779 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004780 }
4781 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004782 audio_format_t fastMixerFormat;
4783 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4784 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4785 } else {
4786 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4787 }
4788 if (mFormat != fastMixerFormat) {
4789 // change our Sink format to accept our intermediate precision
4790 mFormat = fastMixerFormat;
4791 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004792 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004793 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4794 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4795 }
Eric Laurent81784c32012-11-19 14:55:58 -08004796
4797 // create a MonoPipe to connect our submix to FastMixer
4798 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004799
Andy Hung1258c1a2014-05-23 21:22:17 -07004800 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004801 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004802 format.mFormat = fastMixerFormat;
4803 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4804
Eric Laurent81784c32012-11-19 14:55:58 -08004805 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4806 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4807 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4808 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07004809 const NBAIO_Format offersFast[1] = {format};
4810 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004811#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004812 ssize_t index =
4813#else
4814 (void)
4815#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07004816 monoPipe->negotiate(offersFast, std::size(offersFast),
4817 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08004818 ALOG_ASSERT(index == 0);
4819 monoPipe->setAvgFrames((mScreenState & 1) ?
4820 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4821 mPipeSink = monoPipe;
4822
Eric Laurent81784c32012-11-19 14:55:58 -08004823 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004824 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004825 FastMixerStateQueue *sq = mFastMixer->sq();
4826#ifdef STATE_QUEUE_DUMP
4827 sq->setObserverDump(&mStateQueueObserverDump);
4828 sq->setMutatorDump(&mStateQueueMutatorDump);
4829#endif
4830 FastMixerState *state = sq->begin();
4831 FastTrack *fastTrack = &state->mFastTracks[0];
4832 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4833 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4834 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004835 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4836 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4837 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004838 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004839 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004840 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004841 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004842 fastTrack->mGeneration++;
4843 state->mFastTracksGen++;
4844 state->mTrackMask = 1;
4845 // fast mixer will use the HAL output sink
4846 state->mOutputSink = mOutputSink.get();
4847 state->mOutputSinkGen++;
4848 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004849 // specify sink channel mask when haptic channel mask present as it can not
4850 // be calculated directly from channel count
4851 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004852 ? AUDIO_CHANNEL_NONE
4853 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004854 state->mCommand = FastMixerState::COLD_IDLE;
4855 // already done in constructor initialization list
4856 //mFastMixerFutex = 0;
4857 state->mColdFutexAddr = &mFastMixerFutex;
4858 state->mColdGen++;
4859 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004860 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4861 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004862 sq->end();
4863 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4864
Eric Tan0513b5d2018-09-17 10:32:48 -07004865 NBLog::thread_info_t info;
4866 info.id = mId;
4867 info.type = NBLog::FASTMIXER;
4868 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4869
Eric Laurent81784c32012-11-19 14:55:58 -08004870 // start the fast mixer
4871 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4872 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004873 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004874 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004875
4876#ifdef AUDIO_WATCHDOG
4877 // create and start the watchdog
4878 mAudioWatchdog = new AudioWatchdog();
4879 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4880 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4881 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004882 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004883#endif
Andy Hung8946a282018-04-19 20:04:56 -07004884 } else {
4885#ifdef TEE_SINK
4886 // Only use the MixerThread tee if there is no FastMixer.
4887 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4888 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4889#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004890 }
4891
4892 switch (kUseFastMixer) {
4893 case FastMixer_Never:
4894 case FastMixer_Dynamic:
4895 mNormalSink = mOutputSink;
4896 break;
4897 case FastMixer_Always:
4898 mNormalSink = mPipeSink;
4899 break;
4900 case FastMixer_Static:
4901 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4902 break;
4903 }
4904}
4905
4906AudioFlinger::MixerThread::~MixerThread()
4907{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004908 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004909 FastMixerStateQueue *sq = mFastMixer->sq();
4910 FastMixerState *state = sq->begin();
4911 if (state->mCommand == FastMixerState::COLD_IDLE) {
4912 int32_t old = android_atomic_inc(&mFastMixerFutex);
4913 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004914 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004915 }
4916 }
4917 state->mCommand = FastMixerState::EXIT;
4918 sq->end();
4919 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4920 mFastMixer->join();
4921 // Though the fast mixer thread has exited, it's state queue is still valid.
4922 // We'll use that extract the final state which contains one remaining fast track
4923 // corresponding to our sub-mix.
4924 state = sq->begin();
4925 ALOG_ASSERT(state->mTrackMask == 1);
4926 FastTrack *fastTrack = &state->mFastTracks[0];
4927 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4928 delete fastTrack->mBufferProvider;
4929 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004930 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004931#ifdef AUDIO_WATCHDOG
4932 if (mAudioWatchdog != 0) {
4933 mAudioWatchdog->requestExit();
4934 mAudioWatchdog->requestExitAndWait();
4935 mAudioWatchdog.clear();
4936 }
4937#endif
4938 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004939 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004940 delete mAudioMixer;
4941}
4942
4943
4944uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4945{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004946 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004947 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4948 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4949 }
4950 return latency;
4951}
4952
Eric Laurentbfb1b832013-01-07 09:53:42 -08004953ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004954{
4955 // FIXME we should only do one push per cycle; confirm this is true
4956 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004957 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004958 FastMixerStateQueue *sq = mFastMixer->sq();
4959 FastMixerState *state = sq->begin();
4960 if (state->mCommand != FastMixerState::MIX_WRITE &&
4961 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4962 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004963
4964 // FIXME workaround for first HAL write being CPU bound on some devices
4965 ATRACE_BEGIN("write");
4966 mOutput->write((char *)mSinkBuffer, 0);
4967 ATRACE_END();
4968
Eric Laurent81784c32012-11-19 14:55:58 -08004969 int32_t old = android_atomic_inc(&mFastMixerFutex);
4970 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004971 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004972 }
4973#ifdef AUDIO_WATCHDOG
4974 if (mAudioWatchdog != 0) {
4975 mAudioWatchdog->resume();
4976 }
4977#endif
4978 }
4979 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004980#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004981 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004982 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004983#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004984 sq->end();
4985 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4986 if (kUseFastMixer == FastMixer_Dynamic) {
4987 mNormalSink = mPipeSink;
4988 }
4989 } else {
4990 sq->end(false /*didModify*/);
4991 }
4992 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004993 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004994}
4995
4996void AudioFlinger::MixerThread::threadLoop_standby()
4997{
4998 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004999 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005000 FastMixerStateQueue *sq = mFastMixer->sq();
5001 FastMixerState *state = sq->begin();
5002 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005003 // Report any frames trapped in the Monopipe
5004 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5005 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5006 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5007 "monoPipeWritten:%lld monoPipeLeft:%lld",
5008 (long long)mFramesWritten, (long long)mSuspendedFrames,
5009 (long long)mPipeSink->framesWritten(), pipeFrames);
5010 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5011
Eric Laurent81784c32012-11-19 14:55:58 -08005012 state->mCommand = FastMixerState::COLD_IDLE;
5013 state->mColdFutexAddr = &mFastMixerFutex;
5014 state->mColdGen++;
5015 mFastMixerFutex = 0;
5016 sq->end();
5017 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5018 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5019 if (kUseFastMixer == FastMixer_Dynamic) {
5020 mNormalSink = mOutputSink;
5021 }
5022#ifdef AUDIO_WATCHDOG
5023 if (mAudioWatchdog != 0) {
5024 mAudioWatchdog->pause();
5025 }
5026#endif
5027 } else {
5028 sq->end(false /*didModify*/);
5029 }
5030 }
5031 PlaybackThread::threadLoop_standby();
5032}
5033
Eric Laurentbfb1b832013-01-07 09:53:42 -08005034bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
5035{
5036 return false;
5037}
5038
5039bool AudioFlinger::PlaybackThread::shouldStandby_l()
5040{
5041 return !mStandby;
5042}
5043
5044bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
5045{
5046 Mutex::Autolock _l(mLock);
5047 return waitingAsyncCallback_l();
5048}
5049
Eric Laurent81784c32012-11-19 14:55:58 -08005050// shared by MIXER and DIRECT, overridden by DUPLICATING
5051void AudioFlinger::PlaybackThread::threadLoop_standby()
5052{
5053 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005054 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005055 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005056 // discard any pending drain or write ack by incrementing sequence
5057 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5058 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005059 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005060 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5061 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005062 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005063 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005064 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005065}
5066
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005067void AudioFlinger::PlaybackThread::onAddNewTrack_l()
5068{
5069 ALOGV("signal playback thread");
5070 broadcast_l();
5071}
5072
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005073void AudioFlinger::PlaybackThread::onAsyncError()
5074{
5075 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5076 invalidateTracks((audio_stream_type_t)i);
5077 }
5078}
5079
Eric Laurent81784c32012-11-19 14:55:58 -08005080void AudioFlinger::MixerThread::threadLoop_mix()
5081{
Eric Laurent81784c32012-11-19 14:55:58 -08005082 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005083 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005084 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005085 // increase sleep time progressively when application underrun condition clears.
5086 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5087 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5088 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005089 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005090 sleepTimeShift--;
5091 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005092 mSleepTimeUs = 0;
5093 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005094 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005095
Eric Laurent81784c32012-11-19 14:55:58 -08005096}
5097
5098void AudioFlinger::MixerThread::threadLoop_sleepTime()
5099{
5100 // If no tracks are ready, sleep once for the duration of an output
5101 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005102 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005103 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005104 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5105 // Using the Monopipe availableToWrite, we estimate the
5106 // sleep time to retry for more data (before we underrun).
5107 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5108 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5109 const size_t pipeFrames = monoPipe->maxFrames();
5110 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5111 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5112 const size_t framesDelay = std::min(
5113 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5114 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5115 pipeFrames, framesLeft, framesDelay);
5116 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5117 } else {
5118 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5119 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5120 mSleepTimeUs = kMinThreadSleepTimeUs;
5121 }
5122 // reduce sleep time in case of consecutive application underruns to avoid
5123 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5124 // duration we would end up writing less data than needed by the audio HAL if
5125 // the condition persists.
5126 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5127 sleepTimeShift++;
5128 }
Eric Laurent81784c32012-11-19 14:55:58 -08005129 }
5130 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005131 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005132 }
5133 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005134 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5135 // before effects processing or output.
5136 if (mMixerBufferValid) {
5137 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005138 if (mType == SPATIALIZER) {
5139 memset(mSinkBuffer, 0, mSinkBufferSize);
5140 }
Andy Hung98ef9782014-03-04 14:46:50 -08005141 } else {
5142 memset(mSinkBuffer, 0, mSinkBufferSize);
5143 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005144 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005145 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5146 "anticipated start");
5147 }
5148 // TODO add standby time extension fct of effect tail
5149}
5150
5151// prepareTracks_l() must be called with ThreadBase::mLock held
5152AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5153 Vector< sp<Track> > *tracksToRemove)
5154{
Andy Hungc0691382018-09-12 18:01:57 -07005155 // clean up deleted track ids in AudioMixer before allocating new tracks
5156 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5157 // for each trackId, destroy it in the AudioMixer
5158 if (mAudioMixer->exists(trackId)) {
5159 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005160 }
5161 });
Andy Hungc0691382018-09-12 18:01:57 -07005162 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005163
5164 mixer_state mixerStatus = MIXER_IDLE;
5165 // find out which tracks need to be processed
5166 size_t count = mActiveTracks.size();
5167 size_t mixedTracks = 0;
5168 size_t tracksWithEffect = 0;
5169 // counts only _active_ fast tracks
5170 size_t fastTracks = 0;
5171 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5172
5173 float masterVolume = mMasterVolume;
5174 bool masterMute = mMasterMute;
5175
5176 if (masterMute) {
5177 masterVolume = 0;
5178 }
5179 // Delegate master volume control to effect in output mix effect chain if needed
5180 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5181 if (chain != 0) {
5182 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5183 chain->setVolume_l(&v, &v);
5184 masterVolume = (float)((v + (1 << 23)) >> 24);
5185 chain.clear();
5186 }
5187
5188 // prepare a new state to push
5189 FastMixerStateQueue *sq = NULL;
5190 FastMixerState *state = NULL;
5191 bool didModify = false;
5192 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005193 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005194 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005195 sq = mFastMixer->sq();
5196 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005197 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005198 }
5199
Andy Hung69aed5f2014-02-25 17:24:40 -08005200 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005201 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005202
Andy Hungbd3b2b02018-05-21 10:53:11 -07005203 // DeferredOperations handles statistics after setting mixerStatus.
5204 class DeferredOperations {
5205 public:
Andy Hungea840382020-05-05 21:50:17 -07005206 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5207 : mMixerStatus(mixerStatus)
5208 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005209
5210 // when leaving scope, tally frames properly.
5211 ~DeferredOperations() {
5212 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5213 // because that is when the underrun occurs.
5214 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005215 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005216 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005217 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005218 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005219 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005220 }
5221 }
Andy Hungea840382020-05-05 21:50:17 -07005222 // send the max underrun frames for this mixer period
5223 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005224 }
5225
5226 // tallyUnderrunFrames() is called to update the track counters
5227 // with the number of underrun frames for a particular mixer period.
5228 // We defer tallying until we know the final mixer status.
Andy Hung71ba4b32022-10-06 12:09:49 -07005229 void tallyUnderrunFrames(const sp<Track>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005230 mUnderrunFrames.emplace_back(track, underrunFrames);
5231 }
5232
5233 private:
5234 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005235 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005236 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005237 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005238 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005239
jiabin245cdd92018-12-07 17:55:15 -08005240 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005241 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005242 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005243
5244 // this const just means the local variable doesn't change
5245 Track* const track = t.get();
5246
5247 // process fast tracks
5248 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005249 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5250 "%s(%d): FastTrack(%d) present without FastMixer",
5251 __func__, id(), track->id());
5252
jiabin245cdd92018-12-07 17:55:15 -08005253 if (track->getHapticPlaybackEnabled()) {
5254 noFastHapticTrack = false;
5255 }
Eric Laurent81784c32012-11-19 14:55:58 -08005256
5257 // It's theoretically possible (though unlikely) for a fast track to be created
5258 // and then removed within the same normal mix cycle. This is not a problem, as
5259 // the track never becomes active so it's fast mixer slot is never touched.
5260 // The converse, of removing an (active) track and then creating a new track
5261 // at the identical fast mixer slot within the same normal mix cycle,
5262 // is impossible because the slot isn't marked available until the end of each cycle.
5263 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005264 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005265 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5266 FastTrack *fastTrack = &state->mFastTracks[j];
5267
5268 // Determine whether the track is currently in underrun condition,
5269 // and whether it had a recent underrun.
5270 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5271 FastTrackUnderruns underruns = ftDump->mUnderruns;
5272 uint32_t recentFull = (underruns.mBitFields.mFull -
5273 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5274 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5275 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5276 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5277 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5278 uint32_t recentUnderruns = recentPartial + recentEmpty;
5279 track->mObservedUnderruns = underruns;
5280 // don't count underruns that occur while stopping or pausing
5281 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005282 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005283 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5284 recentUnderruns > 0) {
5285 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005286 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005287 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005288 // Immediately account for FastTrack underruns.
5289 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005290
5291 // This is similar to the state machine for normal tracks,
5292 // with a few modifications for fast tracks.
5293 bool isActive = true;
5294 switch (track->mState) {
5295 case TrackBase::STOPPING_1:
5296 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005297 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005298 track->mState = TrackBase::STOPPING_2;
5299 }
5300 break;
5301 case TrackBase::PAUSING:
5302 // ramp down is not yet implemented
5303 track->setPaused();
5304 break;
5305 case TrackBase::RESUMING:
5306 // ramp up is not yet implemented
5307 track->mState = TrackBase::ACTIVE;
5308 break;
5309 case TrackBase::ACTIVE:
5310 if (recentFull > 0 || recentPartial > 0) {
5311 // track has provided at least some frames recently: reset retry count
5312 track->mRetryCount = kMaxTrackRetries;
5313 }
5314 if (recentUnderruns == 0) {
5315 // no recent underruns: stay active
5316 break;
5317 }
5318 // there has recently been an underrun of some kind
5319 if (track->sharedBuffer() == 0) {
5320 // were any of the recent underruns "empty" (no frames available)?
5321 if (recentEmpty == 0) {
5322 // no, then ignore the partial underruns as they are allowed indefinitely
5323 break;
5324 }
5325 // there has recently been an "empty" underrun: decrement the retry counter
5326 if (--(track->mRetryCount) > 0) {
5327 break;
5328 }
5329 // indicate to client process that the track was disabled because of underrun;
5330 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005331 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005332 // remove from active list, but state remains ACTIVE [confusing but true]
5333 isActive = false;
5334 break;
5335 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005336 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005337 case TrackBase::STOPPING_2:
5338 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005339 case TrackBase::STOPPED:
5340 case TrackBase::FLUSHED: // flush() while active
5341 // Check for presentation complete if track is inactive
5342 // We have consumed all the buffers of this track.
5343 // This would be incomplete if we auto-paused on underrun
5344 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005345 uint32_t latency = 0;
5346 status_t result = mOutput->stream->getLatency(&latency);
5347 ALOGE_IF(result != OK,
5348 "Error when retrieving output stream latency: %d", result);
5349 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005350 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005351 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5352 // track stays in active list until presentation is complete
5353 break;
5354 }
5355 }
5356 if (track->isStopping_2()) {
5357 track->mState = TrackBase::STOPPED;
5358 }
5359 if (track->isStopped()) {
5360 // Can't reset directly, as fast mixer is still polling this track
5361 // track->reset();
5362 // So instead mark this track as needing to be reset after push with ack
5363 resetMask |= 1 << i;
5364 }
5365 isActive = false;
5366 break;
5367 case TrackBase::IDLE:
5368 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005369 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005370 }
5371
5372 if (isActive) {
5373 // was it previously inactive?
5374 if (!(state->mTrackMask & (1 << j))) {
5375 ExtendedAudioBufferProvider *eabp = track;
5376 VolumeProvider *vp = track;
5377 fastTrack->mBufferProvider = eabp;
5378 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005379 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005380 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005381 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005382 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005383 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005384 fastTrack->mGeneration++;
5385 state->mTrackMask |= 1 << j;
5386 didModify = true;
5387 // no acknowledgement required for newly active tracks
5388 }
Kevin Rocard12381092018-04-11 09:19:59 -07005389 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005390 float volume;
5391 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5392 volume = 0.f;
5393 } else {
5394 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5395 }
5396
5397 handleVoipVolume_l(&volume);
5398
Eric Laurent81784c32012-11-19 14:55:58 -08005399 // cache the combined master volume and stream type volume for fast mixer; this
5400 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005401 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005402 proxy->framesReleased()).first;
5403 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005404 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005405 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5406 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5407 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005408
Kevin Rocard12381092018-04-11 09:19:59 -07005409 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005410 ++fastTracks;
5411 } else {
5412 // was it previously active?
5413 if (state->mTrackMask & (1 << j)) {
5414 fastTrack->mBufferProvider = NULL;
5415 fastTrack->mGeneration++;
5416 state->mTrackMask &= ~(1 << j);
5417 didModify = true;
5418 // If any fast tracks were removed, we must wait for acknowledgement
5419 // because we're about to decrement the last sp<> on those tracks.
5420 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5421 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005422 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5423 // AudioTrack may start (which may not be with a start() but with a write()
5424 // after underrun) and immediately paused or released. In that case the
5425 // FastTrack state hasn't had time to update.
5426 // TODO Remove the ALOGW when this theory is confirmed.
5427 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005428 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005429 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005430 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005431 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005432 }
5433 tracksToRemove->add(track);
5434 // Avoids a misleading display in dumpsys
5435 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5436 }
jiabin245cdd92018-12-07 17:55:15 -08005437 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5438 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5439 didModify = true;
5440 }
Eric Laurent81784c32012-11-19 14:55:58 -08005441 continue;
5442 }
5443
5444 { // local variable scope to avoid goto warning
5445
5446 audio_track_cblk_t* cblk = track->cblk();
5447
5448 // The first time a track is added we wait
5449 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005450 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005451
5452 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005453 // use the trackId as the AudioMixer name.
5454 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005455 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005456 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005457 track->mChannelMask,
5458 track->mFormat,
5459 track->mSessionId);
5460 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005461 ALOGW("%s(): AudioMixer cannot create track(%d)"
5462 " mask %#x, format %#x, sessionId %d",
5463 __func__, trackId,
5464 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005465 tracksToRemove->add(track);
5466 track->invalidate(); // consider it dead.
5467 continue;
5468 }
5469 }
5470
Eric Laurent81784c32012-11-19 14:55:58 -08005471 // make sure that we have enough frames to mix one full buffer.
5472 // enforce this condition only once to enable draining the buffer in case the client
5473 // app does not call stop() and relies on underrun to stop:
5474 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5475 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005476 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005477 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Andy Hung71ba4b32022-10-06 12:09:49 -07005478 const AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005479
5480 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005481 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005482 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5483 // add frames already consumed but not yet released by the resampler
5484 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005485 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005486
Eric Laurent81784c32012-11-19 14:55:58 -08005487 uint32_t minFrames = 1;
5488 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5489 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005490 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005491 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005492
5493 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005494 if (ATRACE_ENABLED()) {
5495 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005496 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005497 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005498 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005499 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005500 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005501 !track->isPaused() && !track->isTerminated())
5502 {
Andy Hungc0691382018-09-12 18:01:57 -07005503 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005504
5505 mixedTracks++;
5506
Andy Hung69aed5f2014-02-25 17:24:40 -08005507 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5508 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005509 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005510 if (track->mainBuffer() != mSinkBuffer &&
5511 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005512 if (mEffectBufferEnabled) {
5513 mEffectBufferValid = true; // Later can set directly.
5514 }
Eric Laurent81784c32012-11-19 14:55:58 -08005515 chain = getEffectChain_l(track->sessionId());
5516 // Delegate volume control to effect in track effect chain if needed
5517 if (chain != 0) {
5518 tracksWithEffect++;
5519 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005520 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005521 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005522 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005523 }
5524 }
5525
5526
5527 int param = AudioMixer::VOLUME;
5528 if (track->mFillingUpStatus == Track::FS_FILLED) {
5529 // no ramp for the first volume setting
5530 track->mFillingUpStatus = Track::FS_ACTIVE;
5531 if (track->mState == TrackBase::RESUMING) {
5532 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005533 // If a new track is paused immediately after start, do not ramp on resume.
5534 if (cblk->mServer != 0) {
5535 param = AudioMixer::RAMP_VOLUME;
5536 }
Eric Laurent81784c32012-11-19 14:55:58 -08005537 }
Andy Hungc0691382018-09-12 18:01:57 -07005538 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005539 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005540 // FIXME should not make a decision based on mServer
5541 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005542 // If the track is stopped before the first frame was mixed,
5543 // do not apply ramp
5544 param = AudioMixer::RAMP_VOLUME;
5545 }
5546
5547 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005548 uint32_t vl, vr; // in U8.24 integer format
5549 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005550 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005551 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005552 // Always fetch volumeshaper volume to ensure state is updated.
5553 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5554 const float vh = track->getVolumeHandler()->getVolume(
5555 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005556
Eric Laurenteab90452019-06-24 15:17:46 -07005557 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5558 v = 0;
5559 }
5560
5561 handleVoipVolume_l(&v);
5562
5563 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005564 vl = vr = 0;
5565 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005566 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005567 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005568 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005569 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5570 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005571 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005572 if (vlf > GAIN_FLOAT_UNITY) {
5573 ALOGV("Track left volume out of range: %.3g", vlf);
5574 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005575 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005576 if (vrf > GAIN_FLOAT_UNITY) {
5577 ALOGV("Track right volume out of range: %.3g", vrf);
5578 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005579 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005580 // now apply the master volume and stream type volume and shaper volume
5581 vlf *= v * vh;
5582 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005583 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005584 // then derive vl and vr as U8.24 versions for the effect chain
5585 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5586 vl = (uint32_t) (scaleto8_24 * vlf);
5587 vr = (uint32_t) (scaleto8_24 * vrf);
5588 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005589 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005590 // send level comes from shared memory and so may be corrupt
5591 if (sendLevel > MAX_GAIN_INT) {
5592 ALOGV("Track send level out of range: %04X", sendLevel);
5593 sendLevel = MAX_GAIN_INT;
5594 }
Andy Hung6be49402014-05-30 10:42:03 -07005595 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5596 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005597 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005598
Kevin Rocard12381092018-04-11 09:19:59 -07005599 track->setFinalVolume((vrf + vlf) / 2.f);
5600
Eric Laurent81784c32012-11-19 14:55:58 -08005601 // Delegate volume control to effect in track effect chain if needed
5602 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5603 // Do not ramp volume if volume is controlled by effect
5604 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005605 // Update remaining floating point volume levels
5606 vlf = (float)vl / (1 << 24);
5607 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005608 track->mHasVolumeController = true;
5609 } else {
5610 // force no volume ramp when volume controller was just disabled or removed
5611 // from effect chain to avoid volume spike
5612 if (track->mHasVolumeController) {
5613 param = AudioMixer::VOLUME;
5614 }
5615 track->mHasVolumeController = false;
5616 }
5617
Eric Laurent81784c32012-11-19 14:55:58 -08005618 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005619 mAudioMixer->setBufferProvider(trackId, track);
5620 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005621
Andy Hungc0691382018-09-12 18:01:57 -07005622 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5623 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5624 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005625 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005626 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005627 AudioMixer::TRACK,
5628 AudioMixer::FORMAT, (void *)track->format());
5629 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005630 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005631 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005632 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005633
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005634 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005635 mAudioMixer->setParameter(
5636 trackId,
5637 AudioMixer::TRACK,
5638 AudioMixer::MIXER_CHANNEL_MASK,
5639 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5640 } else {
5641 mAudioMixer->setParameter(
5642 trackId,
5643 AudioMixer::TRACK,
5644 AudioMixer::MIXER_CHANNEL_MASK,
5645 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5646 }
5647
Glenn Kastene3aa6592012-12-04 12:22:46 -08005648 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005649 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005650 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005651 if (reqSampleRate == 0) {
5652 reqSampleRate = mSampleRate;
5653 } else if (reqSampleRate > maxSampleRate) {
5654 reqSampleRate = maxSampleRate;
5655 }
Eric Laurent81784c32012-11-19 14:55:58 -08005656 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005657 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005658 AudioMixer::RESAMPLE,
5659 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005660 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005661
Andy Hung8edb8dc2015-03-26 19:13:55 -07005662 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005663 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005664 AudioMixer::TIMESTRETCH,
5665 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005666 // cast away constness for this generic API.
5667 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005668
Andy Hung69aed5f2014-02-25 17:24:40 -08005669 /*
5670 * Select the appropriate output buffer for the track.
5671 *
Andy Hung98ef9782014-03-04 14:46:50 -08005672 * Tracks with effects go into their own effects chain buffer
5673 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005674 *
5675 * Other tracks can use mMixerBuffer for higher precision
5676 * channel accumulation. If this buffer is enabled
5677 * (mMixerBufferEnabled true), then selected tracks will accumulate
5678 * into it.
5679 *
5680 */
5681 if (mMixerBufferEnabled
5682 && (track->mainBuffer() == mSinkBuffer
5683 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005684 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005685 mAudioMixer->setParameter(
5686 trackId,
5687 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005688 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005689 mAudioMixer->setParameter(
5690 trackId,
5691 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005692 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005693 } else {
5694 mAudioMixer->setParameter(
5695 trackId,
5696 AudioMixer::TRACK,
5697 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5698 mAudioMixer->setParameter(
5699 trackId,
5700 AudioMixer::TRACK,
5701 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5702 // TODO: override track->mainBuffer()?
5703 mMixerBufferValid = true;
5704 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005705 } else {
5706 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005707 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005708 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005709 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005710 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005711 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005712 AudioMixer::TRACK,
5713 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5714 }
Eric Laurent81784c32012-11-19 14:55:58 -08005715 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005716 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005717 AudioMixer::TRACK,
5718 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005719 mAudioMixer->setParameter(
5720 trackId,
5721 AudioMixer::TRACK,
5722 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005723 mAudioMixer->setParameter(
5724 trackId,
5725 AudioMixer::TRACK,
5726 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005727 mAudioMixer->setParameter(
5728 trackId,
5729 AudioMixer::TRACK,
5730 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005731
5732 // reset retry count
5733 track->mRetryCount = kMaxTrackRetries;
5734
5735 // If one track is ready, set the mixer ready if:
5736 // - the mixer was not ready during previous round OR
5737 // - no other track is not ready
5738 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5739 mixerStatus != MIXER_TRACKS_ENABLED) {
5740 mixerStatus = MIXER_TRACKS_READY;
5741 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005742
5743 // Enable the next few lines to instrument a test for underrun log handling.
5744 // TODO: Remove when we have a better way of testing the underrun log.
5745#if 0
5746 static int i;
5747 if ((++i & 0xf) == 0) {
5748 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5749 }
5750#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005751 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005752 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005753 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005754 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5755 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005756 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005757 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005758 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005759
Eric Laurent81784c32012-11-19 14:55:58 -08005760 // clear effect chain input buffer if an active track underruns to avoid sending
5761 // previous audio buffer again to effects
5762 chain = getEffectChain_l(track->sessionId());
5763 if (chain != 0) {
5764 chain->clearInputBuffer();
5765 }
5766
Andy Hungc0691382018-09-12 18:01:57 -07005767 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005768 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5769 track->isStopped() || track->isPaused()) {
5770 // We have consumed all the buffers of this track.
5771 // Remove it from the list of active tracks.
5772 // TODO: use actual buffer filling status instead of latency when available from
5773 // audio HAL
5774 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005775 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005776 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5777 if (track->isStopped()) {
5778 track->reset();
5779 }
5780 tracksToRemove->add(track);
5781 }
5782 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005783 // No buffers for this track. Give it a few chances to
5784 // fill a buffer, then remove it from active list.
5785 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005786 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5787 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005788 tracksToRemove->add(track);
5789 // indicate to client process that the track was disabled because of underrun;
5790 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005791 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005792 // If one track is not ready, mark the mixer also not ready if:
5793 // - the mixer was ready during previous round OR
5794 // - no other track is ready
5795 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5796 mixerStatus != MIXER_TRACKS_READY) {
5797 mixerStatus = MIXER_TRACKS_ENABLED;
5798 }
5799 }
Andy Hungc0691382018-09-12 18:01:57 -07005800 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005801 }
5802
5803 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005804
5805 }
5806
jiabin245cdd92018-12-07 17:55:15 -08005807 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5808 // When there is no fast track playing haptic and FastMixer exists,
5809 // enabling the first FastTrack, which provides mixed data from normal
5810 // tracks, to play haptic data.
5811 FastTrack *fastTrack = &state->mFastTracks[0];
5812 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5813 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5814 didModify = true;
5815 }
5816 }
5817
Eric Laurent81784c32012-11-19 14:55:58 -08005818 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08005819 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005820 if (didModify) {
5821 state->mFastTracksGen++;
5822 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5823 if (kUseFastMixer == FastMixer_Dynamic &&
5824 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5825 state->mCommand = FastMixerState::COLD_IDLE;
5826 state->mColdFutexAddr = &mFastMixerFutex;
5827 state->mColdGen++;
5828 mFastMixerFutex = 0;
5829 if (kUseFastMixer == FastMixer_Dynamic) {
5830 mNormalSink = mOutputSink;
5831 }
5832 // If we go into cold idle, need to wait for acknowledgement
5833 // so that fast mixer stops doing I/O.
5834 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5835 pauseAudioWatchdog = true;
5836 }
Eric Laurent81784c32012-11-19 14:55:58 -08005837 }
5838 if (sq != NULL) {
5839 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005840 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5841 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5842 // when bringing the output sink into standby.)
5843 //
5844 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5845 //
5846 // This occurs with BT suspend when we idle the FastMixer with
5847 // active tracks, which may be added or removed.
5848 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005849 }
5850#ifdef AUDIO_WATCHDOG
5851 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5852 mAudioWatchdog->pause();
5853 }
5854#endif
5855
5856 // Now perform the deferred reset on fast tracks that have stopped
5857 while (resetMask != 0) {
5858 size_t i = __builtin_ctz(resetMask);
5859 ALOG_ASSERT(i < count);
5860 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005861 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005862 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5863 track->reset();
5864 }
5865
Andy Hung80d03d22018-04-10 10:32:11 -07005866 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5867 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5868 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5869 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5870 // See also the implementation of destroyTrack_l().
5871 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005872 const int trackId = track->id();
5873 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5874 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005875 }
5876 }
5877
Eric Laurent81784c32012-11-19 14:55:58 -08005878 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005879 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005880
Eric Laurentb3f315a2021-07-13 15:09:05 +02005881 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5882 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005883 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005884 }
5885
5886 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005887 // as long as there are effects we should clear the effects buffer, to avoid
5888 // passing a non-clean buffer to the effect chain
5889 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02005890 if (mType == SPATIALIZER) {
5891 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
5892 }
Eric Laurent97d547d2014-09-02 14:45:53 -07005893 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005894 // sink or mix buffer must be cleared if all tracks are connected to an
5895 // effect chain as in this case the mixer will not write to the sink or mix buffer
5896 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005897 // always clear sink buffer for spatializer output as the output of the spatializer
5898 // effect will be accumulated into it
5899 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5900 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005901 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005902 if (mMixerBufferValid) {
5903 memset(mMixerBuffer, 0, mMixerBufferSize);
5904 // TODO: In testing, mSinkBuffer below need not be cleared because
5905 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5906 // after mixing.
5907 //
5908 // To enforce this guarantee:
5909 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5910 // (mixedTracks == 0 && fastTracks > 0))
5911 // must imply MIXER_TRACKS_READY.
5912 // Later, we may clear buffers regardless, and skip much of this logic.
5913 }
Andy Hung98ef9782014-03-04 14:46:50 -08005914 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005915 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005916 }
5917
5918 // if any fast tracks, then status is ready
5919 mMixerStatusIgnoringFastTracks = mixerStatus;
5920 if (fastTracks > 0) {
5921 mixerStatus = MIXER_TRACKS_READY;
5922 }
5923 return mixerStatus;
5924}
5925
Eric Laurentad7dd962016-09-22 12:38:37 -07005926// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005927uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005928{
5929 uint32_t trackCount = 0;
5930 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005931 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005932 trackCount++;
5933 }
5934 }
5935 return trackCount;
5936}
5937
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005938bool AudioFlinger::PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut * output)
ziyangch8f194f12021-12-01 13:48:04 -08005939{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005940 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
5941 // could falsely detect that the frame position has stalled due to underrun because we haven't
5942 // given the Audio HAL enough time to update.
5943 const nsecs_t nowNs = systemTime();
5944 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
5945 return mLatchedValue;
5946 }
5947 mPreviousNs = nowNs;
5948 mLatchedValue = false;
5949 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08005950 uint64_t position = 0;
5951 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005952 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08005953 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005954 if (position != mPreviousPosition) {
5955 mPreviousPosition = position;
5956 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08005957 }
5958 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02005959 return mLatchedValue;
5960}
5961
5962void AudioFlinger::PlaybackThread::IsTimestampAdvancing::clear()
5963{
5964 mLatchedValue = true;
5965 mPreviousPosition = 0;
5966 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08005967}
5968
Andy Hung1bc088a2018-02-09 15:57:31 -08005969// isTrackAllowed_l() must be called with ThreadBase::mLock held
5970bool AudioFlinger::MixerThread::isTrackAllowed_l(
5971 audio_channel_mask_t channelMask, audio_format_t format,
5972 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005973{
Andy Hung1bc088a2018-02-09 15:57:31 -08005974 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5975 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005976 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005977 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005978 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005979 ALOGW("%s: invalid format: %#x", __func__, format);
5980 return false;
5981 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005982 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005983 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5984 return false;
5985 }
5986 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005987}
5988
Eric Laurent10351942014-05-08 18:49:52 -07005989// checkForNewParameter_l() must be called with ThreadBase::mLock held
5990bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5991 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005992{
Eric Laurent81784c32012-11-19 14:55:58 -08005993 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005994 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005995
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005996 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005997
Eric Laurent10351942014-05-08 18:49:52 -07005998 AudioParameter param = AudioParameter(keyValuePair);
5999 int value;
6000 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6001 reconfig = true;
6002 }
6003 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006004 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006005 status = BAD_VALUE;
6006 } else {
6007 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006008 reconfig = true;
6009 }
Eric Laurent10351942014-05-08 18:49:52 -07006010 }
6011 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07006012 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006013 status = BAD_VALUE;
6014 } else {
6015 // no need to save value, since it's constant
6016 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006017 }
Eric Laurent10351942014-05-08 18:49:52 -07006018 }
6019 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6020 // do not accept frame count changes if tracks are open as the track buffer
6021 // size depends on frame count and correct behavior would not be guaranteed
6022 // if frame count is changed after track creation
6023 if (!mTracks.isEmpty()) {
6024 status = INVALID_OPERATION;
6025 } else {
6026 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006027 }
Eric Laurent10351942014-05-08 18:49:52 -07006028 }
6029 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006030 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006031 }
Eric Laurent81784c32012-11-19 14:55:58 -08006032
Eric Laurent10351942014-05-08 18:49:52 -07006033 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006034 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006035 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006036 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6037 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006038 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006039 mThreadMetrics.logEndInterval();
6040 mThreadSnapshot.onEnd();
6041 mStandby = true;
Eric Laurent10351942014-05-08 18:49:52 -07006042 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006043 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006044 }
Eric Laurent10351942014-05-08 18:49:52 -07006045 if (status == NO_ERROR && reconfig) {
6046 readOutputParameters_l();
6047 delete mAudioMixer;
6048 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006049 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006050 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006051 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006052 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08006053 track->mChannelMask,
6054 track->mFormat,
6055 track->mSessionId);
Andy Hung71ba4b32022-10-06 12:09:49 -07006056 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006057 "%s(): AudioMixer cannot create track(%d)"
6058 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006059 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07006060 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07006061 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006062 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006063 }
Eric Laurent81784c32012-11-19 14:55:58 -08006064 }
6065
Dean Wheatley68918102021-03-19 22:09:19 +11006066 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006067}
6068
6069
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006070void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006071{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006072 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006073 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006074 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006075 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006076 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6077 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6078 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006079 if (hasFastMixer()) {
6080 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6081
6082 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6083 // while we are dumping it. It may be inconsistent, but it won't mutate!
6084 // This is a large object so we place it on the heap.
6085 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006086 const std::unique_ptr<FastMixerDumpState> copy =
6087 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006088 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006089
6090#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006091 // Similar for state queue
6092 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6093 observerCopy.dump(fd);
6094 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6095 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006096#endif
6097
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006098#ifdef AUDIO_WATCHDOG
6099 if (mAudioWatchdog != 0) {
6100 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6101 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6102 wdCopy.dump(fd);
6103 }
6104#endif
6105
6106 } else {
6107 dprintf(fd, " No FastMixer\n");
6108 }
Eric Laurent81784c32012-11-19 14:55:58 -08006109}
6110
6111uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
6112{
6113 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6114}
6115
6116uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
6117{
6118 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6119}
6120
6121void AudioFlinger::MixerThread::cacheParameters_l()
6122{
6123 PlaybackThread::cacheParameters_l();
6124
6125 // FIXME: Relaxed timing because of a certain device that can't meet latency
6126 // Should be reduced to 2x after the vendor fixes the driver issue
6127 // increase threshold again due to low power audio mode. The way this warning
6128 // threshold is calculated and its usefulness should be reconsidered anyway.
6129 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6130}
6131
6132// ----------------------------------------------------------------------------
6133
6134AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006135 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6136 const audio_offload_info_t& offloadInfo)
jiabinc52b1ff2019-10-31 17:20:42 -07006137 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006138 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006139{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006140 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006141}
6142
Eric Laurent81784c32012-11-19 14:55:58 -08006143AudioFlinger::DirectOutputThread::~DirectOutputThread()
6144{
6145}
6146
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006147void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006148{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006149 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006150 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6151 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6152}
6153
6154void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
6155{
6156 Mutex::Autolock _l(mLock);
6157 if (mMasterBalance != balance) {
6158 mMasterBalance.store(balance);
6159 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6160 broadcast_l();
6161 }
6162}
6163
Eric Laurent5850c4c2016-11-10 13:04:31 -08006164void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006165{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006166 float left, right;
6167
Andy Hung333ab962019-05-28 20:23:35 -07006168 // Ensure volumeshaper state always advances even when muted.
6169 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hungee86cee2022-12-13 19:19:53 -08006170
6171 const size_t framesReleased = proxy->framesReleased();
6172 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6173 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6174
6175 ALOGV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6176 __func__, framesReleased, (long long)frames, (long long)time);
6177
6178 const int64_t volumeShaperFrames =
6179 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6180 const auto [shaperVolume, shaperActive] =
6181 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006182 mVolumeShaperActive = shaperActive;
6183
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006184 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006185 left = right = 0;
6186 } else {
6187 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006188 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006189
Glenn Kastenc56f3422014-03-21 17:53:17 -07006190 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6191 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6192 if (left > GAIN_FLOAT_UNITY) {
6193 left = GAIN_FLOAT_UNITY;
6194 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006195 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6196 if (right > GAIN_FLOAT_UNITY) {
6197 right = GAIN_FLOAT_UNITY;
6198 }
zhangjincheng73e73872023-01-16 17:17:38 +08006199 left *= v;
6200 right *= v;
6201 if (mAudioFlinger->getMode() != AUDIO_MODE_IN_COMMUNICATION
6202 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6203 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6204 right *= mMasterBalanceRight;
6205 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006206 }
6207
6208 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006209 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006210 if (left != mLeftVolFloat || right != mRightVolFloat) {
6211 mLeftVolFloat = left;
6212 mRightVolFloat = right;
6213
Eric Laurentbfb1b832013-01-07 09:53:42 -08006214 // Delegate volume control to effect in track effect chain if needed
6215 // only one effect chain can be present on DirectOutputThread, so if
6216 // there is one, the track is connected to it
6217 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006218 // if effect chain exists, volume is handled by it.
6219 // Convert volumes from float to 8.24
6220 uint32_t vl = (uint32_t)(left * (1 << 24));
6221 uint32_t vr = (uint32_t)(right * (1 << 24));
6222 // Direct/Offload effect chains set output volume in setVolume_l().
6223 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6224 } else {
6225 // otherwise we directly set the volume.
6226 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006227 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006228 }
6229 }
6230}
6231
Phil Burk43b4dcc2015-06-09 16:53:44 -07006232void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6233{
6234 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006235 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006236
Eric Laurent0f0631e2015-07-06 18:01:25 -07006237 if (previousTrack != 0 && latestTrack != 0) {
6238 if (mType == DIRECT) {
6239 if (previousTrack.get() != latestTrack.get()) {
6240 mFlushPending = true;
6241 }
6242 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006243 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6244 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006245 mFlushPending = true;
6246 }
6247 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006248 } else if (previousTrack == 0) {
6249 // there could be an old track added back during track transition for direct
6250 // output, so always issues flush to flush data of the previous track if it
6251 // was already destroyed with HAL paused, then flush can resume the playback
6252 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006253 }
6254 PlaybackThread::onAddNewTrack_l();
6255}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006256
Eric Laurent81784c32012-11-19 14:55:58 -08006257AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6258 Vector< sp<Track> > *tracksToRemove
6259)
6260{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006261 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006262 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006263 bool doHwPause = false;
6264 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006265
6266 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006267 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006268 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006269 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006270 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006271 continue;
6272 }
6273
Eric Laurent5850c4c2016-11-10 13:04:31 -08006274 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006275#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006276 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006277#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006278 // Only consider last track started for volume and mixer state control.
6279 // In theory an older track could underrun and restart after the new one starts
6280 // but as we only care about the transition phase between two tracks on a
6281 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006282 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006283 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006284
Kuowei Li23666472021-01-20 10:23:25 +08006285 if (track->isPausePending()) {
6286 track->pauseAck();
6287 // It is possible a track might have been flushed or stopped.
6288 // Other operations such as flush pending might occur on the next prepare.
6289 if (track->isPausing()) {
6290 track->setPaused();
6291 }
6292 // Always perform pause, as an immediate flush will change
6293 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006294 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006295 doHwPause = true;
6296 mHwPaused = true;
6297 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006298 } else if (track->isFlushPending()) {
6299 track->flushAck();
6300 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006301 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006302 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006303 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006304 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006305 if (last) {
6306 mLeftVolFloat = mRightVolFloat = -1.0;
6307 if (mHwPaused) {
6308 doHwResume = true;
6309 mHwPaused = false;
6310 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006311 }
6312 }
6313
Eric Laurent81784c32012-11-19 14:55:58 -08006314 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006315 // for all its buffers to be filled before processing it.
6316 // Allow draining the buffer in case the client
6317 // app does not call stop() and relies on underrun to stop:
6318 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006319 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6320 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6321 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006322 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006323
6324 // target retry count that we will use is based on the time we wait for retries.
6325 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6326 // the retry threshold is when we accept any size for PCM data. This is slightly
6327 // smaller than the retry count so we can push small bits of data without a glitch.
6328 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006329 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006330 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006331 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006332 minFrames = mNormalFrameCount;
6333 } else {
6334 minFrames = 1;
6335 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006336
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006337 const size_t framesReady = track->framesReady();
6338 const int trackId = track->id();
6339 if (ATRACE_ENABLED()) {
6340 std::string traceName("nRdy");
6341 traceName += std::to_string(trackId);
6342 ATRACE_INT(traceName.c_str(), framesReady);
6343 }
6344 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006345 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006346 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006347 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006348
6349 if (track->mFillingUpStatus == Track::FS_FILLED) {
6350 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006351 if (last) {
6352 // make sure processVolume_l() will apply new volume even if 0
6353 mLeftVolFloat = mRightVolFloat = -1.0;
6354 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006355 if (!mHwSupportsPause) {
6356 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006357 }
6358 }
6359
6360 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006361 processVolume_l(track, last);
6362 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006363 sp<Track> previousTrack = mPreviousTrack.promote();
6364 if (previousTrack != 0) {
6365 if (track != previousTrack.get()) {
6366 // Flush any data still being written from last track
6367 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006368 // Invalidate previous track to force a seek when resuming.
6369 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006370 }
6371 }
6372 mPreviousTrack = track;
6373
Eric Laurentd595b7c2013-04-03 17:27:56 -07006374 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006375 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006376 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006377 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006378 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006379 doHwResume = true;
6380 mHwPaused = false;
6381 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006382 }
Eric Laurent81784c32012-11-19 14:55:58 -08006383 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006384 // clear effect chain input buffer if the last active track started underruns
6385 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006386 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006387 mEffectChains[0]->clearInputBuffer();
6388 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006389 if (track->isStopping_1()) {
6390 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006391 if (last && mHwPaused) {
6392 doHwResume = true;
6393 mHwPaused = false;
6394 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006395 }
6396 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6397 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006398 // We have consumed all the buffers of this track.
6399 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006400 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006401 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006402 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006403 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006404 if (presComplete) {
6405 mOutput->presentationComplete();
6406 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006407 if (track->isStopping_2()) {
6408 track->mState = TrackBase::STOPPED;
6409 }
Eric Laurent81784c32012-11-19 14:55:58 -08006410 if (track->isStopped()) {
6411 track->reset();
6412 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006413 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006414 }
6415 } else {
6416 // No buffers for this track. Give it a few chances to
6417 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006418 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006419 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006420 if (!isTunerStream() // tuner streams remain active in underrun
6421 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006422 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
ziyangch8f194f12021-12-01 13:48:04 -08006423 track->mRetryCount = kMaxTrackRetriesOffload;
6424 } else {
6425 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6426 tracksToRemove->add(track);
6427 // indicate to client process that the track was disabled because of
6428 // underrun; it will then automatically call start() when data is available
6429 track->disable();
6430 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6431 // unlike mixerthread, HAL can be paused for direct output
6432 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6433 "minFrames = %u, mFormat = %#x",
6434 framesReady, minFrames, mFormat);
6435 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6436 doHwPause = true;
6437 mHwPaused = true;
6438 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006439 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006440 } else if (last) {
6441 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006442 }
6443 }
6444 }
6445 }
6446
Eric Laurentd1f69b02014-12-15 14:33:13 -08006447 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006448 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006449 for (size_t i = 0; i < mTracks.size(); i++) {
6450 if (mTracks[i]->isFlushPending()) {
6451 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006452 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006453 }
6454 }
6455 }
6456
6457 // make sure the pause/flush/resume sequence is executed in the right order.
6458 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6459 // before flush and then resume HW. This can happen in case of pause/flush/resume
6460 // if resume is received before pause is executed.
6461 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006462 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006463 status_t result = mOutput->stream->pause();
6464 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006465 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006466 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006467 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006468 flushHw_l();
6469 }
6470 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006471 status_t result = mOutput->stream->resume();
6472 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006473 }
Eric Laurent81784c32012-11-19 14:55:58 -08006474 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006475 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006476
6477 return mixerStatus;
6478}
6479
6480void AudioFlinger::DirectOutputThread::threadLoop_mix()
6481{
Eric Laurent81784c32012-11-19 14:55:58 -08006482 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006483 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006484 // output audio to hardware
6485 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006486 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006487 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006488 status_t status = mActiveTrack->getNextBuffer(&buffer);
6489 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006490 // no need to pad with 0 for compressed audio
6491 if (audio_has_proportional_frames(mFormat)) {
6492 memset(curBuf, 0, frameCount * mFrameSize);
6493 }
Eric Laurent81784c32012-11-19 14:55:58 -08006494 break;
6495 }
6496 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6497 frameCount -= buffer.frameCount;
6498 curBuf += buffer.frameCount * mFrameSize;
6499 mActiveTrack->releaseBuffer(&buffer);
6500 }
Andy Hung2098f272014-02-27 14:00:06 -08006501 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006502 mSleepTimeUs = 0;
6503 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006504 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006505}
6506
6507void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6508{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006509 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006510 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006511 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006512 return;
6513 }
Andy Hung85ba3332021-04-27 17:40:26 -07006514 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6515 mSleepTimeUs = mActiveSleepTimeUs;
6516 } else {
6517 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006518 }
Andy Hung85ba3332021-04-27 17:40:26 -07006519 // Note: In S or later, we do not write zeroes for
6520 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006521}
6522
Eric Laurentd1f69b02014-12-15 14:33:13 -08006523void AudioFlinger::DirectOutputThread::threadLoop_exit()
6524{
6525 {
6526 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006527 for (size_t i = 0; i < mTracks.size(); i++) {
6528 if (mTracks[i]->isFlushPending()) {
6529 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006530 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006531 }
6532 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006533 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006534 flushHw_l();
6535 }
6536 }
6537 PlaybackThread::threadLoop_exit();
6538}
6539
6540// must be called with thread mutex locked
6541bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6542{
6543 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006544 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006545
6546 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6547 // after a timeout and we will enter standby then.
6548 if (mTracks.size() > 0) {
6549 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006550 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6551 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006552 }
6553
Eric Laurent5cff4032015-05-26 13:49:58 -07006554 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006555}
6556
Eric Laurent10351942014-05-08 18:49:52 -07006557// checkForNewParameter_l() must be called with ThreadBase::mLock held
6558bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6559 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006560{
6561 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006562 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006563
Eric Laurent10351942014-05-08 18:49:52 -07006564 AudioParameter param = AudioParameter(keyValuePair);
6565 int value;
6566 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006567 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006568 }
Eric Laurent10351942014-05-08 18:49:52 -07006569 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6570 // do not accept frame count changes if tracks are open as the track buffer
6571 // size depends on frame count and correct behavior would not be garantied
6572 // if frame count is changed after track creation
6573 if (!mTracks.isEmpty()) {
6574 status = INVALID_OPERATION;
6575 } else {
6576 reconfig = true;
6577 }
6578 }
6579 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006580 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006581 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006582 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006583 if (!mStandby) {
6584 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006585 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07006586 mStandby = true;
6587 }
Eric Laurent10351942014-05-08 18:49:52 -07006588 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006589 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006590 }
6591 if (status == NO_ERROR && reconfig) {
6592 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006593 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006594 }
6595 }
6596
Dean Wheatley68918102021-03-19 22:09:19 +11006597 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006598}
6599
6600uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6601{
6602 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006603 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006604 time = PlaybackThread::activeSleepTimeUs();
6605 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006606 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006607 }
6608 return time;
6609}
6610
6611uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6612{
6613 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006614 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006615 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6616 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006617 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006618 }
6619 return time;
6620}
6621
6622uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6623{
6624 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006625 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006626 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6627 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006628 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006629 }
6630 return time;
6631}
6632
6633void AudioFlinger::DirectOutputThread::cacheParameters_l()
6634{
6635 PlaybackThread::cacheParameters_l();
6636
6637 // use shorter standby delay as on normal output to release
6638 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006639 // no delay on outputs with HW A/V sync
6640 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006641 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006642 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006643 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006644 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006645 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006646 }
Eric Laurent81784c32012-11-19 14:55:58 -08006647}
6648
Eric Laurente659ef42014-09-29 13:06:46 -07006649void AudioFlinger::DirectOutputThread::flushHw_l()
6650{
ziyangch8f194f12021-12-01 13:48:04 -08006651 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08006652 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006653 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006654 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006655 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006656 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08006657 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07006658}
6659
Andy Hung10cbff12017-02-21 17:30:14 -08006660int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6661 // If a VolumeShaper is active, we must wake up periodically to update volume.
6662 const int64_t NS_PER_MS = 1000000;
6663 return mVolumeShaperActive ?
6664 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6665}
6666
Eric Laurent81784c32012-11-19 14:55:58 -08006667// ----------------------------------------------------------------------------
6668
Eric Laurentbfb1b832013-01-07 09:53:42 -08006669AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006670 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006671 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006672 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006673 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006674 mDrainSequence(0),
6675 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006676{
6677}
6678
6679AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6680{
6681}
6682
6683void AudioFlinger::AsyncCallbackThread::onFirstRef()
6684{
6685 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6686}
6687
6688bool AudioFlinger::AsyncCallbackThread::threadLoop()
6689{
6690 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006691 uint32_t writeAckSequence;
6692 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006693 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006694
6695 {
6696 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006697 while (!((mWriteAckSequence & 1) ||
6698 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006699 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006700 exitPending())) {
6701 mWaitWorkCV.wait(mLock);
6702 }
6703
Eric Laurentbfb1b832013-01-07 09:53:42 -08006704 if (exitPending()) {
6705 break;
6706 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006707 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6708 mWriteAckSequence, mDrainSequence);
6709 writeAckSequence = mWriteAckSequence;
6710 mWriteAckSequence &= ~1;
6711 drainSequence = mDrainSequence;
6712 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006713 asyncError = mAsyncError;
6714 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006715 }
6716 {
Eric Laurent4de95592013-09-26 15:28:21 -07006717 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6718 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006719 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006720 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006721 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006722 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006723 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006724 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006725 if (asyncError) {
6726 playbackThread->onAsyncError();
6727 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006728 }
6729 }
6730 }
6731 return false;
6732}
6733
6734void AudioFlinger::AsyncCallbackThread::exit()
6735{
6736 ALOGV("AsyncCallbackThread::exit");
6737 Mutex::Autolock _l(mLock);
6738 requestExit();
6739 mWaitWorkCV.broadcast();
6740}
6741
Eric Laurent3b4529e2013-09-05 18:09:19 -07006742void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006743{
6744 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006745 // bit 0 is cleared
6746 mWriteAckSequence = sequence << 1;
6747}
6748
6749void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6750{
6751 Mutex::Autolock _l(mLock);
6752 // ignore unexpected callbacks
6753 if (mWriteAckSequence & 2) {
6754 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006755 mWaitWorkCV.signal();
6756 }
6757}
6758
Eric Laurent3b4529e2013-09-05 18:09:19 -07006759void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006760{
6761 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006762 // bit 0 is cleared
6763 mDrainSequence = sequence << 1;
6764}
6765
6766void AudioFlinger::AsyncCallbackThread::resetDraining()
6767{
6768 Mutex::Autolock _l(mLock);
6769 // ignore unexpected callbacks
6770 if (mDrainSequence & 2) {
6771 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006772 mWaitWorkCV.signal();
6773 }
6774}
6775
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006776void AudioFlinger::AsyncCallbackThread::setAsyncError()
6777{
6778 Mutex::Autolock _l(mLock);
6779 mAsyncError = true;
6780 mWaitWorkCV.signal();
6781}
6782
Eric Laurentbfb1b832013-01-07 09:53:42 -08006783
6784// ----------------------------------------------------------------------------
6785AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Gareth Fenn56576722022-10-05 13:42:36 -07006786 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6787 const audio_offload_info_t& offloadInfo)
6788 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08006789 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006790{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006791 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006792 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006793 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006794}
6795
Eric Laurentbfb1b832013-01-07 09:53:42 -08006796void AudioFlinger::OffloadThread::threadLoop_exit()
6797{
6798 if (mFlushPending || mHwPaused) {
6799 // If a flush is pending or track was paused, just discard buffered data
6800 flushHw_l();
6801 } else {
6802 mMixerStatus = MIXER_DRAIN_ALL;
6803 threadLoop_drain();
6804 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006805 if (mUseAsyncWrite) {
6806 ALOG_ASSERT(mCallbackThread != 0);
6807 mCallbackThread->exit();
6808 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006809 PlaybackThread::threadLoop_exit();
6810}
6811
6812AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6813 Vector< sp<Track> > *tracksToRemove
6814)
6815{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006816 size_t count = mActiveTracks.size();
6817
6818 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006819 bool doHwPause = false;
6820 bool doHwResume = false;
6821
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006822 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006823
Eric Laurentbfb1b832013-01-07 09:53:42 -08006824 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006825 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006826 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006827#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006828 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006829#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006830 // Only consider last track started for volume and mixer state control.
6831 // In theory an older track could underrun and restart after the new one starts
6832 // but as we only care about the transition phase between two tracks on a
6833 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006834 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006835 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006836
Haynes Mathew George7844f672014-01-15 12:32:55 -08006837 if (track->isInvalid()) {
6838 ALOGW("An invalidated track shouldn't be in active list");
6839 tracksToRemove->add(track);
6840 continue;
6841 }
6842
6843 if (track->mState == TrackBase::IDLE) {
6844 ALOGW("An idle track shouldn't be in active list");
6845 continue;
6846 }
6847
Kuowei Li23666472021-01-20 10:23:25 +08006848 if (track->isPausePending()) {
6849 track->pauseAck();
6850 // It is possible a track might have been flushed or stopped.
6851 // Other operations such as flush pending might occur on the next prepare.
6852 if (track->isPausing()) {
6853 track->setPaused();
6854 }
6855 // Always perform pause if last, as an immediate flush will change
6856 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006857 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006858 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006859 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006860 mHwPaused = true;
6861 }
6862 // If we were part way through writing the mixbuffer to
6863 // the HAL we must save this until we resume
6864 // BUG - this will be wrong if a different track is made active,
6865 // in that case we want to discard the pending data in the
6866 // mixbuffer and tell the client to present it again when the
6867 // track is resumed
6868 mPausedWriteLength = mCurrentWriteLength;
6869 mPausedBytesRemaining = mBytesRemaining;
6870 mBytesRemaining = 0; // stop writing
6871 }
6872 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006873 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006874 if (track->isStopping_1()) {
6875 track->mRetryCount = kMaxTrackStopRetriesOffload;
6876 } else {
6877 track->mRetryCount = kMaxTrackRetriesOffload;
6878 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006879 track->flushAck();
6880 if (last) {
6881 mFlushPending = true;
6882 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006883 } else if (track->isResumePending()){
6884 track->resumeAck();
6885 if (last) {
6886 if (mPausedBytesRemaining) {
6887 // Need to continue write that was interrupted
6888 mCurrentWriteLength = mPausedWriteLength;
6889 mBytesRemaining = mPausedBytesRemaining;
6890 mPausedBytesRemaining = 0;
6891 }
6892 if (mHwPaused) {
6893 doHwResume = true;
6894 mHwPaused = false;
6895 // threadLoop_mix() will handle the case that we need to
6896 // resume an interrupted write
6897 }
6898 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006899 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006900
Eric Laurent3df841a2016-07-15 15:15:40 -07006901 mLeftVolFloat = mRightVolFloat = -1.0;
6902
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006903 // Do not handle new data in this iteration even if track->framesReady()
6904 mixerStatus = MIXER_TRACKS_ENABLED;
6905 }
6906 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006907 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006908 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006909 if (track->mFillingUpStatus == Track::FS_FILLED) {
6910 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006911 if (last) {
6912 // make sure processVolume_l() will apply new volume even if 0
6913 mLeftVolFloat = mRightVolFloat = -1.0;
6914 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006915 }
6916
6917 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006918 sp<Track> previousTrack = mPreviousTrack.promote();
6919 if (previousTrack != 0) {
6920 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006921 // Flush any data still being written from last track
6922 mBytesRemaining = 0;
6923 if (mPausedBytesRemaining) {
6924 // Last track was paused so we also need to flush saved
6925 // mixbuffer state and invalidate track so that it will
6926 // re-submit that unwritten data when it is next resumed
6927 mPausedBytesRemaining = 0;
6928 // Invalidate is a bit drastic - would be more efficient
6929 // to have a flag to tell client that some of the
6930 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006931 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006932 }
6933 // flush data already sent to the DSP if changing audio session as audio
6934 // comes from a different source. Also invalidate previous track to force a
6935 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006936 if (previousTrack->sessionId() != track->sessionId()) {
6937 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006938 }
6939 }
6940 }
6941 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006942 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006943 if (track->isStopping_1()) {
6944 track->mRetryCount = kMaxTrackStopRetriesOffload;
6945 } else {
6946 track->mRetryCount = kMaxTrackRetriesOffload;
6947 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006948 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006949 mixerStatus = MIXER_TRACKS_READY;
6950 }
6951 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006952 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006953 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006954 if (--(track->mRetryCount) <= 0) {
6955 // Hardware buffer can hold a large amount of audio so we must
6956 // wait for all current track's data to drain before we say
6957 // that the track is stopped.
6958 if (mBytesRemaining == 0) {
6959 // Only start draining when all data in mixbuffer
6960 // has been written
6961 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6962 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6963 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6964 if (last && !mStandby) {
6965 // do not modify drain sequence if we are already draining. This happens
6966 // when resuming from pause after drain.
6967 if ((mDrainSequence & 1) == 0) {
6968 mSleepTimeUs = 0;
6969 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6970 mixerStatus = MIXER_DRAIN_TRACK;
6971 mDrainSequence += 2;
6972 }
6973 if (mHwPaused) {
6974 // It is possible to move from PAUSED to STOPPING_1 without
6975 // a resume so we must ensure hardware is running
6976 doHwResume = true;
6977 mHwPaused = false;
6978 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006979 }
6980 }
Eric Laurente93cc032016-05-05 10:15:10 -07006981 } else if (last) {
6982 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6983 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006984 }
6985 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006986 // Drain has completed or we are in standby, signal presentation complete
6987 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006988 track->mState = TrackBase::STOPPED;
Atneya Nair0cae0432022-05-10 18:12:12 -04006989 mOutput->presentationComplete();
6990 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08006991 track->reset();
6992 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006993 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006994 if (!mUseAsyncWrite) {
6995 // If we don't get explicit drain notification we must
6996 // register discontinuity regardless of whether this is
6997 // the previous (!last) or the upcoming (last) track
6998 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006999 mTimestampVerifier.discontinuity(
7000 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007001 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007002 }
7003 } else {
7004 // No buffers for this track. Give it a few chances to
7005 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007006 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007007 if (!isTunerStream() // tuner streams remain active in underrun
7008 && --(track->mRetryCount) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007009 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hungf8044752016-07-27 14:58:11 -07007010 track->mRetryCount = kMaxTrackRetriesOffload;
7011 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007012 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7013 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007014 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007015 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007016 // it will then automatically call start() when data is available
7017 track->disable();
7018 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007019 } else if (last){
7020 mixerStatus = MIXER_TRACKS_ENABLED;
7021 }
7022 }
7023 }
7024 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007025 if (track->isReady()) { // check ready to prevent premature start.
7026 processVolume_l(track, last);
7027 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007028 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007029
Eric Laurentea0fade2013-10-04 16:23:48 -07007030 // make sure the pause/flush/resume sequence is executed in the right order.
7031 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7032 // before flush and then resume HW. This can happen in case of pause/flush/resume
7033 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007034 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007035 status_t result = mOutput->stream->pause();
7036 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007037 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007038 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007039 if (mFlushPending) {
7040 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007041 }
Eric Laurentfd477972013-10-25 18:10:40 -07007042 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007043 status_t result = mOutput->stream->resume();
7044 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007045 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007046
Eric Laurentbfb1b832013-01-07 09:53:42 -08007047 // remove all the tracks that need to be...
7048 removeTracks_l(*tracksToRemove);
7049
7050 return mixerStatus;
7051}
7052
Eric Laurentbfb1b832013-01-07 09:53:42 -08007053// must be called with thread mutex locked
7054bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
7055{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007056 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7057 mWriteAckSequence, mDrainSequence);
7058 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007059 return true;
7060 }
7061 return false;
7062}
7063
Eric Laurentbfb1b832013-01-07 09:53:42 -08007064bool AudioFlinger::OffloadThread::waitingAsyncCallback()
7065{
7066 Mutex::Autolock _l(mLock);
7067 return waitingAsyncCallback_l();
7068}
7069
7070void AudioFlinger::OffloadThread::flushHw_l()
7071{
Eric Laurente659ef42014-09-29 13:06:46 -07007072 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007073 // Flush anything still waiting in the mixbuffer
7074 mCurrentWriteLength = 0;
7075 mBytesRemaining = 0;
7076 mPausedWriteLength = 0;
7077 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007078 // reset bytes written count to reflect that DSP buffers are empty after flush.
7079 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007080
Eric Laurentbfb1b832013-01-07 09:53:42 -08007081 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007082 // discard any pending drain or write ack by incrementing sequence
7083 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7084 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007085 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007086 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7087 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007088 }
7089}
7090
Haynes Mathew George05317d22016-05-03 16:34:26 -07007091void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
7092{
7093 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07007094 if (PlaybackThread::invalidateTracks_l(streamType)) {
7095 mFlushPending = true;
7096 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007097}
7098
Eric Laurentbfb1b832013-01-07 09:53:42 -08007099// ----------------------------------------------------------------------------
7100
Eric Laurent81784c32012-11-19 14:55:58 -08007101AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07007102 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07007103 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007104 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007105 mWaitTimeMs(UINT_MAX)
7106{
7107 addOutputTrack(mainThread);
7108}
7109
7110AudioFlinger::DuplicatingThread::~DuplicatingThread()
7111{
7112 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7113 mOutputTracks[i]->destroy();
7114 }
7115}
7116
7117void AudioFlinger::DuplicatingThread::threadLoop_mix()
7118{
7119 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007120 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007121 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007122 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007123 if (mMixerBufferValid) {
7124 memset(mMixerBuffer, 0, mMixerBufferSize);
7125 } else {
7126 memset(mSinkBuffer, 0, mSinkBufferSize);
7127 }
Eric Laurent81784c32012-11-19 14:55:58 -08007128 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007129 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007130 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007131 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007132 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007133}
7134
7135void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
7136{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007137 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007138 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007139 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007140 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007141 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007142 }
7143 } else if (mBytesWritten != 0) {
7144 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7145 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007146 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007147 } else {
7148 // flush remaining overflow buffers in output tracks
7149 writeFrames = 0;
7150 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007151 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007152 }
7153}
7154
Eric Laurentbfb1b832013-01-07 09:53:42 -08007155ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007156{
7157 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007158 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7159
7160 // Consider the first OutputTrack for timestamp and frame counting.
7161
7162 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7163 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7164 // we always claim success.
7165 if (i == 0) {
7166 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7167 ALOGD_IF(correction != 0 && writeFrames != 0,
7168 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7169 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7170 mFramesWritten -= correction;
7171 }
7172
7173 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007174 }
Andy Hungcf10d742020-04-28 15:38:24 -07007175 if (mStandby) {
7176 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007177 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007178 mStandby = false;
7179 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007180 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007181}
7182
7183void AudioFlinger::DuplicatingThread::threadLoop_standby()
7184{
7185 // DuplicatingThread implements standby by stopping all tracks
7186 for (size_t i = 0; i < outputTracks.size(); i++) {
7187 outputTracks[i]->stop();
7188 }
7189}
7190
Andy Hung71ba4b32022-10-06 12:09:49 -07007191void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007192{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007193 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007194
7195 std::stringstream ss;
7196 const size_t numTracks = mOutputTracks.size();
7197 ss << " " << numTracks << " OutputTracks";
7198 if (numTracks > 0) {
7199 ss << ":";
7200 for (const auto &track : mOutputTracks) {
7201 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007202 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007203 if (thread.get() != nullptr) {
7204 ss << thread.get() << ", " << thread->id();
7205 } else {
7206 ss << "null";
7207 }
7208 ss << ")";
7209 }
7210 }
7211 ss << "\n";
7212 std::string result = ss.str();
7213 write(fd, result.c_str(), result.size());
7214}
7215
Eric Laurent81784c32012-11-19 14:55:58 -08007216void AudioFlinger::DuplicatingThread::saveOutputTracks()
7217{
7218 outputTracks = mOutputTracks;
7219}
7220
7221void AudioFlinger::DuplicatingThread::clearOutputTracks()
7222{
7223 outputTracks.clear();
7224}
7225
7226void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7227{
7228 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007229 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7230 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7231 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7232 const size_t frameCount =
7233 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7234 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7235 // from different OutputTracks and their associated MixerThreads (e.g. one may
7236 // nearly empty and the other may be dropping data).
7237
Svet Ganov33761132021-05-13 22:51:08 +00007238 // TODO b/182392769: use attribution source util, move to server edge
7239 AttributionSourceState attributionSource = AttributionSourceState();
7240 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007241 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007242 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007243 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007244 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007245 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007246 this,
7247 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007248 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007249 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007250 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007251 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007252 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7253 if (status != NO_ERROR) {
7254 ALOGE("addOutputTrack() initCheck failed %d", status);
7255 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007256 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007257 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7258 mOutputTracks.add(outputTrack);
7259 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7260 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007261}
7262
7263void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7264{
7265 Mutex::Autolock _l(mLock);
7266 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7267 if (mOutputTracks[i]->thread() == thread) {
7268 mOutputTracks[i]->destroy();
7269 mOutputTracks.removeAt(i);
7270 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007271 if (thread->getOutput() == mOutput) {
7272 mOutput = NULL;
7273 }
Eric Laurent81784c32012-11-19 14:55:58 -08007274 return;
7275 }
7276 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007277 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007278}
7279
7280// caller must hold mLock
7281void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7282{
7283 mWaitTimeMs = UINT_MAX;
7284 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7285 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7286 if (strong != 0) {
7287 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7288 if (waitTimeMs < mWaitTimeMs) {
7289 mWaitTimeMs = waitTimeMs;
7290 }
7291 }
7292 }
7293}
7294
Andy Hung71ba4b32022-10-06 12:09:49 -07007295bool AudioFlinger::DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007296{
7297 for (size_t i = 0; i < outputTracks.size(); i++) {
7298 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7299 if (thread == 0) {
7300 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7301 outputTracks[i].get());
7302 return false;
7303 }
7304 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7305 // see note at standby() declaration
7306 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7307 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7308 thread.get());
7309 return false;
7310 }
7311 }
7312 return true;
7313}
7314
Kevin Rocard12381092018-04-11 09:19:59 -07007315void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7316 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007317{
Kevin Rocard12381092018-04-11 09:19:59 -07007318 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7319 outputTrack->setMetadatas(metadata.tracks);
7320 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007321}
7322
Eric Laurent81784c32012-11-19 14:55:58 -08007323uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7324{
7325 return (mWaitTimeMs * 1000) / 2;
7326}
7327
7328void AudioFlinger::DuplicatingThread::cacheParameters_l()
7329{
7330 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7331 updateWaitTime_l();
7332
7333 MixerThread::cacheParameters_l();
7334}
7335
Eric Laurentb3f315a2021-07-13 15:09:05 +02007336// ----------------------------------------------------------------------------
7337
Eric Laurentfa0f6742021-08-17 18:39:44 +02007338AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007339 AudioStreamOut* output,
7340 audio_io_handle_t id,
7341 bool systemReady,
7342 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007343 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007344{
7345}
7346
Eric Laurent6f9534f2022-05-03 18:15:04 +02007347void AudioFlinger::SpatializerThread::onFirstRef() {
7348 PlaybackThread::onFirstRef();
7349
7350 Mutex::Autolock _l(mLock);
7351 status_t status = mOutput->stream->setLatencyModeCallback(this);
7352 if (status != INVALID_OPERATION) {
7353 updateHalSupportedLatencyModes_l();
7354 }
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007355
Andy Hung41ccf7f2022-12-14 14:25:49 -08007356 const pid_t tid = getTid();
7357 if (tid == -1) {
7358 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7359 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7360 } else {
7361 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7362 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007363 stream()->setHalThreadPriority(priorityBoost);
7364 }
7365 }
Eric Laurent6f9534f2022-05-03 18:15:04 +02007366}
7367
7368status_t AudioFlinger::SpatializerThread::createAudioPatch_l(const struct audio_patch *patch,
7369 audio_patch_handle_t *handle)
7370{
7371 status_t status = MixerThread::createAudioPatch_l(patch, handle);
7372 updateHalSupportedLatencyModes_l();
7373 return status;
7374}
7375
7376void AudioFlinger::SpatializerThread::updateHalSupportedLatencyModes_l() {
7377 std::vector<audio_latency_mode_t> latencyModes;
Andy Hung4bd53e72022-11-17 17:21:45 -08007378 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
7379 if (status != NO_ERROR) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007380 latencyModes.clear();
7381 }
7382 if (latencyModes != mSupportedLatencyModes) {
Andy Hung4bd53e72022-11-17 17:21:45 -08007383 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
7384 __func__, mId, status, toString(latencyModes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007385 mSupportedLatencyModes.swap(latencyModes);
7386 sendHalLatencyModesChangedEvent_l();
7387 }
7388}
7389
7390void AudioFlinger::SpatializerThread::onHalLatencyModesChanged_l() {
7391 mAudioFlinger->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
7392}
7393
7394void AudioFlinger::SpatializerThread::setHalLatencyMode_l() {
7395 // if mSupportedLatencyModes is empty, the HAL stream does not support
7396 // latency mode control and we can exit.
7397 if (mSupportedLatencyModes.empty()) {
7398 return;
7399 }
7400 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7401 if (mSupportedLatencyModes.size() == 1) {
7402 // If the HAL only support one latency mode currently, confirm the choice
7403 latencyMode = mSupportedLatencyModes[0];
7404 } else if (mSupportedLatencyModes.size() > 1) {
7405 // Request low latency if:
7406 // - The low latency mode is requested by the spatializer controller
7407 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7408 // AND
7409 // - At least one active track is spatialized
7410 bool hasSpatializedActiveTrack = false;
7411 for (const auto& track : mActiveTracks) {
7412 if (track->isSpatialized()) {
7413 hasSpatializedActiveTrack = true;
7414 break;
7415 }
7416 }
7417 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7418 latencyMode = AUDIO_LATENCY_MODE_LOW;
7419 }
7420 }
7421
7422 if (latencyMode != mSetLatencyMode) {
7423 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007424 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7425 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007426 if (status == NO_ERROR) {
7427 mSetLatencyMode = latencyMode;
7428 }
7429 }
7430}
7431
7432status_t AudioFlinger::SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
7433 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7434 return BAD_VALUE;
7435 }
7436 Mutex::Autolock _l(mLock);
7437 mRequestedLatencyMode = mode;
7438 return NO_ERROR;
7439}
7440
7441status_t AudioFlinger::SpatializerThread::getSupportedLatencyModes(
7442 std::vector<audio_latency_mode_t>* modes) {
7443 if (modes == nullptr) {
7444 return BAD_VALUE;
7445 }
7446 Mutex::Autolock _l(mLock);
7447 *modes = mSupportedLatencyModes;
7448 return NO_ERROR;
7449}
7450
Eric Laurent49879b72022-12-20 20:20:23 +01007451status_t AudioFlinger::PlaybackThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007452 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
Eric Laurent49879b72022-12-20 20:20:23 +01007453 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
Eric Laurent01eb1642022-12-16 11:45:07 +01007454 return INVALID_OPERATION;
7455 }
7456 mBluetoothLatencyModesEnabled.store(enabled);
7457 return NO_ERROR;
7458}
7459
Eric Laurentfa0f6742021-08-17 18:39:44 +02007460void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007461{
7462 bool hasVirtualizer = false;
7463 bool hasDownMixer = false;
7464 sp<EffectHandle> finalDownMixer;
7465 {
7466 Mutex::Autolock _l(mLock);
7467 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7468 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007469 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007470 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7471 }
7472
7473 finalDownMixer = mFinalDownMixer;
7474 mFinalDownMixer.clear();
7475 }
7476
7477 if (hasVirtualizer) {
7478 if (finalDownMixer != nullptr) {
7479 int32_t ret;
7480 finalDownMixer->disable(&ret);
7481 }
7482 finalDownMixer.clear();
7483 } else if (!hasDownMixer) {
7484 std::vector<effect_descriptor_t> descriptors;
7485 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7486 EFFECT_UIID_DOWNMIX, &descriptors);
7487 if (status != NO_ERROR) {
7488 return;
7489 }
7490 ALOG_ASSERT(!descriptors.empty(),
7491 "%s getDescriptors() returned no error but empty list", __func__);
7492
7493 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7494 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007495 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007496
7497 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7498 ALOGW("%s error creating downmixer %d", __func__, status);
7499 finalDownMixer.clear();
7500 } else {
7501 int32_t ret;
7502 finalDownMixer->enable(&ret);
7503 }
7504 }
7505
7506 {
7507 Mutex::Autolock _l(mLock);
7508 mFinalDownMixer = finalDownMixer;
7509 }
7510}
7511
Eric Laurent6f9534f2022-05-03 18:15:04 +02007512void AudioFlinger::SpatializerThread::onRecommendedLatencyModeChanged(
7513 std::vector<audio_latency_mode_t> modes) {
7514 Mutex::Autolock _l(mLock);
7515 if (modes != mSupportedLatencyModes) {
Andy Hungb5ecdb82022-11-18 19:40:00 -08007516 ALOGD("%s: thread(%d) supported latency modes: %s",
7517 __func__, mId, toString(modes).c_str());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007518 mSupportedLatencyModes.swap(modes);
7519 sendHalLatencyModesChangedEvent_l();
7520 }
7521}
Eric Laurent6acd1d42017-01-04 14:23:29 -08007522
Eric Laurent81784c32012-11-19 14:55:58 -08007523// ----------------------------------------------------------------------------
7524// Record
7525// ----------------------------------------------------------------------------
7526
7527AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7528 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007529 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007530 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007531 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007532 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007533 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007534 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007535 mActiveTracks(&this->mLocalLog),
7536 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007537 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007538 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007539 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7540 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007541 // mFastCapture below
7542 , mFastCaptureFutex(0)
7543 // mInputSource
7544 // mPipeSink
7545 // mPipeSource
7546 , mPipeFramesP2(0)
7547 // mPipeMemory
7548 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007549 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007550 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007551{
Glenn Kastend7dca052015-03-05 16:05:54 -08007552 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7553 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007554
George Burgess IVa8f90c12020-05-14 11:27:19 -07007555 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007556 mIsMsdDevice = strcmp(
7557 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7558 }
7559
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007560 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007561
Andy Hungc8fddf32018-08-08 18:32:37 -07007562 // TODO: We may also match on address as well as device type for
7563 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007564 // TODO: This property should be ensure that only contains one single device type.
7565 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7566 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007567 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7568 : AUDIO_DEVICE_NONE));
7569
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007570 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007571 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007572 size_t numCounterOffers = 0;
7573 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007574#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007575 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007576#else
7577 (void)
7578#endif
7579 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007580 ALOG_ASSERT(index == 0);
7581
7582 // initialize fast capture depending on configuration
7583 bool initFastCapture;
7584 switch (kUseFastCapture) {
7585 case FastCapture_Never:
7586 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007587 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007588 break;
7589 case FastCapture_Always:
7590 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007591 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007592 break;
7593 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007594 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7595 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7596 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7597 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7598 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007599 break;
7600 // case FastCapture_Dynamic:
7601 }
7602
7603 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007604 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007605 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007606 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7607 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007608 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007609 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007610 const sp<MemoryDealer> roHeap(readOnlyHeap());
7611 sp<IMemory> pipeMemory;
7612 if ((roHeap == 0) ||
7613 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007614 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007615 ALOGE("not enough memory for pipe buffer size=%zu; "
7616 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7617 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7618 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007619 goto failed;
7620 }
7621 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7622 memset(pipeBuffer, 0, pipeSize);
7623 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07007624 const NBAIO_Format offersFast[1] = {format};
7625 size_t numCounterOffersFast = 0;
7626 [[maybe_unused]] ssize_t index = pipe->negotiate(offersFast, std::size(offersFast),
7627 nullptr /* counterOffers */, numCounterOffersFast);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007628 ALOG_ASSERT(index == 0);
7629 mPipeSink = pipe;
7630 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07007631 numCounterOffersFast = 0;
7632 index = pipeReader->negotiate(offersFast, std::size(offersFast),
7633 nullptr /* counterOffers */, numCounterOffersFast);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007634 ALOG_ASSERT(index == 0);
7635 mPipeSource = pipeReader;
7636 mPipeFramesP2 = pipeFramesP2;
7637 mPipeMemory = pipeMemory;
7638
7639 // create fast capture
7640 mFastCapture = new FastCapture();
7641 FastCaptureStateQueue *sq = mFastCapture->sq();
7642#ifdef STATE_QUEUE_DUMP
7643 // FIXME
7644#endif
7645 FastCaptureState *state = sq->begin();
7646 state->mCblk = NULL;
7647 state->mInputSource = mInputSource.get();
7648 state->mInputSourceGen++;
7649 state->mPipeSink = pipe;
7650 state->mPipeSinkGen++;
7651 state->mFrameCount = mFrameCount;
7652 state->mCommand = FastCaptureState::COLD_IDLE;
7653 // already done in constructor initialization list
7654 //mFastCaptureFutex = 0;
7655 state->mColdFutexAddr = &mFastCaptureFutex;
7656 state->mColdGen++;
7657 state->mDumpState = &mFastCaptureDumpState;
7658#ifdef TEE_SINK
7659 // FIXME
7660#endif
7661 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7662 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7663 sq->end();
7664 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7665
7666 // start the fast capture
7667 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7668 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007669 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007670 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007671#ifdef AUDIO_WATCHDOG
7672 // FIXME
7673#endif
7674
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007675 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007676 }
Andy Hung8946a282018-04-19 20:04:56 -07007677#ifdef TEE_SINK
7678 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7679 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7680#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007681failed: ;
7682
7683 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007684}
7685
Eric Laurent81784c32012-11-19 14:55:58 -08007686AudioFlinger::RecordThread::~RecordThread()
7687{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007688 if (mFastCapture != 0) {
7689 FastCaptureStateQueue *sq = mFastCapture->sq();
7690 FastCaptureState *state = sq->begin();
7691 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7692 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7693 if (old == -1) {
7694 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7695 }
7696 }
7697 state->mCommand = FastCaptureState::EXIT;
7698 sq->end();
7699 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7700 mFastCapture->join();
7701 mFastCapture.clear();
7702 }
7703 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007704 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007705 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007706}
7707
7708void AudioFlinger::RecordThread::onFirstRef()
7709{
Glenn Kastend7dca052015-03-05 16:05:54 -08007710 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007711}
7712
Eric Laurent555530a2017-02-07 18:17:24 -08007713void AudioFlinger::RecordThread::preExit()
7714{
7715 ALOGV(" preExit()");
7716 Mutex::Autolock _l(mLock);
7717 for (size_t i = 0; i < mTracks.size(); i++) {
7718 sp<RecordTrack> track = mTracks[i];
7719 track->invalidate();
7720 }
7721 mActiveTracks.clear();
7722 mStartStopCond.broadcast();
7723}
7724
Eric Laurent81784c32012-11-19 14:55:58 -08007725bool AudioFlinger::RecordThread::threadLoop()
7726{
Eric Laurent81784c32012-11-19 14:55:58 -08007727 nsecs_t lastWarning = 0;
7728
7729 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007730
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007731reacquire_wakelock:
7732 sp<RecordTrack> activeTrack;
7733 {
7734 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007735 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007736 }
7737
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007738 // used to request a deferred sleep, to be executed later while mutex is unlocked
7739 uint32_t sleepUs = 0;
7740
Andy Hung446f4df2019-02-21 12:26:41 -08007741 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7742
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007743 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007744 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007745 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007746
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007747 // activeTracks accumulates a copy of a subset of mActiveTracks
7748 Vector< sp<RecordTrack> > activeTracks;
7749
Glenn Kasten735f45f2014-08-18 15:51:59 -07007750 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007751 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007752
Glenn Kasten735f45f2014-08-18 15:51:59 -07007753 // reference to a fast track which is about to be removed
7754 sp<RecordTrack> fastTrackToRemove;
7755
Eric Laurent33403f02020-05-29 18:35:06 -07007756 bool silenceFastCapture = false;
7757
Eric Laurent81784c32012-11-19 14:55:58 -08007758 { // scope for mLock
7759 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007760
Eric Laurent021cf962014-05-13 10:18:14 -07007761 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007762
Eric Laurent000a4192014-01-29 15:17:32 -08007763 // check exitPending here because checkForNewParameters_l() and
7764 // checkForNewParameters_l() can temporarily release mLock
7765 if (exitPending()) {
7766 break;
7767 }
7768
Eric Laurent5c25d562016-07-13 17:17:45 -07007769 // sleep with mutex unlocked
7770 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007771 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007772 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7773 ATRACE_END();
7774 sleepUs = 0;
7775 continue;
7776 }
7777
Glenn Kasten2b806402013-11-20 16:37:38 -08007778 // if no active track(s), then standby and release wakelock
7779 size_t size = mActiveTracks.size();
7780 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007781 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007782 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007783 releaseWakeLock_l();
7784 ALOGV("RecordThread: loop stopping");
7785 // go to sleep
7786 mWaitWorkCV.wait(mLock);
7787 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007788 goto reacquire_wakelock;
7789 }
7790
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007791 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007792 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007793 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007794
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007795 activeTrack = mActiveTracks[i];
7796 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007797 if (activeTrack->isFastTrack()) {
7798 ALOG_ASSERT(fastTrackToRemove == 0);
7799 fastTrackToRemove = activeTrack;
7800 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007801 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007802 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007803 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007804 continue;
7805 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007806
7807 TrackBase::track_state activeTrackState = activeTrack->mState;
7808 switch (activeTrackState) {
7809
7810 case TrackBase::PAUSING:
7811 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007812 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007813 doBroadcast = true;
7814 size--;
7815 continue;
7816
7817 case TrackBase::STARTING_1:
7818 sleepUs = 10000;
7819 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007820 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007821 continue;
7822
7823 case TrackBase::STARTING_2:
7824 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007825 if (mStandby) {
7826 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007827 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007828 mStandby = false;
7829 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007830 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007831 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007832 break;
7833
7834 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007835 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007836 break;
7837
Andy Hungce685402018-10-05 17:23:27 -07007838 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7839 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7840 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007841 default:
Andy Hungce685402018-10-05 17:23:27 -07007842 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7843 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007844 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007845
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007846 if (activeTrack->isFastTrack()) {
7847 ALOG_ASSERT(!mFastTrackAvail);
7848 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007849 // if the active fast track is silenced either:
7850 // 1) silence the whole capture from fast capture buffer if this is
7851 // the only active track
7852 // 2) invalidate this track: this will cause the client to reconnect and possibly
7853 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007854 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007855 if (activeTrack->isSilenced()) {
7856 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007857 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007858 } else {
7859 silenceFastCapture = true;
7860 }
7861 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007862 // Invalidate fast tracks if access to audio history is required as this is not
7863 // possible with fast tracks. Once the fast track has been invalidated, no new
7864 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7865 if (mMaxSharedAudioHistoryMs != 0) {
7866 invalidate = true;
7867 }
7868 if (invalidate) {
7869 activeTrack->invalidate();
7870 ALOG_ASSERT(fastTrackToRemove == 0);
7871 fastTrackToRemove = activeTrack;
7872 removeTrack_l(activeTrack);
7873 mActiveTracks.remove(activeTrack);
7874 size--;
7875 continue;
7876 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007877 fastTrack = activeTrack;
7878 }
Eric Laurent33403f02020-05-29 18:35:06 -07007879
7880 activeTracks.add(activeTrack);
7881 i++;
7882
Glenn Kasten9e982352013-08-14 14:39:50 -07007883 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007884
Andy Hungdae27702016-10-31 14:01:16 -07007885 mActiveTracks.updatePowerState(this);
7886
Kevin Rocard069c2712018-03-29 19:09:14 -07007887 updateMetadata_l();
7888
Eric Laurent5c25d562016-07-13 17:17:45 -07007889 if (allStopped) {
7890 standbyIfNotAlreadyInStandby();
7891 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007892 if (doBroadcast) {
7893 mStartStopCond.broadcast();
7894 }
7895
7896 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007897 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007898 if (sleepUs == 0) {
7899 sleepUs = kRecordThreadSleepUs;
7900 }
7901 continue;
7902 }
7903 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007904
Eric Laurent81784c32012-11-19 14:55:58 -08007905 lockEffectChains_l(effectChains);
7906 }
7907
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007908 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007909
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007910 size_t size = effectChains.size();
7911 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007912 // thread mutex is not locked, but effect chain is locked
7913 effectChains[i]->process_l();
7914 }
7915
Glenn Kasten735f45f2014-08-18 15:51:59 -07007916 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007917 if (mFastCapture != 0) {
7918 FastCaptureStateQueue *sq = mFastCapture->sq();
7919 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007920 bool didModify = false;
7921 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007922 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7923 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7924 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7925 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7926 if (old == -1) {
7927 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7928 }
7929 }
7930 state->mCommand = FastCaptureState::READ_WRITE;
7931#if 0 // FIXME
7932 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007933 FastThreadDumpState::kSamplingNforLowRamDevice :
7934 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007935#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007936 didModify = true;
7937 }
7938 audio_track_cblk_t *cblkOld = state->mCblk;
7939 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7940 if (cblkNew != cblkOld) {
7941 state->mCblk = cblkNew;
7942 // block until acked if removing a fast track
7943 if (cblkOld != NULL) {
7944 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7945 }
7946 didModify = true;
7947 }
jiabin01c8f562018-07-19 17:47:28 -07007948 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7949 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7950 if (state->mFastPatchRecordBufferProvider != abp) {
7951 state->mFastPatchRecordBufferProvider = abp;
7952 state->mFastPatchRecordFormat = fastTrack == 0 ?
7953 AUDIO_FORMAT_INVALID : fastTrack->format();
7954 didModify = true;
7955 }
Eric Laurent33403f02020-05-29 18:35:06 -07007956 if (state->mSilenceCapture != silenceFastCapture) {
7957 state->mSilenceCapture = silenceFastCapture;
7958 didModify = true;
7959 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007960 sq->end(didModify);
7961 if (didModify) {
7962 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007963#if 0
7964 if (kUseFastCapture == FastCapture_Dynamic) {
7965 mNormalSource = mPipeSource;
7966 }
7967#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007968 }
7969 }
7970
Glenn Kasten735f45f2014-08-18 15:51:59 -07007971 // now run the fast track destructor with thread mutex unlocked
7972 fastTrackToRemove.clear();
7973
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007974 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7975 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7976 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7977 // If destination is non-contiguous, first read past the nominal end of buffer, then
7978 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007979
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007980 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07007981 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08007982 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007983
7984 // If an NBAIO source is present, use it to read the normal capture's data
7985 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007986 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007987
7988 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7989 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7990 // we immediately retry the read() to get data and prevent another overflow.
7991 for (int retries = 0; retries <= 2; ++retries) {
7992 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7993 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7994 framesToRead);
7995 if (framesRead != OVERRUN) break;
7996 }
7997
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007998 const ssize_t availableToRead = mPipeSource->availableToRead();
7999 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008000 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008001 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008002 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8003 "more frames to read than fifo size, %zd > %zu",
8004 availableToRead, mPipeFramesP2);
8005 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8006 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8007 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8008 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008009 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8010 }
8011 if (framesRead < 0) {
8012 status_t status = (status_t) framesRead;
8013 switch (status) {
8014 case OVERRUN:
8015 ALOGW("overrun on read from pipe");
8016 framesRead = 0;
8017 break;
8018 case NEGOTIATE:
8019 ALOGE("re-negotiation is needed");
8020 framesRead = -1; // Will cause an attempt to recover.
8021 break;
8022 default:
8023 ALOGE("unknown error %d on read from pipe", status);
8024 break;
8025 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008026 }
8027 // otherwise use the HAL / AudioStreamIn directly
8028 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008029 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008030 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008031 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008032 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008033 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008034 if (result < 0) {
8035 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008036 } else {
8037 framesRead = bytesRead / mFrameSize;
8038 }
8039 }
8040
Andy Hung446f4df2019-02-21 12:26:41 -08008041 const int64_t lastIoEndNs = systemTime(); // end IO timing
8042
Andy Hung3f0c9022016-01-15 17:49:46 -08008043 // Update server timestamp with server stats
8044 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008045 if (framesRead >= 0) {
8046 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8047 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8048 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008049
8050 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008051 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008052 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008053 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008054 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8055 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8056 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008057 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008058 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8059
8060 mTimestampVerifier.add(position, time, mSampleRate);
8061
8062 // Correct timestamps
8063 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008064 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008065 id(), (long long)time, (long long)position);
8066 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8067 position = correctedTimestamp.mFrames;
8068 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008069 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008070 id(), (long long)time, (long long)position);
8071 }
8072
Andy Hung3f0c9022016-01-15 17:49:46 -08008073 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8074 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8075 // Note: In general record buffers should tend to be empty in
8076 // a properly running pipeline.
8077 //
8078 // Also, it is not advantageous to call get_presentation_position during the read
8079 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008080 } else {
8081 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008082 }
8083 }
Andy Hunge6c37112019-02-26 17:38:10 -08008084
8085 // From the timestamp, input read latency is negative output write latency.
8086 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
8087 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
8088 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8089 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8090 mLatencyMs.add(latencyMs);
8091 }
8092
Andy Hung3f0c9022016-01-15 17:49:46 -08008093 // Use this to track timestamp information
8094 // ALOGD("%s", mTimestamp.toString().c_str());
8095
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008096 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008097 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008098 // Force input into standby so that it tries to recover at next read attempt
8099 inputStandBy();
8100 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008101 }
8102 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008103 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008104 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008105 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008106 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008107
Andy Hung8946a282018-04-19 20:04:56 -07008108#ifdef TEE_SINK
8109 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8110#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008111 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008112 {
8113 size_t part1 = mRsmpInFramesP2 - rear;
8114 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008115 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008116 (framesRead - part1) * mFrameSize);
8117 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008118 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008119 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008120
8121 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008123 // loop over each active track
8124 for (size_t i = 0; i < size; i++) {
8125 activeTrack = activeTracks[i];
8126
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008127 // skip fast tracks, as those are handled directly by FastCapture
8128 if (activeTrack->isFastTrack()) {
8129 continue;
8130 }
8131
Andy Hung73c02e42015-03-29 01:13:58 -07008132 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008133 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8134
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008135 enum {
8136 OVERRUN_UNKNOWN,
8137 OVERRUN_TRUE,
8138 OVERRUN_FALSE
8139 } overrun = OVERRUN_UNKNOWN;
8140
8141 // loop over getNextBuffer to handle circular sink
8142 for (;;) {
8143
8144 activeTrack->mSink.frameCount = ~0;
8145 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
8146 size_t framesOut = activeTrack->mSink.frameCount;
8147 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8148
Andy Hung73c02e42015-03-29 01:13:58 -07008149 // check available frames and handle overrun conditions
8150 // if the record track isn't draining fast enough.
8151 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008152 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07008153 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
8154 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008155 overrun = OVERRUN_TRUE;
8156 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008157 if (framesOut == 0 || framesIn == 0) {
8158 break;
8159 }
8160
Andy Hung6770c6f2015-04-07 13:43:36 -07008161 // Don't allow framesOut to be larger than what is possible with resampling
8162 // from framesIn.
8163 // This isn't strictly necessary but helps limit buffer resizing in
8164 // RecordBufferConverter. TODO: remove when no longer needed.
8165 framesOut = min(framesOut,
8166 destinationFramesPossible(
8167 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008168
8169 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008170 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008171 // straight from RecordThread buffer to RecordTrack buffer.
8172 AudioBufferProvider::Buffer buffer;
8173 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008174 const status_t getNextBufferStatus =
8175 activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
8176 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008177 ALOGV_IF(buffer.frameCount != framesOut,
8178 "%s() read less than expected (%zu vs %zu)",
8179 __func__, buffer.frameCount, framesOut);
8180 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008181 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008182 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
8183 } else {
8184 framesOut = 0;
8185 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008186 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008187 }
8188 } else {
8189 // process frames from the RecordThread buffer provider to the RecordTrack
8190 // buffer
8191 framesOut = activeTrack->mRecordBufferConverter->convert(
8192 activeTrack->mSink.raw,
8193 activeTrack->mResamplerBufferProvider,
8194 framesOut);
8195 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008196
8197 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8198 overrun = OVERRUN_FALSE;
8199 }
8200
Andy Hung93bb5732023-05-04 21:16:34 -07008201 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8202 const ssize_t framesToDrop =
8203 activeTrack->mSynchronizedRecordState.updateRecordFrames(framesOut);
8204 if (framesToDrop == 0) {
8205 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008206 if (framesOut > 0) {
8207 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008208 // Sanitize before releasing if the track has no access to the source data
8209 // An idle UID receives silence from non virtual devices until active
8210 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07008211 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008212 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008213 activeTrack->releaseBuffer(&activeTrack->mSink);
8214 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008215 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008216 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008217 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008218 }
8219 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008220
8221 switch (overrun) {
8222 case OVERRUN_TRUE:
8223 // client isn't retrieving buffers fast enough
8224 if (!activeTrack->setOverflow()) {
8225 nsecs_t now = systemTime();
8226 // FIXME should lastWarning per track?
8227 if ((now - lastWarning) > kWarningThrottleNs) {
8228 ALOGW("RecordThread: buffer overflow");
8229 lastWarning = now;
8230 }
8231 }
8232 break;
8233 case OVERRUN_FALSE:
8234 activeTrack->clearOverflow();
8235 break;
8236 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008237 break;
8238 }
8239
Andy Hung3f0c9022016-01-15 17:49:46 -08008240 // update frame information and push timestamp out
8241 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08008242 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008243 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8244 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008245 }
8246
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008247unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008248 // enable changes in effect chain
8249 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008250 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008251 if (audio_has_proportional_frames(mFormat)
8252 && loopCount == lastLoopCountRead + 1) {
8253 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8254 const double jitterMs =
8255 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8256 {framesRead, readPeriodNs},
8257 {0, 0} /* lastTimestamp */, mSampleRate);
8258 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8259
8260 Mutex::Autolock _l(mLock);
8261 mIoJitterMs.add(jitterMs);
8262 mProcessTimeMs.add(processMs);
8263 }
8264 // update timing info.
8265 mLastIoBeginNs = lastIoBeginNs;
8266 mLastIoEndNs = lastIoEndNs;
8267 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008268 }
8269
Glenn Kasten93e471f2013-08-19 08:40:07 -07008270 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008271
8272 {
8273 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07008274 for (size_t i = 0; i < mTracks.size(); i++) {
8275 sp<RecordTrack> track = mTracks[i];
8276 track->invalidate();
8277 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008278 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08008279 mStartStopCond.broadcast();
8280 }
8281
8282 releaseWakeLock();
8283
8284 ALOGV("RecordThread %p exiting", this);
8285 return false;
8286}
8287
Glenn Kasten93e471f2013-08-19 08:40:07 -07008288void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008289{
8290 if (!mStandby) {
8291 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008292 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008293 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008294 mStandby = true;
8295 }
8296}
8297
8298void AudioFlinger::RecordThread::inputStandBy()
8299{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008300 // Idle the fast capture if it's currently running
8301 if (mFastCapture != 0) {
8302 FastCaptureStateQueue *sq = mFastCapture->sq();
8303 FastCaptureState *state = sq->begin();
8304 if (!(state->mCommand & FastCaptureState::IDLE)) {
8305 state->mCommand = FastCaptureState::COLD_IDLE;
8306 state->mColdFutexAddr = &mFastCaptureFutex;
8307 state->mColdGen++;
8308 mFastCaptureFutex = 0;
8309 sq->end();
8310 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8311 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8312#if 0
8313 if (kUseFastCapture == FastCapture_Dynamic) {
8314 // FIXME
8315 }
8316#endif
8317#ifdef AUDIO_WATCHDOG
8318 // FIXME
8319#endif
8320 } else {
8321 sq->end(false /*didModify*/);
8322 }
8323 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008324 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008325 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008326
8327 // If going into standby, flush the pipe source.
8328 if (mPipeSource.get() != nullptr) {
8329 const ssize_t flushed = mPipeSource->flush();
8330 if (flushed > 0) {
8331 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8332 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8333 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8334 }
8335 }
Eric Laurent81784c32012-11-19 14:55:58 -08008336}
8337
Glenn Kasten05997e22014-03-13 15:08:33 -07008338// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008339sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008340 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008341 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008342 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008343 audio_format_t format,
8344 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008345 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008346 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008347 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008348 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008349 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008350 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008351 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008352 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008353 audio_port_handle_t portId,
8354 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008355{
Glenn Kasten74935e42013-12-19 08:56:45 -08008356 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008357 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008358 sp<RecordTrack> track;
8359 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008360 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008361 audio_input_flags_t requestedFlags = *flags;
8362 uint32_t sampleRate;
8363
8364 lStatus = initCheck();
8365 if (lStatus != NO_ERROR) {
8366 ALOGE("createRecordTrack_l() audio driver not initialized");
8367 goto Exit;
8368 }
8369
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008370 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8371 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8372 lStatus = BAD_VALUE;
8373 goto Exit;
8374 }
8375
Eric Laurentec376dc2021-04-08 20:41:22 +02008376 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008377 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008378 lStatus = PERMISSION_DENIED;
8379 goto Exit;
8380 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008381 if (maxSharedAudioHistoryMs < 0
8382 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8383 lStatus = BAD_VALUE;
8384 goto Exit;
8385 }
8386 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008387 if (*pSampleRate == 0) {
8388 *pSampleRate = mSampleRate;
8389 }
8390 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008391
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008392 // special case for FAST flag considered OK if fast capture is present and access to
8393 // audio history is not required
8394 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008395 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8396 }
8397
Eric Laurentf14db3c2017-12-08 14:20:36 -08008398 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008399 if ((*flags & inputFlags) != *flags) {
8400 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8401 " input flags (%08x)",
8402 *flags, inputFlags);
8403 *flags = (audio_input_flags_t)(*flags & inputFlags);
8404 }
Eric Laurent81784c32012-11-19 14:55:58 -08008405
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008406 // client expresses a preference for FAST and no access to audio history,
8407 // but we get the final say
8408 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008409 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008410 // we formerly checked for a callback handler (non-0 tid),
8411 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008412 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008413 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008414 // Frame count is not specified (0), or is less than or equal the pipe depth.
8415 // It is OK to provide a higher capacity than requested.
8416 // We will force it to mPipeFramesP2 below.
8417 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008418 // PCM data
8419 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008420 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008421 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008422 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008423 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008424 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008425 hasFastCapture() &&
8426 // there are sufficient fast track slots available
8427 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008428 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008429 // check compatibility with audio effects.
8430 Mutex::Autolock _l(mLock);
8431 // Do not accept FAST flag if the session has software effects
8432 sp<EffectChain> chain = getEffectChain_l(sessionId);
8433 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008434 audio_input_flags_t old = *flags;
8435 chain->checkInputFlagCompatibility(flags);
8436 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008437 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8438 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008439 }
8440 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008441 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008442 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8443 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008444 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008445 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8446 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008447 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008448 this, frameCount, mFrameCount, mPipeFramesP2,
8449 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008450 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008451 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008452 }
8453 }
8454
Eric Laurentf14db3c2017-12-08 14:20:36 -08008455 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8456 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8457 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8458 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8459 lStatus = BAD_TYPE;
8460 goto Exit;
8461 }
8462
Glenn Kasten74105912014-07-03 12:28:53 -07008463 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008464 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008465 // fast track: frame count is exactly the pipe depth
8466 frameCount = mPipeFramesP2;
8467 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008468 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008469 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008470 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8471 // or 20 ms if there is a fast capture
8472 // TODO This could be a roundupRatio inline, and const
8473 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8474 * sampleRate + mSampleRate - 1) / mSampleRate;
8475 // minimum number of notification periods is at least kMinNotifications,
8476 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8477 static const size_t kMinNotifications = 3;
8478 static const uint32_t kMinMs = 30;
8479 // TODO This could be a roundupRatio inline
8480 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8481 // TODO This could be a roundupRatio inline
8482 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8483 maxNotificationFrames;
8484 const size_t minFrameCount = maxNotificationFrames *
8485 max(kMinNotifications, minNotificationsByMs);
8486 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008487 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8488 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008489 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008490 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008491 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008492 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008493
8494 { // scope for mLock
8495 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008496 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008497 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008498 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008499 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008500 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008501 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008502 }
Eric Laurent81784c32012-11-19 14:55:58 -08008503
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008504 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008505 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008506 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Eric Laurent9ff3e532022-11-10 16:04:44 +01008507 attributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008508 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008509
Glenn Kasten03003332013-08-06 15:40:54 -07008510 lStatus = track->initCheck();
8511 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008512 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008513 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008514 goto Exit;
8515 }
8516 mTracks.add(track);
8517
Eric Laurent05067782016-06-01 18:27:28 -07008518 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008519 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8520 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8521 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008522 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008523 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008524
8525 if (maxSharedAudioHistoryMs != 0) {
8526 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8527 }
Eric Laurent81784c32012-11-19 14:55:58 -08008528 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008529
Eric Laurent81784c32012-11-19 14:55:58 -08008530 lStatus = NO_ERROR;
8531
8532Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008533 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008534 return track;
8535}
8536
8537status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8538 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008539 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008540{
8541 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8542 sp<ThreadBase> strongMe = this;
8543 status_t status = NO_ERROR;
8544
8545 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008546 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008547 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung93bb5732023-05-04 21:16:34 -07008548 recordTrack->mSynchronizedRecordState.startRecording(
8549 mAudioFlinger->createSyncEvent(
8550 event, triggerSession,
8551 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008552 }
8553
8554 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008555 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008556 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008557 if (recordTrack->isInvalid()) {
8558 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008559 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8560 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008561 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008562 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8563 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008564 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8565 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008566 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008567 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008568 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008569 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008570 }
8571 return status;
8572 }
8573
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008574 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8575 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8576 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008577 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008578 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008579 if (recordTrack->isExternalTrack()) {
8580 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008581 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008582 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008583 if (recordTrack->isInvalid()) {
8584 recordTrack->clearSyncStartEvent();
8585 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8586 recordTrack->mState = TrackBase::STARTING_2;
8587 // STARTING_2 forces destroy to call stopInput.
8588 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008589 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8590 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008591 }
8592 if (recordTrack->mState != TrackBase::STARTING_1) {
8593 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008594 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008595 // Someone else has changed state, let them take over,
8596 // leave mState in the new state.
8597 recordTrack->clearSyncStartEvent();
8598 return INVALID_OPERATION;
8599 }
8600 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008601 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008602 ALOGW("%s(%d): startInput failed, status %d",
8603 __func__, recordTrack->id(), status);
8604 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8605 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008606 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008607 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008608 return status;
8609 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008610 sendIoConfigEvent_l(
8611 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008612 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008613
8614 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8615
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008616 // Catch up with current buffer indices if thread is already running.
8617 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8618 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8619 // see previously buffered data before it called start(), but with greater risk of overrun.
8620
Andy Hung73c02e42015-03-29 01:13:58 -07008621 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008622 if (!recordTrack->isDirect()) {
8623 // clear any converter state as new data will be discontinuous
8624 recordTrack->mRecordBufferConverter->reset();
8625 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008626 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008627 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008628 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008629 return status;
8630 }
Eric Laurent81784c32012-11-19 14:55:58 -08008631}
8632
Andy Hung068e08e2023-05-15 19:02:55 -07008633void AudioFlinger::RecordThread::syncStartEventCallback(const wp<audioflinger::SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008634{
Andy Hung068e08e2023-05-15 19:02:55 -07008635 sp<audioflinger::SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008636
8637 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008638 sp<RefBase> ptr = strongEvent->cookie().promote();
8639 if (ptr != 0) {
8640 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8641 recordTrack->handleSyncStartEvent(strongEvent);
8642 }
Eric Laurent81784c32012-11-19 14:55:58 -08008643 }
8644}
8645
Glenn Kastena8356f62013-07-25 14:37:52 -07008646bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008647 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008648 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008649 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008650 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008651 return false;
8652 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008653 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008654 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008655
Andy Hungabfab202019-03-07 19:45:54 -08008656 // NOTE: Waiting here is important to keep stop synchronous.
8657 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008658 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8659 mWaitWorkCV.broadcast(); // signal thread to stop
8660 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008661 }
Andy Hungce685402018-10-05 17:23:27 -07008662
8663 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008664 ALOGV("Record stopped OK");
8665 return true;
8666 }
Andy Hungce685402018-10-05 17:23:27 -07008667
8668 // don't handle anything - we've been invalidated or restarted and in a different state
8669 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8670 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008671 return false;
8672}
8673
Andy Hung068e08e2023-05-15 19:02:55 -07008674bool AudioFlinger::RecordThread::isValidSyncEvent(
8675 const sp<audioflinger::SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08008676{
8677 return false;
8678}
8679
Andy Hung068e08e2023-05-15 19:02:55 -07008680status_t AudioFlinger::RecordThread::setSyncEvent(
8681 const sp<audioflinger::SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008682{
8683#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8684 if (!isValidSyncEvent(event)) {
8685 return BAD_VALUE;
8686 }
8687
Glenn Kastend848eb42016-03-08 13:42:11 -08008688 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008689 status_t ret = NAME_NOT_FOUND;
8690
8691 Mutex::Autolock _l(mLock);
8692
8693 for (size_t i = 0; i < mTracks.size(); i++) {
8694 sp<RecordTrack> track = mTracks[i];
8695 if (eventSession == track->sessionId()) {
8696 (void) track->setSyncEvent(event);
8697 ret = NO_ERROR;
8698 }
8699 }
8700 return ret;
8701#else
8702 return BAD_VALUE;
8703#endif
8704}
8705
jiabin653cc0a2018-01-17 17:54:10 -08008706status_t AudioFlinger::RecordThread::getActiveMicrophones(
Mikhail Naganov2a6a3012023-02-13 11:45:03 -08008707 std::vector<media::MicrophoneInfoFw>* activeMicrophones)
jiabin653cc0a2018-01-17 17:54:10 -08008708{
8709 ALOGV("RecordThread::getActiveMicrophones");
8710 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008711 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008712 return NO_INIT;
8713 }
jiabin9ff780e2018-03-19 18:19:52 -07008714 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8715 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008716}
8717
Paul McLean12340082019-03-19 09:35:05 -06008718status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8719 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008720{
Paul McLean12340082019-03-19 09:35:05 -06008721 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008722 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008723 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008724 return NO_INIT;
8725 }
Paul McLean12340082019-03-19 09:35:05 -06008726 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008727}
8728
Paul McLean12340082019-03-19 09:35:05 -06008729status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008730{
Paul McLean12340082019-03-19 09:35:05 -06008731 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008732 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008733 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008734 return NO_INIT;
8735 }
Paul McLean12340082019-03-19 09:35:05 -06008736 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008737}
8738
Eric Laurentec376dc2021-04-08 20:41:22 +02008739status_t AudioFlinger::RecordThread::shareAudioHistory(
8740 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8741 int64_t sharedAudioStartMs) {
8742 AutoMutex _l(mLock);
8743 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8744}
8745
8746status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8747 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8748 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008749
Eric Laurentec376dc2021-04-08 20:41:22 +02008750 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8751 return BAD_VALUE;
8752 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008753
8754 if (sharedAudioStartMs < 0
8755 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008756 return BAD_VALUE;
8757 }
8758
Eric Laurent2407ce32021-04-26 14:56:03 +02008759 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8760 // As we cannot detect more than one wraparound, only accept values up current write position
8761 // after one wraparound
8762 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8763 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008764 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008765 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8766 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008767 // Bring the start frame position within the input buffer to match the documented
8768 // "best effort" behavior of the API.
8769 if (sharedOffset < 0) {
8770 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07008771 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008772 sharedAudioStartFrames =
8773 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008774 }
8775
Eric Laurentec376dc2021-04-08 20:41:22 +02008776 mSharedAudioPackageName = sharedAudioPackageName;
8777 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008778 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008779 } else {
8780 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008781 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008782 }
8783 return NO_ERROR;
8784}
8785
Eric Laurent92d0a322021-07-16 15:32:33 +02008786void AudioFlinger::RecordThread::resetAudioHistory_l() {
8787 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8788 mSharedAudioStartFrames = -1;
8789 mSharedAudioPackageName = "";
8790}
8791
Kevin Rocard069c2712018-03-29 19:09:14 -07008792void AudioFlinger::RecordThread::updateMetadata_l()
8793{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008794 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8795 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008796 }
8797 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02008798 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07008799 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02008800 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07008801 }
8802 mInput->stream->updateSinkMetadata(metadata);
8803}
8804
Eric Laurent81784c32012-11-19 14:55:58 -08008805// destroyTrack_l() must be called with ThreadBase::mLock held
8806void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8807{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008808 track->terminate();
8809 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008810
Eric Laurent81784c32012-11-19 14:55:58 -08008811 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008812 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008813 removeTrack_l(track);
8814 }
8815}
8816
8817void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8818{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008819 String8 result;
8820 track->appendDump(result, false /* active */);
8821 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8822
Eric Laurent81784c32012-11-19 14:55:58 -08008823 mTracks.remove(track);
8824 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008825 if (track->isFastTrack()) {
8826 ALOG_ASSERT(!mFastTrackAvail);
8827 mFastTrackAvail = true;
8828 }
Eric Laurent81784c32012-11-19 14:55:58 -08008829}
8830
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008831void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008832{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008833 AudioStreamIn *input = mInput;
8834 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8835 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008836 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008837 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008838 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008839 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008840 }
Andy Hungbfa64962017-06-12 14:43:19 -07008841
8842 if (input != nullptr) {
8843 dprintf(fd, " Hal stream dump:\n");
8844 (void)input->stream->dump(fd);
8845 }
8846
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008847 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008848 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008849
Glenn Kasten2f90c512015-12-02 11:40:09 -08008850 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8851 // while we are dumping it. It may be inconsistent, but it won't mutate!
8852 // This is a large object so we place it on the heap.
8853 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008854 const std::unique_ptr<FastCaptureDumpState> copy =
8855 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008856 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008857}
8858
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008859void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008860{
Eric Laurent81784c32012-11-19 14:55:58 -08008861 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008862 size_t numtracks = mTracks.size();
8863 size_t numactive = mActiveTracks.size();
8864 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008865 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008866 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008867 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008868 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008869 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008870 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008871 for (size_t i = 0; i < numtracks ; ++i) {
8872 sp<RecordTrack> track = mTracks[i];
8873 if (track != 0) {
8874 bool active = mActiveTracks.indexOf(track) >= 0;
8875 if (active) {
8876 numactiveseen++;
8877 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008878 result.append(prefix);
8879 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008880 }
Eric Laurent81784c32012-11-19 14:55:58 -08008881 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008882 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008883 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008884 }
8885
Marco Nelissenb2208842014-02-07 14:00:50 -08008886 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008887 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008888 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008889 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008890 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008891 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008892 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008893 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008894 result.append(prefix);
8895 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008896 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008897 }
Eric Laurent81784c32012-11-19 14:55:58 -08008898
8899 }
8900 write(fd, result.string(), result.size());
8901}
8902
Eric Laurent5ada82e2019-08-29 17:53:54 -07008903void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008904{
8905 Mutex::Autolock _l(mLock);
8906 for (size_t i = 0; i < mTracks.size() ; i++) {
8907 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008908 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008909 track->setSilenced(silenced);
8910 }
8911 }
8912}
Andy Hung73c02e42015-03-29 01:13:58 -07008913
8914void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8915{
8916 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8917 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008918 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008919 const int32_t rear = recordThread->mRsmpInRear;
8920 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008921 if (mRecordTrack->startFrames() >= 0) {
8922 int32_t startFrames = mRecordTrack->startFrames();
8923 // Accept a recent wraparound of mRsmpInRear
8924 if (startFrames <= rear) {
8925 deltaFrames = rear - startFrames;
8926 } else {
8927 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008928 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008929 // start frame cannot be further in the past than start of resampling buffer
8930 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8931 deltaFrames = recordThread->mRsmpInFrames;
8932 }
8933 }
8934 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008935}
8936
8937void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8938 size_t *framesAvailable, bool *hasOverrun)
8939{
8940 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8941 RecordThread *recordThread = (RecordThread *) threadBase.get();
8942 const int32_t rear = recordThread->mRsmpInRear;
8943 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008944 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008945
8946 size_t framesIn;
8947 bool overrun = false;
8948 if (filled < 0) {
8949 // should not happen, but treat like a massive overrun and re-sync
8950 framesIn = 0;
8951 mRsmpInFront = rear;
8952 overrun = true;
8953 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8954 framesIn = (size_t) filled;
8955 } else {
8956 // client is not keeping up with server, but give it latest data
8957 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008958 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8959 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008960 overrun = true;
8961 }
8962 if (framesAvailable != NULL) {
8963 *framesAvailable = framesIn;
8964 }
8965 if (hasOverrun != NULL) {
8966 *hasOverrun = overrun;
8967 }
8968}
8969
Eric Laurent81784c32012-11-19 14:55:58 -08008970// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008971status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008972 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008973{
Andy Hung73c02e42015-03-29 01:13:58 -07008974 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008975 if (threadBase == 0) {
8976 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008977 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008978 return NOT_ENOUGH_DATA;
8979 }
8980 RecordThread *recordThread = (RecordThread *) threadBase.get();
8981 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008982 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008983 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008984 // FIXME should not be P2 (don't want to increase latency)
8985 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008986 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008987 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008988
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008989 front &= recordThread->mRsmpInFramesP2 - 1;
8990 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008991 if (part1 > (size_t) filled) {
8992 part1 = filled;
8993 }
8994 size_t ask = buffer->frameCount;
8995 ALOG_ASSERT(ask > 0);
8996 if (part1 > ask) {
8997 part1 = ask;
8998 }
8999 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009000 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009001 buffer->raw = NULL;
9002 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009003 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009004 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009005 }
9006
Andy Hung57446612015-04-19 23:56:46 -07009007 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009008 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009009 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009010 return NO_ERROR;
9011}
9012
9013// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009014void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
9015 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009016{
Hongwei Wang95e37682019-04-12 11:13:36 -07009017 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009018 if (stepCount == 0) {
9019 return;
9020 }
Andy Hung73c02e42015-03-29 01:13:58 -07009021 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
9022 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009023 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009024 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009025 buffer->frameCount = 0;
9026}
9027
Eric Laurentd8365c52017-07-16 15:27:05 -07009028void AudioFlinger::RecordThread::checkBtNrec()
9029{
9030 Mutex::Autolock _l(mLock);
9031 checkBtNrec_l();
9032}
9033
9034void AudioFlinger::RecordThread::checkBtNrec_l()
9035{
9036 // disable AEC and NS if the device is a BT SCO headset supporting those
9037 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009038 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07009039 mAudioFlinger->btNrecIsOff();
9040 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9041 for (size_t i = 0; i < mEffectChains.size(); i++) {
9042 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9043 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9044 }
9045 }
9046}
9047
Andy Hung97a893e2015-03-29 01:03:07 -07009048
Eric Laurent10351942014-05-08 18:49:52 -07009049bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
9050 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009051{
9052 bool reconfig = false;
9053
Eric Laurent10351942014-05-08 18:49:52 -07009054 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009055
Eric Laurent10351942014-05-08 18:49:52 -07009056 audio_format_t reqFormat = mFormat;
9057 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009058 // 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 +08009059 [[maybe_unused]] audio_channel_mask_t channelMask =
9060 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009061
9062 AudioParameter param = AudioParameter(keyValuePair);
9063 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009064
9065 // scope for AutoPark extends to end of method
9066 AutoPark<FastCapture> park(mFastCapture);
9067
Eric Laurent10351942014-05-08 18:49:52 -07009068 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9069 // channel count change can be requested. Do we mandate the first client defines the
9070 // HAL sampling rate and channel count or do we allow changes on the fly?
9071 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9072 samplingRate = value;
9073 reconfig = true;
9074 }
9075 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009076 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009077 status = BAD_VALUE;
9078 } else {
9079 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009080 reconfig = true;
9081 }
Eric Laurent10351942014-05-08 18:49:52 -07009082 }
9083 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9084 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009085 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009086 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009087 status = BAD_VALUE;
9088 } else {
9089 channelMask = mask;
9090 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009091 }
Eric Laurent10351942014-05-08 18:49:52 -07009092 }
9093 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9094 // do not accept frame count changes if tracks are open as the track buffer
9095 // size depends on frame count and correct behavior would not be guaranteed
9096 // if frame count is changed after track creation
9097 if (mActiveTracks.size() > 0) {
9098 status = INVALID_OPERATION;
9099 } else {
9100 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009101 }
Eric Laurent10351942014-05-08 18:49:52 -07009102 }
9103 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009104 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009105 }
9106 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9107 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009108 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009109 }
Glenn Kastene198c362013-08-13 09:13:36 -07009110
Eric Laurent10351942014-05-08 18:49:52 -07009111 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009112 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009113 if (status == INVALID_OPERATION) {
9114 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009115 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009116 }
9117 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009118 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009119 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9120 if (mInput->stream->getAudioProperties(&config) == OK &&
9121 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9122 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009123 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009124 status = NO_ERROR;
9125 }
Eric Laurent81784c32012-11-19 14:55:58 -08009126 }
Eric Laurent10351942014-05-08 18:49:52 -07009127 if (status == NO_ERROR) {
9128 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009129 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009130 }
9131 }
Eric Laurent81784c32012-11-19 14:55:58 -08009132 }
Eric Laurent10351942014-05-08 18:49:52 -07009133
Eric Laurent81784c32012-11-19 14:55:58 -08009134 return reconfig;
9135}
9136
9137String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
9138{
Eric Laurent81784c32012-11-19 14:55:58 -08009139 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009140 if (initCheck() == NO_ERROR) {
9141 String8 out_s8;
9142 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9143 return out_s8;
9144 }
Eric Laurent81784c32012-11-19 14:55:58 -08009145 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009146 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009147}
9148
Mikhail Naganov88536df2021-07-26 17:30:29 -07009149void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009150 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009151 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009152 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009153 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009154 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009155 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009156 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9157 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009158 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009159 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009160 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009161 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009162 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009163 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009164 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009165 break;
9166 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07009167 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009168}
9169
Glenn Kastendeca2ae2014-02-07 10:25:56 -08009170void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009171{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009172 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9173 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009174 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009175 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9176 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009177 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9178 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009179 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009180 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009181 ALOGI("HAL format %#x is not linear pcm", mFormat);
9182 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009183 result = mInput->stream->getFrameSize(&mFrameSize);
9184 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009185 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9186 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009187 result = mInput->stream->getBufferSize(&mBufferSize);
9188 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009189 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009190 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9191 "mBufferSize=%zu, mFrameCount=%zu",
9192 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009193
Eric Laurentec376dc2021-04-08 20:41:22 +02009194 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9195 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009196 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009197
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009198 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9199 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009200
9201 audio_input_flags_t flags = mInput->flags;
9202 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9203 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9204 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9205 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9206 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9207 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9208 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9209 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9210 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009211}
9212
Glenn Kasten5f972c02014-01-13 09:59:31 -08009213uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08009214{
9215 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009216 uint32_t result;
9217 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9218 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009219 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009220 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009221}
9222
Glenn Kastend848eb42016-03-08 13:42:11 -08009223KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009224{
Glenn Kastend848eb42016-03-08 13:42:11 -08009225 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08009226 Mutex::Autolock _l(mLock);
9227 for (size_t j = 0; j < mTracks.size(); ++j) {
9228 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009229 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009230 if (ids.indexOfKey(sessionId) < 0) {
9231 ids.add(sessionId, true);
9232 }
9233 }
9234 return ids;
9235}
9236
9237AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
9238{
9239 Mutex::Autolock _l(mLock);
9240 AudioStreamIn *input = mInput;
9241 mInput = NULL;
9242 return input;
9243}
9244
9245// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009246sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009247{
9248 if (mInput == NULL) {
9249 return NULL;
9250 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009251 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009252}
9253
9254status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
9255{
Eric Laurent81784c32012-11-19 14:55:58 -08009256 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009257 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009258 chain->setInBuffer(NULL);
9259 chain->setOutBuffer(NULL);
9260
9261 checkSuspendOnAddEffectChain_l(chain);
9262
Eric Laurent1b928682014-10-02 19:41:47 -07009263 // make sure enabled pre processing effects state is communicated to the HAL as we
9264 // just moved them to a new input stream.
9265 chain->syncHalEffectsState();
9266
Eric Laurent81784c32012-11-19 14:55:58 -08009267 mEffectChains.add(chain);
9268
9269 return NO_ERROR;
9270}
9271
9272size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
9273{
9274 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009275
9276 for (size_t i = 0; i < mEffectChains.size(); i++) {
9277 if (chain == mEffectChains[i]) {
9278 mEffectChains.removeAt(i);
9279 break;
9280 }
Eric Laurent81784c32012-11-19 14:55:58 -08009281 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009282 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009283}
9284
Eric Laurent1c333e22014-05-20 10:48:17 -07009285status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
9286 audio_patch_handle_t *handle)
9287{
9288 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009289
9290 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009291 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009292 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009293 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009294 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009295 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009296 }
9297
Eric Laurentd8365c52017-07-16 15:27:05 -07009298 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009299
9300 // store new source and send to effects
9301 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9302 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009303 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009304 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009305 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009306 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009307
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009308 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009309 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9310 status = hwDevice->createAudioPatch(patch->num_sources,
9311 patch->sources,
9312 patch->num_sinks,
9313 patch->sinks,
9314 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009315 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009316 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9317 patch->sinks[0].ext.mix.usecase.source,
9318 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009319 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009320 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009321
jiabinc52b1ff2019-10-31 17:20:42 -07009322 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009323 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009324 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009325 }
Eric Laurent296fb132015-05-01 11:38:42 -07009326
Andy Hungc2b11cb2020-04-22 09:04:01 -07009327 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009328 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009329 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009330 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009331 // also dispatch to active AudioRecords
9332 for (const auto &track : mActiveTracks) {
9333 track->logEndInterval();
9334 track->logBeginInterval(pathSourcesAsString);
9335 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009336 return status;
9337}
9338
9339status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9340{
9341 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009342
jiabinc52b1ff2019-10-31 17:20:42 -07009343 mPatch = audio_patch{};
9344 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009345
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009346 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009347 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9348 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009349 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009350 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009351 }
9352 return status;
9353}
9354
jiabinc52b1ff2019-10-31 17:20:42 -07009355void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9356{
wendy lin56aa82b2020-12-02 15:19:55 +08009357 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009358 mOutDevices = outDevices;
9359 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9360 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009361 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009362 }
9363}
9364
Eric Laurentec376dc2021-04-08 20:41:22 +02009365int32_t AudioFlinger::RecordThread::getOldestFront_l()
9366{
9367 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009368 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009369 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009370 int32_t oldestFront = mRsmpInRear;
9371 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009372 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009373 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9374 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009375 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009376 if (filled > maxFilled) {
9377 oldestFront = front;
9378 maxFilled = filled;
9379 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009380 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009381 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009382 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9383 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009384 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009385}
9386
9387void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9388{
9389 if (offset == 0) {
9390 return;
9391 }
9392 for (size_t i = 0; i < mTracks.size(); i++) {
9393 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9394 front = audio_utils::safe_sub_overflow(front, offset);
9395 mTracks[i]->mResamplerBufferProvider->setFront(front);
9396 }
9397}
9398
9399void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9400{
9401 // This is the formula for calculating the temporary buffer size.
9402 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9403 // 1 full output buffer, regardless of the alignment of the available input.
9404 // The value is somewhat arbitrary, and could probably be even larger.
9405 // A larger value should allow more old data to be read after a track calls start(),
9406 // without increasing latency.
9407 //
9408 // Note this is independent of the maximum downsampling ratio permitted for capture.
9409 size_t minRsmpInFrames = mFrameCount * 7;
9410
9411 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9412 // capture history available to another client using the same session ID:
9413 // dimension the resampler input buffer accordingly.
9414
9415 // Get oldest client read position: getOldestFront_l() must be called before altering
9416 // mRsmpInRear, or mRsmpInFrames
9417 int32_t previousFront = getOldestFront_l();
9418 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9419 int32_t previousRear = mRsmpInRear;
9420 mRsmpInRear = 0;
9421
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009422 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9423 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9424 "resizeInputBuffer_l() called with invalid max shared history %d",
9425 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009426 if (maxSharedAudioHistoryMs != 0) {
9427 // resizeInputBuffer_l should never be called with a non zero shared history if the
9428 // buffer was not already allocated
9429 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9430 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9431 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9432 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009433 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009434 return;
9435 }
9436 mRsmpInFrames = rsmpInFrames;
9437 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009438 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009439 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9440 // initialized
9441 if (mRsmpInFrames < minRsmpInFrames) {
9442 mRsmpInFrames = minRsmpInFrames;
9443 }
9444 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9445
9446 // TODO optimize audio capture buffer sizes ...
9447 // Here we calculate the size of the sliding buffer used as a source
9448 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9449 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9450 // be better to have it derived from the pipe depth in the long term.
9451 // The current value is higher than necessary. However it should not add to latency.
9452
9453 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9454 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9455
9456 void *rsmpInBuffer;
9457 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9458 // if posix_memalign fails, will segv here.
9459 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9460
9461 // Copy audio history if any from old buffer before freeing it
9462 if (previousRear != 0) {
9463 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9464 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9465
9466 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9467 previousFront &= previousRsmpInFramesP2 - 1;
9468 size_t part1 = previousRsmpInFramesP2 - previousFront;
9469 if (part1 > (size_t) unread) {
9470 part1 = unread;
9471 }
9472 if (part1 != 0) {
9473 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9474 part1 * mFrameSize);
9475 mRsmpInRear = part1;
9476 part1 = unread - part1;
9477 if (part1 != 0) {
9478 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9479 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9480 mRsmpInRear += part1;
9481 }
9482 }
9483 // Update front for all clients according to new rear
9484 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9485 } else {
9486 mRsmpInRear = 0;
9487 }
9488 free(mRsmpInBuffer);
9489 mRsmpInBuffer = rsmpInBuffer;
9490}
9491
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009492void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009493{
9494 Mutex::Autolock _l(mLock);
9495 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009496 if (record->getSource()) {
9497 mSource = record->getSource();
9498 }
Eric Laurent83b88082014-06-20 18:31:16 -07009499}
9500
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009501void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009502{
9503 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009504 if (mSource == record->getSource()) {
9505 mSource = mInput;
9506 }
Eric Laurent83b88082014-06-20 18:31:16 -07009507 destroyTrack_l(record);
9508}
9509
Mikhail Naganovdc769682018-05-04 15:34:08 -07009510void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009511{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009512 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009513 config->role = AUDIO_PORT_ROLE_SINK;
9514 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9515 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009516 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9517 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9518 config->flags.input = mInput->flags;
9519 }
Eric Laurent83b88082014-06-20 18:31:16 -07009520}
Eric Laurent1c333e22014-05-20 10:48:17 -07009521
Eric Laurent6acd1d42017-01-04 14:23:29 -08009522// ----------------------------------------------------------------------------
9523// Mmap
9524// ----------------------------------------------------------------------------
9525
9526AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9527 : mThread(thread)
9528{
Phil Burk9fabbf82017-08-03 12:02:00 -07009529 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009530}
9531
9532AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9533{
Phil Burk9fabbf82017-08-03 12:02:00 -07009534 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009535}
9536
9537status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9538 struct audio_mmap_buffer_info *info)
9539{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009540 return mThread->createMmapBuffer(minSizeFrames, info);
9541}
9542
9543status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9544{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009545 return mThread->getMmapPosition(position);
9546}
9547
jiabinb7d8c5a2020-08-26 17:24:52 -07009548status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9549 int64_t *timeNanos) {
9550 return mThread->getExternalPosition(position, timeNanos);
9551}
9552
Eric Laurenta54f1282017-07-01 19:39:32 -07009553status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009554 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009555
9556{
jiabind1f1cb62020-03-24 11:57:57 -07009557 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009558}
9559
9560status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9561{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009562 return mThread->stop(handle);
9563}
9564
Eric Laurent18b57012017-02-13 16:23:52 -08009565status_t AudioFlinger::MmapThreadHandle::standby()
9566{
Eric Laurent18b57012017-02-13 16:23:52 -08009567 return mThread->standby();
9568}
9569
Eric Laurent6acd1d42017-01-04 14:23:29 -08009570
9571AudioFlinger::MmapThread::MmapThread(
9572 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009573 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009574 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009575 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009576 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009577 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009578 mActiveTracks(&this->mLocalLog),
9579 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9580 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009581{
Eric Laurent18b57012017-02-13 16:23:52 -08009582 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009583 readHalParameters_l();
9584}
9585
9586AudioFlinger::MmapThread::~MmapThread()
9587{
9588}
9589
9590void AudioFlinger::MmapThread::onFirstRef()
9591{
9592 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9593}
9594
9595void AudioFlinger::MmapThread::disconnect()
9596{
Eric Laurent331679c2018-04-16 17:03:16 -07009597 ActiveTracks<MmapTrack> activeTracks;
9598 {
9599 Mutex::Autolock _l(mLock);
9600 for (const sp<MmapTrack> &t : mActiveTracks) {
9601 activeTracks.add(t);
9602 }
9603 }
9604 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009605 stop(t->portId());
9606 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009607 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009608 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009609 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009610 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009611 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009612 }
9613}
9614
9615
9616void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9617 audio_stream_type_t streamType __unused,
9618 audio_session_t sessionId,
9619 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009620 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009621 audio_port_handle_t portId)
9622{
9623 mAttr = *attr;
9624 mSessionId = sessionId;
9625 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009626 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009627 mPortId = portId;
9628}
9629
9630status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9631 struct audio_mmap_buffer_info *info)
9632{
9633 if (mHalStream == 0) {
9634 return NO_INIT;
9635 }
Eric Laurent18b57012017-02-13 16:23:52 -08009636 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009637 return mHalStream->createMmapBuffer(minSizeFrames, info);
9638}
9639
9640status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9641{
9642 if (mHalStream == 0) {
9643 return NO_INIT;
9644 }
9645 return mHalStream->getMmapPosition(position);
9646}
9647
Eric Laurent331679c2018-04-16 17:03:16 -07009648status_t AudioFlinger::MmapThread::exitStandby()
9649{
9650 status_t ret = mHalStream->start();
9651 if (ret != NO_ERROR) {
9652 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9653 return ret;
9654 }
Andy Hungcf10d742020-04-28 15:38:24 -07009655 if (mStandby) {
9656 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009657 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07009658 mStandby = false;
9659 }
Eric Laurent331679c2018-04-16 17:03:16 -07009660 return NO_ERROR;
9661}
9662
Eric Laurenta54f1282017-07-01 19:39:32 -07009663status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009664 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009665 audio_port_handle_t *handle)
9666{
Eric Laurenta54f1282017-07-01 19:39:32 -07009667 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009668 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009669 if (mHalStream == 0) {
9670 return NO_INIT;
9671 }
9672
9673 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009674
Eric Laurenta54f1282017-07-01 19:39:32 -07009675 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009676 // For the first track, reuse portId and session allocated when the stream was opened.
9677 ret = exitStandby();
9678 if (ret == NO_ERROR) {
9679 acquireWakeLock();
9680 }
9681 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009682 }
9683
9684 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9685
9686 audio_io_handle_t io = mId;
9687 if (isOutput()) {
9688 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9689 config.sample_rate = mSampleRate;
9690 config.channel_mask = mChannelMask;
9691 config.format = mFormat;
9692 audio_stream_type_t stream = streamType();
9693 audio_output_flags_t flags =
9694 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009695 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009696 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009697 bool isSpatialized;
Eric Laurenta54f1282017-07-01 19:39:32 -07009698 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9699 mSessionId,
9700 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009701 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009702 &config,
9703 flags,
9704 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009705 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02009706 &secondaryOutputs,
9707 &isSpatialized);
Kevin Rocard153f92d2018-12-18 18:33:28 -08009708 ALOGD_IF(!secondaryOutputs.empty(),
9709 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009710 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009711 audio_config_base_t config;
9712 config.sample_rate = mSampleRate;
9713 config.channel_mask = mChannelMask;
9714 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009715 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009716 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009717 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009718 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009719 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009720 &config,
9721 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9722 &deviceId,
9723 &portId);
9724 }
9725 // APM should not chose a different input or output stream for the same set of attributes
9726 // and audo configuration
9727 if (ret != NO_ERROR || io != mId) {
9728 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9729 __FUNCTION__, ret, io, mId);
9730 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009731 }
9732
9733 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009734 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009735 } else {
jiabincfc10a42022-06-15 19:26:01 +00009736 {
9737 // Add the track record before starting input so that the silent status for the
9738 // client can be cached.
9739 Mutex::Autolock _l(mLock);
9740 setClientSilencedState_l(portId, false /*silenced*/);
9741 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009742 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009743 }
9744
Eric Laurent331679c2018-04-16 17:03:16 -07009745 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009746 // abort if start is rejected by audio policy manager
9747 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009748 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009749 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009750 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009751 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009752 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009753 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009754 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009755 }
Eric Laurent331679c2018-04-16 17:03:16 -07009756 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009757 } else {
9758 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009759 }
jiabincfc10a42022-06-15 19:26:01 +00009760 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009761 return PERMISSION_DENIED;
9762 }
9763
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009764 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009765 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009766 mChannelMask, mSessionId, isOutput(),
9767 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009768 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +00009769 if (!isOutput()) {
9770 track->setSilenced_l(isClientSilenced_l(portId));
9771 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009772
Eric Laurent4eb58f12018-12-07 16:41:02 -08009773 if (isOutput()) {
9774 // force volume update when a new track is added
9775 mHalVolFloat = -1.0f;
9776 } else if (!track->isSilenced_l()) {
9777 for (const sp<MmapTrack> &t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -07009778 if (t->isSilenced_l()
9779 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009780 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -07009781 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08009782 }
9783 }
9784
9785
Eric Laurent6acd1d42017-01-04 14:23:29 -08009786 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009787 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009788 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009789 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009790 chain->incTrackCnt();
9791 chain->incActiveTrackCnt();
9792 }
9793
Andy Hungc2b11cb2020-04-22 09:04:01 -07009794 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009795 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009796 broadcast_l();
9797
Eric Laurenta54f1282017-07-01 19:39:32 -07009798 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009799
9800 return NO_ERROR;
9801}
9802
9803status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9804{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009805 ALOGV("%s handle %d", __FUNCTION__, handle);
9806
9807 if (mHalStream == 0) {
9808 return NO_INIT;
9809 }
9810
Eric Laurenta54f1282017-07-01 19:39:32 -07009811 if (handle == mPortId) {
9812 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009813 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009814 return NO_ERROR;
9815 }
9816
Eric Laurent331679c2018-04-16 17:03:16 -07009817 Mutex::Autolock _l(mLock);
9818
Eric Laurent6acd1d42017-01-04 14:23:29 -08009819 sp<MmapTrack> track;
9820 for (const sp<MmapTrack> &t : mActiveTracks) {
9821 if (handle == t->portId()) {
9822 track = t;
9823 break;
9824 }
9825 }
9826 if (track == 0) {
9827 return BAD_VALUE;
9828 }
9829
9830 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +00009831 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009832
Eric Laurent331679c2018-04-16 17:03:16 -07009833 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009834 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009835 AudioSystem::stopOutput(track->portId());
9836 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009837 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009838 AudioSystem::stopInput(track->portId());
9839 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009840 }
Eric Laurent331679c2018-04-16 17:03:16 -07009841 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009842
9843 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9844 if (chain != 0) {
9845 chain->decActiveTrackCnt();
9846 chain->decTrackCnt();
9847 }
9848
9849 broadcast_l();
9850
Eric Laurent6acd1d42017-01-04 14:23:29 -08009851 return NO_ERROR;
9852}
9853
Eric Laurent18b57012017-02-13 16:23:52 -08009854status_t AudioFlinger::MmapThread::standby()
9855{
9856 ALOGV("%s", __FUNCTION__);
9857
9858 if (mHalStream == 0) {
9859 return NO_INIT;
9860 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009861 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009862 return INVALID_OPERATION;
9863 }
9864 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009865 if (!mStandby) {
9866 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009867 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -07009868 mStandby = true;
9869 }
Eric Laurent18b57012017-02-13 16:23:52 -08009870 releaseWakeLock();
9871 return NO_ERROR;
9872}
9873
Eric Laurent6acd1d42017-01-04 14:23:29 -08009874
9875void AudioFlinger::MmapThread::readHalParameters_l()
9876{
9877 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9878 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9879 mFormat = mHALFormat;
9880 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9881 result = mHalStream->getFrameSize(&mFrameSize);
9882 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009883 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9884 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009885 result = mHalStream->getBufferSize(&mBufferSize);
9886 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9887 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009888
Andy Hungcf10d742020-04-28 15:38:24 -07009889 // TODO: make a readHalParameters call?
9890 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009891 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9892 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9893 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9894 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9895 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9896 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9897 /*
9898 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9899 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9900 (int32_t)mHapticChannelMask)
9901 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9902 (int32_t)mHapticChannelCount)
9903 */
9904 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9905 formatToString(mHALFormat).c_str())
9906 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9907 (int32_t)mFrameCount) // sic - added HAL
9908 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009909}
9910
9911bool AudioFlinger::MmapThread::threadLoop()
9912{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009913 checkSilentMode_l();
9914
9915 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9916
9917 while (!exitPending())
9918 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009919 Vector< sp<EffectChain> > effectChains;
9920
Andy Hung13850be2019-03-14 11:33:09 -07009921 { // under Thread lock
9922 Mutex::Autolock _l(mLock);
9923
Eric Laurent6acd1d42017-01-04 14:23:29 -08009924 if (mSignalPending) {
9925 // A signal was raised while we were unlocked
9926 mSignalPending = false;
9927 } else {
9928 if (mConfigEvents.isEmpty()) {
9929 // we're about to wait, flush the binder command buffer
9930 IPCThreadState::self()->flushCommands();
9931
9932 if (exitPending()) {
9933 break;
9934 }
9935
Eric Laurent6acd1d42017-01-04 14:23:29 -08009936 // wait until we have something to do...
9937 ALOGV("%s going to sleep", myName.string());
9938 mWaitWorkCV.wait(mLock);
9939 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009940
9941 checkSilentMode_l();
9942
9943 continue;
9944 }
9945 }
9946
9947 processConfigEvents_l();
9948
9949 processVolume_l();
9950
9951 checkInvalidTracks_l();
9952
9953 mActiveTracks.updatePowerState(this);
9954
Kevin Rocard069c2712018-03-29 19:09:14 -07009955 updateMetadata_l();
9956
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009958 } // release Thread lock
9959
Eric Laurent6acd1d42017-01-04 14:23:29 -08009960 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009961 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009962 }
Andy Hung13850be2019-03-14 11:33:09 -07009963
9964 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009965 unlockEffectChains(effectChains);
9966 // Effect chains will be actually deleted here if they were removed from
9967 // mEffectChains list during mixing or effects processing
9968 }
9969
9970 threadLoop_exit();
9971
9972 if (!mStandby) {
9973 threadLoop_standby();
9974 mStandby = true;
9975 }
9976
Eric Laurent6acd1d42017-01-04 14:23:29 -08009977 ALOGV("Thread %p type %d exiting", this, mType);
9978 return false;
9979}
9980
9981// checkForNewParameter_l() must be called with ThreadBase::mLock held
9982bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9983 status_t& status)
9984{
9985 AudioParameter param = AudioParameter(keyValuePair);
9986 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009987 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009989 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009990 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009991 if (sendToHal) {
9992 status = mHalStream->setParameters(keyValuePair);
9993 } else {
9994 status = NO_ERROR;
9995 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009996
9997 return false;
9998}
9999
10000String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
10001{
10002 Mutex::Autolock _l(mLock);
10003 String8 out_s8;
10004 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10005 return out_s8;
10006 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010007 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010008}
10009
Mikhail Naganov88536df2021-07-26 17:30:29 -070010010void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010011 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010012 sp<AudioIoDescriptor> desc;
10013 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010014 switch (event) {
10015 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010016 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010017 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010018 isInput = true;
10019 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010020 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010021 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010022 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010023 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10024 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010025 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010026 case AUDIO_INPUT_CLOSED:
10027 case AUDIO_OUTPUT_CLOSED:
10028 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010029 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010030 break;
10031 }
10032 mAudioFlinger->ioConfigChanged(event, desc, pid);
10033}
10034
10035status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
10036 audio_patch_handle_t *handle)
Andy Hung71ba4b32022-10-06 12:09:49 -070010037NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010038{
10039 status_t status = NO_ERROR;
10040
10041 // store new device and send to effects
10042 audio_devices_t type = AUDIO_DEVICE_NONE;
10043 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010044 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10045 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10046 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010047 if (isOutput()) {
10048 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010049 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10050 && !mAudioHwDev->supportsAudioPatches(),
10051 "Enumerated device type(%#x) must not be used "
10052 "as it does not support audio patches",
10053 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010054 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010055 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10056 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010057 }
10058 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010059 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010060 } else {
10061 type = patch->sources[0].ext.device.type;
10062 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010063 numDevices = mPatch.num_sources;
10064 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010065 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010066 }
10067
10068 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010069 if (isOutput()) {
10070 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10071 } else {
10072 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10073 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010074 }
10075
jiabinc52b1ff2019-10-31 17:20:42 -070010076 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010077 // store new source and send to effects
10078 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10079 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10080 for (size_t i = 0; i < mEffectChains.size(); i++) {
10081 mEffectChains[i]->setAudioSource_l(mAudioSource);
10082 }
10083 }
10084 }
10085
10086 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010087 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10088 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010089 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010090 audio_port_config port;
10091 std::optional<audio_source_t> source;
10092 if (isOutput()) {
10093 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010094 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010095 port = patch->sources[0];
10096 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010097 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010098 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010099 *handle = AUDIO_PATCH_HANDLE_NONE;
10100 }
10101
jiabinc52b1ff2019-10-31 17:20:42 -070010102 if (numDevices == 0 || mDeviceId != deviceId) {
10103 if (isOutput()) {
10104 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10105 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010106 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010107 } else {
10108 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10109 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10110 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010111 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010112 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -070010113 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010114 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -070010115 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116 }
jiabinc52b1ff2019-10-31 17:20:42 -070010117 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010118 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010119 }
10120 return status;
10121}
10122
10123status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
10124{
10125 status_t status = NO_ERROR;
10126
jiabinc52b1ff2019-10-31 17:20:42 -070010127 mPatch = audio_patch{};
10128 mOutDeviceTypeAddrs.clear();
10129 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010130
10131 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10132 supportsAudioPatches : false;
10133
10134 if (supportsAudioPatches) {
10135 status = mHalDevice->releaseAudioPatch(handle);
10136 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010137 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138 }
10139 return status;
10140}
10141
Mikhail Naganovdc769682018-05-04 15:34:08 -070010142void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010143{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010144 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145 if (isOutput()) {
10146 config->role = AUDIO_PORT_ROLE_SOURCE;
10147 config->ext.mix.hw_module = mAudioHwDev->handle();
10148 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10149 } else {
10150 config->role = AUDIO_PORT_ROLE_SINK;
10151 config->ext.mix.hw_module = mAudioHwDev->handle();
10152 config->ext.mix.usecase.source = mAudioSource;
10153 }
10154}
10155
10156status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
10157{
10158 audio_session_t session = chain->sessionId();
10159
10160 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10161 // Attach all tracks with same session ID to this chain.
10162 // indicate all active tracks in the chain
10163 for (const sp<MmapTrack> &track : mActiveTracks) {
10164 if (session == track->sessionId()) {
10165 chain->incTrackCnt();
10166 chain->incActiveTrackCnt();
10167 }
10168 }
10169
10170 chain->setThread(this);
10171 chain->setInBuffer(nullptr);
10172 chain->setOutBuffer(nullptr);
10173 chain->syncHalEffectsState();
10174
10175 mEffectChains.add(chain);
10176 checkSuspendOnAddEffectChain_l(chain);
10177 return NO_ERROR;
10178}
10179
10180size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
10181{
10182 audio_session_t session = chain->sessionId();
10183
10184 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10185
10186 for (size_t i = 0; i < mEffectChains.size(); i++) {
10187 if (chain == mEffectChains[i]) {
10188 mEffectChains.removeAt(i);
10189 // detach all active tracks from the chain
10190 // detach all tracks with same session ID from this chain
10191 for (const sp<MmapTrack> &track : mActiveTracks) {
10192 if (session == track->sessionId()) {
10193 chain->decActiveTrackCnt();
10194 chain->decTrackCnt();
10195 }
10196 }
10197 break;
10198 }
10199 }
10200 return mEffectChains.size();
10201}
10202
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203void AudioFlinger::MmapThread::threadLoop_standby()
10204{
10205 mHalStream->standby();
10206}
10207
10208void AudioFlinger::MmapThread::threadLoop_exit()
10209{
Phil Burk7dce7282017-09-27 13:51:41 -070010210 // Do not call callback->onTearDown() because it is redundant for thread exit
10211 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010212}
10213
Andy Hung068e08e2023-05-15 19:02:55 -070010214status_t AudioFlinger::MmapThread::setSyncEvent(const sp<audioflinger::SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010215{
10216 return BAD_VALUE;
10217}
10218
Andy Hung068e08e2023-05-15 19:02:55 -070010219bool AudioFlinger::MmapThread::isValidSyncEvent(
10220 const sp<audioflinger::SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010221{
10222 return false;
10223}
10224
10225status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
10226 const effect_descriptor_t *desc, audio_session_t sessionId)
10227{
10228 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010229 if (audio_is_global_session(sessionId)) {
10230 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231 desc->name, mThreadName);
10232 return BAD_VALUE;
10233 }
10234
10235 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10236 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10237 desc->name);
10238 return BAD_VALUE;
10239 }
10240 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010241 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10242 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243 return BAD_VALUE;
10244 }
10245
10246 // Only allow effects without processing load or latency
10247 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10248 return BAD_VALUE;
10249 }
10250
jiabineb3bda02020-06-30 14:07:03 -070010251 if (EffectModule::isHapticGenerator(&desc->type)) {
10252 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10253 return BAD_VALUE;
10254 }
10255
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257}
10258
10259void AudioFlinger::MmapThread::checkInvalidTracks_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010260NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mLock
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010262 sp<MmapStreamCallback> callback;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263 for (const sp<MmapTrack> &track : mActiveTracks) {
10264 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010265 callback = mCallback.promote();
10266 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10267 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010268 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010270 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010271 }
10272 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010273 if (callback != 0) {
10274 mLock.unlock();
10275 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10276 mLock.lock();
10277 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278}
10279
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010280void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010281{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010282 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10283 mAttr.content_type, mAttr.usage, mAttr.source);
10284 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010285 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010286 dprintf(fd, " No active clients\n");
10287 }
10288}
10289
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010290void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010292 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010294 dprintf(fd, " %zu Tracks\n", numtracks);
10295 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010297 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010298 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010299 for (size_t i = 0; i < numtracks ; ++i) {
10300 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010301 result.append(prefix);
10302 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010303 }
10304 } else {
10305 dprintf(fd, "\n");
10306 }
10307 write(fd, result.string(), result.size());
10308}
10309
10310AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10311 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010312 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010313 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010315 mStreamVolume(1.0),
10316 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010317 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010318{
10319 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10320 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10321 mMasterVolume = audioFlinger->masterVolume_l();
10322 mMasterMute = audioFlinger->masterMute_l();
10323 if (mAudioHwDev) {
10324 if (mAudioHwDev->canSetMasterVolume()) {
10325 mMasterVolume = 1.0;
10326 }
10327
10328 if (mAudioHwDev->canSetMasterMute()) {
10329 mMasterMute = false;
10330 }
10331 }
10332}
10333
10334void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10335 audio_stream_type_t streamType,
10336 audio_session_t sessionId,
10337 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010338 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339 audio_port_handle_t portId)
10340{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010341 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342 mStreamType = streamType;
10343}
10344
10345AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10346{
10347 Mutex::Autolock _l(mLock);
10348 AudioStreamOut *output = mOutput;
10349 mOutput = NULL;
10350 return output;
10351}
10352
10353void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10354{
10355 Mutex::Autolock _l(mLock);
10356 // Don't apply master volume in SW if our HAL can do it for us.
10357 if (mAudioHwDev &&
10358 mAudioHwDev->canSetMasterVolume()) {
10359 mMasterVolume = 1.0;
10360 } else {
10361 mMasterVolume = value;
10362 }
10363}
10364
10365void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10366{
10367 Mutex::Autolock _l(mLock);
10368 // Don't apply master mute in SW if our HAL can do it for us.
10369 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10370 mMasterMute = false;
10371 } else {
10372 mMasterMute = muted;
10373 }
10374}
10375
10376void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10377{
10378 Mutex::Autolock _l(mLock);
10379 if (stream == mStreamType) {
10380 mStreamVolume = value;
10381 broadcast_l();
10382 }
10383}
10384
10385float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10386{
10387 Mutex::Autolock _l(mLock);
10388 if (stream == mStreamType) {
10389 return mStreamVolume;
10390 }
10391 return 0.0f;
10392}
10393
10394void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10395{
10396 Mutex::Autolock _l(mLock);
10397 if (stream == mStreamType) {
10398 mStreamMute= muted;
10399 broadcast_l();
10400 }
10401}
10402
10403void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10404{
10405 Mutex::Autolock _l(mLock);
10406 if (streamType == mStreamType) {
10407 for (const sp<MmapTrack> &track : mActiveTracks) {
10408 track->invalidate();
10409 }
10410 broadcast_l();
10411 }
10412}
10413
10414void AudioFlinger::MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010415NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010416{
10417 float volume;
10418
10419 if (mMasterMute || mStreamMute) {
10420 volume = 0;
10421 } else {
10422 volume = mMasterVolume * mStreamVolume;
10423 }
10424
10425 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426
10427 // Convert volumes from float to 8.24
10428 uint32_t vol = (uint32_t)(volume * (1 << 24));
10429
10430 // Delegate volume control to effect in track effect chain if needed
10431 // only one effect chain can be present on DirectOutputThread, so if
10432 // there is one, the track is connected to it
10433 if (!mEffectChains.isEmpty()) {
10434 mEffectChains[0]->setVolume_l(&vol, &vol);
10435 volume = (float)vol / (1 << 24);
10436 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010437 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010438 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10439 mHalVolFloat = volume; // HW volume control worked, so update value.
10440 mNoCallbackWarningCount = 0;
10441 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010442 sp<MmapStreamCallback> callback = mCallback.promote();
10443 if (callback != 0) {
10444 int channelCount;
10445 if (isOutput()) {
10446 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10447 } else {
10448 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10449 }
10450 Vector<float> values;
10451 for (int i = 0; i < channelCount; i++) {
10452 values.add(volume);
10453 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010454 mHalVolFloat = volume; // SW volume control worked, so update value.
10455 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010456 mLock.unlock();
10457 callback->onVolumeChanged(mChannelMask, values);
10458 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010460 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10461 ALOGW("Could not set MMAP stream volume: no volume callback!");
10462 mNoCallbackWarningCount++;
10463 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010464 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010466 for (const sp<MmapTrack> &track : mActiveTracks) {
10467 track->setMetadataHasChanged();
10468 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 }
10470}
10471
Kevin Rocard069c2712018-03-29 19:09:14 -070010472void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10473{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010474 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10475 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010476 }
10477 StreamOutHalInterface::SourceMetadata metadata;
10478 for (const sp<MmapTrack> &track : mActiveTracks) {
10479 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010480 playback_track_metadata_v7_t trackMetadata;
10481 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010482 .usage = track->attributes().usage,
10483 .content_type = track->attributes().content_type,
10484 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010485 };
10486 trackMetadata.channel_mask = track->channelMask(),
10487 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10488 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010489 }
10490 mOutput->stream->updateSourceMetadata(metadata);
10491}
10492
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10494{
10495 if (!mMasterMute) {
10496 char value[PROPERTY_VALUE_MAX];
10497 if (property_get("ro.audio.silent", value, "0") > 0) {
10498 char *endptr;
10499 unsigned long ul = strtoul(value, &endptr, 0);
10500 if (*endptr == '\0' && ul != 0) {
10501 ALOGD("Silence is golden");
10502 // The setprop command will not allow a property to be changed after
10503 // the first time it is set, so we don't have to worry about un-muting.
10504 setMasterMute_l(true);
10505 }
10506 }
10507 }
10508}
10509
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010510void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10511{
10512 MmapThread::toAudioPortConfig(config);
10513 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10514 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10515 config->flags.output = mOutput->flags;
10516 }
10517}
10518
jiabinb7d8c5a2020-08-26 17:24:52 -070010519status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10520 int64_t *timeNanos)
10521{
10522 if (mOutput == nullptr) {
10523 return NO_INIT;
10524 }
10525 struct timespec timestamp;
10526 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10527 if (status == NO_ERROR) {
10528 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10529 }
10530 return status;
10531}
10532
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010533void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010535 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536
Glenn Kastend3bb6452016-12-05 18:14:37 -080010537 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10538 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010539 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10540}
10541
10542AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10543 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010544 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010545 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010546 mInput(input)
10547{
10548 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10549 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10550}
10551
Eric Laurent331679c2018-04-16 17:03:16 -070010552status_t AudioFlinger::MmapCaptureThread::exitStandby()
10553{
Phil Burkf054fc32018-12-06 09:45:59 -080010554 {
10555 // mInput might have been cleared by clearInput()
10556 Mutex::Autolock _l(mLock);
10557 if (mInput != nullptr && mInput->stream != nullptr) {
10558 mInput->stream->setGain(1.0f);
10559 }
10560 }
Eric Laurent331679c2018-04-16 17:03:16 -070010561 return MmapThread::exitStandby();
10562}
10563
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10565{
10566 Mutex::Autolock _l(mLock);
10567 AudioStreamIn *input = mInput;
10568 mInput = NULL;
10569 return input;
10570}
Kevin Rocard069c2712018-03-29 19:09:14 -070010571
Eric Laurent331679c2018-04-16 17:03:16 -070010572
10573void AudioFlinger::MmapCaptureThread::processVolume_l()
10574{
10575 bool changed = false;
10576 bool silenced = false;
10577
10578 sp<MmapStreamCallback> callback = mCallback.promote();
10579 if (callback == 0) {
10580 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10581 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10582 mNoCallbackWarningCount++;
10583 }
10584 }
10585
10586 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10587 // track is silenced and unmute otherwise
10588 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10589 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10590 changed = true;
10591 silenced = mActiveTracks[i]->isSilenced_l();
10592 }
10593 }
10594
10595 if (changed) {
10596 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10597 }
10598}
10599
Kevin Rocard069c2712018-03-29 19:09:14 -070010600void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10601{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010602 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10603 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010604 }
10605 StreamInHalInterface::SinkMetadata metadata;
10606 for (const sp<MmapTrack> &track : mActiveTracks) {
10607 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010608 record_track_metadata_v7_t trackMetadata;
10609 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010610 .source = track->attributes().source,
10611 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010612 };
10613 trackMetadata.channel_mask = track->channelMask(),
10614 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10615 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010616 }
10617 mInput->stream->updateSinkMetadata(metadata);
10618}
10619
Eric Laurent5ada82e2019-08-29 17:53:54 -070010620void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010621{
10622 Mutex::Autolock _l(mLock);
10623 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010624 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010625 mActiveTracks[i]->setSilenced_l(silenced);
10626 broadcast_l();
10627 }
10628 }
jiabincfc10a42022-06-15 19:26:01 +000010629 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070010630}
10631
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010632void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10633{
10634 MmapThread::toAudioPortConfig(config);
10635 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10636 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10637 config->flags.input = mInput->flags;
10638 }
10639}
10640
jiabinb7d8c5a2020-08-26 17:24:52 -070010641status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10642 uint64_t *position, int64_t *timeNanos)
10643{
10644 if (mInput == nullptr) {
10645 return NO_INIT;
10646 }
10647 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10648}
10649
Glenn Kasten63238ef2015-03-02 15:50:29 -080010650} // namespace android